clang  9.0.0svn
TransEmptyStatementsAndDealloc.cpp
Go to the documentation of this file.
1 //===-- TransEmptyStatementsAndDealloc.cpp - Transformations to ARC mode --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // removeEmptyStatementsAndDealloc:
10 //
11 // Removes empty statements that are leftovers from previous transformations.
12 // e.g for
13 //
14 // [x retain];
15 //
16 // removeRetainReleaseDealloc will leave an empty ";" that removeEmptyStatements
17 // will remove.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "Transforms.h"
22 #include "Internals.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/StmtVisitor.h"
26 
27 using namespace clang;
28 using namespace arcmt;
29 using namespace trans;
30 
32  std::vector<SourceLocation> &MacroLocs,
33  ASTContext &Ctx) {
34  if (!S->hasLeadingEmptyMacro())
35  return false;
36 
37  SourceLocation SemiLoc = S->getSemiLoc();
38  if (SemiLoc.isInvalid() || SemiLoc.isMacroID())
39  return false;
40 
41  if (MacroLocs.empty())
42  return false;
43 
45  std::vector<SourceLocation>::iterator
46  I = std::upper_bound(MacroLocs.begin(), MacroLocs.end(), SemiLoc,
48  --I;
50  AfterMacroLoc = I->getLocWithOffset(getARCMTMacroName().size());
51  assert(AfterMacroLoc.isFileID());
52 
53  if (AfterMacroLoc == SemiLoc)
54  return true;
55 
56  int RelOffs = 0;
57  if (!SM.isInSameSLocAddrSpace(AfterMacroLoc, SemiLoc, &RelOffs))
58  return false;
59  if (RelOffs < 0)
60  return false;
61 
62  // We make the reasonable assumption that a semicolon after 100 characters
63  // means that it is not the next token after our macro. If this assumption
64  // fails it is not critical, we will just fail to clear out, e.g., an empty
65  // 'if'.
66  if (RelOffs - getARCMTMacroName().size() > 100)
67  return false;
68 
69  SourceLocation AfterMacroSemiLoc = findSemiAfterLocation(AfterMacroLoc, Ctx);
70  return AfterMacroSemiLoc == SemiLoc;
71 }
72 
73 namespace {
74 
75 /// Returns true if the statement became empty due to previous
76 /// transformations.
77 class EmptyChecker : public StmtVisitor<EmptyChecker, bool> {
78  ASTContext &Ctx;
79  std::vector<SourceLocation> &MacroLocs;
80 
81 public:
82  EmptyChecker(ASTContext &ctx, std::vector<SourceLocation> &macroLocs)
83  : Ctx(ctx), MacroLocs(macroLocs) { }
84 
85  bool VisitNullStmt(NullStmt *S) {
86  return isEmptyARCMTMacroStatement(S, MacroLocs, Ctx);
87  }
88  bool VisitCompoundStmt(CompoundStmt *S) {
89  if (S->body_empty())
90  return false; // was already empty, not because of transformations.
91  for (auto *I : S->body())
92  if (!Visit(I))
93  return false;
94  return true;
95  }
96  bool VisitIfStmt(IfStmt *S) {
97  if (S->getConditionVariable())
98  return false;
99  Expr *condE = S->getCond();
100  if (!condE)
101  return false;
102  if (hasSideEffects(condE, Ctx))
103  return false;
104  if (!S->getThen() || !Visit(S->getThen()))
105  return false;
106  return !S->getElse() || Visit(S->getElse());
107  }
108  bool VisitWhileStmt(WhileStmt *S) {
109  if (S->getConditionVariable())
110  return false;
111  Expr *condE = S->getCond();
112  if (!condE)
113  return false;
114  if (hasSideEffects(condE, Ctx))
115  return false;
116  if (!S->getBody())
117  return false;
118  return Visit(S->getBody());
119  }
120  bool VisitDoStmt(DoStmt *S) {
121  Expr *condE = S->getCond();
122  if (!condE)
123  return false;
124  if (hasSideEffects(condE, Ctx))
125  return false;
126  if (!S->getBody())
127  return false;
128  return Visit(S->getBody());
129  }
130  bool VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
131  Expr *Exp = S->getCollection();
132  if (!Exp)
133  return false;
134  if (hasSideEffects(Exp, Ctx))
135  return false;
136  if (!S->getBody())
137  return false;
138  return Visit(S->getBody());
139  }
140  bool VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
141  if (!S->getSubStmt())
142  return false;
143  return Visit(S->getSubStmt());
144  }
145 };
146 
147 class EmptyStatementsRemover :
148  public RecursiveASTVisitor<EmptyStatementsRemover> {
149  MigrationPass &Pass;
150 
151 public:
152  EmptyStatementsRemover(MigrationPass &pass) : Pass(pass) { }
153 
154  bool TraverseStmtExpr(StmtExpr *E) {
155  CompoundStmt *S = E->getSubStmt();
157  I = S->body_begin(), E = S->body_end(); I != E; ++I) {
158  if (I != E - 1)
159  check(*I);
160  TraverseStmt(*I);
161  }
162  return true;
163  }
164 
165  bool VisitCompoundStmt(CompoundStmt *S) {
166  for (auto *I : S->body())
167  check(I);
168  return true;
169  }
170 
171  ASTContext &getContext() { return Pass.Ctx; }
172 
173 private:
174  void check(Stmt *S) {
175  if (!S) return;
176  if (EmptyChecker(Pass.Ctx, Pass.ARCMTMacroLocs).Visit(S)) {
177  Transaction Trans(Pass.TA);
178  Pass.TA.removeStmt(S);
179  }
180  }
181 };
182 
183 } // anonymous namespace
184 
185 static bool isBodyEmpty(CompoundStmt *body, ASTContext &Ctx,
186  std::vector<SourceLocation> &MacroLocs) {
187  for (auto *I : body->body())
188  if (!EmptyChecker(Ctx, MacroLocs).Visit(I))
189  return false;
190 
191  return true;
192 }
193 
195  ASTContext &Ctx = pass.Ctx;
196  TransformActions &TA = pass.TA;
198  Selector FinalizeSel =
199  Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
200 
202  impl_iterator;
203  for (impl_iterator I = impl_iterator(DC->decls_begin()),
204  E = impl_iterator(DC->decls_end()); I != E; ++I) {
205  ObjCMethodDecl *DeallocM = nullptr;
206  ObjCMethodDecl *FinalizeM = nullptr;
207  for (auto *MD : I->instance_methods()) {
208  if (!MD->hasBody())
209  continue;
210 
211  if (MD->getMethodFamily() == OMF_dealloc) {
212  DeallocM = MD;
213  } else if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
214  FinalizeM = MD;
215  }
216  }
217 
218  if (DeallocM) {
219  if (isBodyEmpty(DeallocM->getCompoundBody(), Ctx, pass.ARCMTMacroLocs)) {
220  Transaction Trans(TA);
221  TA.remove(DeallocM->getSourceRange());
222  }
223 
224  if (FinalizeM) {
225  Transaction Trans(TA);
226  TA.remove(FinalizeM->getSourceRange());
227  }
228 
229  } else if (FinalizeM) {
230  if (isBodyEmpty(FinalizeM->getCompoundBody(), Ctx, pass.ARCMTMacroLocs)) {
231  Transaction Trans(TA);
232  TA.remove(FinalizeM->getSourceRange());
233  } else {
234  Transaction Trans(TA);
235  TA.replaceText(FinalizeM->getSelectorStartLoc(), "finalize", "dealloc");
236  }
237  }
238  }
239 }
240 
242  EmptyStatementsRemover(pass).TraverseDecl(pass.Ctx.getTranslationUnitDecl());
243 
245 
246  for (unsigned i = 0, e = pass.ARCMTMacroLocs.size(); i != e; ++i) {
247  Transaction Trans(pass.TA);
248  pass.TA.remove(pass.ARCMTMacroLocs[i]);
249  }
250 }
Defines the clang::ASTContext interface.
body_iterator body_end()
Definition: Stmt.h:1313
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Smart pointer class that efficiently represents Objective-C method names.
Expr * getCond()
Definition: Stmt.h:2202
CompoundStmt * getSubStmt()
Definition: Expr.h:3865
Stmt - This represents one statement.
Definition: Stmt.h:65
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1765
Defines the SourceManager interface.
static StringRef getARCMTMacroName()
Definition: Internals.h:172
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1257
SourceLocation findSemiAfterLocation(SourceLocation loc, ASTContext &Ctx, bool IsDecl=false)
&#39;Loc&#39; is the end of a statement range.
Definition: Transforms.cpp:129
bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS, int *RelativeOffset) const
Return true if both LHS and RHS are in the local source location address space or the loaded one...
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
Stmt * getThen()
Definition: Stmt.h:1852
const Stmt * getSubStmt() const
Definition: StmtObjC.h:379
Stmt * getBody()
Definition: Stmt.h:2306
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
IdentifierTable & Idents
Definition: ASTContext.h:566
Selector getNullarySelector(IdentifierInfo *ID)
static bool isBodyEmpty(CompoundStmt *body, ASTContext &Ctx, std::vector< SourceLocation > &MacroLocs)
CompoundStmt * getCompoundBody()
Definition: DeclObjC.h:510
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1278
This represents one expression.
Definition: Expr.h:108
void removeEmptyStatementsAndDeallocFinalize(MigrationPass &pass)
SourceLocation getSelectorStartLoc() const
Definition: DeclObjC.h:288
Stmt * getBody()
Definition: Stmt.h:2214
Compare two source locations.
Expr * getCond()
Definition: Stmt.h:1840
const SourceManager & SM
Definition: Format.cpp:1568
DoStmt - This represents a &#39;do/while&#39; stmt.
Definition: Stmt.h:2281
SelectorTable & Selectors
Definition: ASTContext.h:567
Encodes a location in the source.
body_range body()
Definition: Stmt.h:1311
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1374
Stmt * getElse()
Definition: Stmt.h:1861
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:182
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3849
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclObjC.h:284
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1243
static void cleanupDeallocOrFinalize(MigrationPass &pass)
Dataflow Directional Tag Classes.
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1013
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
bool hasSideEffects(Expr *E, ASTContext &Ctx)
Definition: Transforms.cpp:167
SourceLocation getSemiLoc() const
Definition: Stmt.h:1254
void replaceText(SourceLocation loc, StringRef text, StringRef replacementText)
body_iterator body_begin()
Definition: Stmt.h:1312
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2039
bool isMacroID() const
bool body_empty() const
Definition: Stmt.h:1305
Represents Objective-C&#39;s collection statement.
Definition: StmtObjC.h:23
std::vector< SourceLocation > & ARCMTMacroLocs
Definition: Internals.h:152
SourceManager & getSourceManager()
Definition: ASTContext.h:662
Expr * getCond()
Definition: Stmt.h:2299
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:856
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1004
TransformActions & TA
Definition: Internals.h:150
void remove(SourceRange range)
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:2153
static bool isEmptyARCMTMacroStatement(NullStmt *S, std::vector< SourceLocation > &MacroLocs, ASTContext &Ctx)
Represents Objective-C&#39;s @autoreleasepool Statement.
Definition: StmtObjC.h:368
This class handles loading and caching of source files into memory.
decl_iterator decls_end() const
Definition: DeclBase.h:2021