clang  3.7.0
BodyFarm.cpp
Go to the documentation of this file.
1 //== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- C++ -*-//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // BodyFarm is a factory for creating faux implementations for functions/methods
11 // for analysis purposes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "BodyFarm.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprObjC.h"
21 #include "llvm/ADT/StringSwitch.h"
22 
23 using namespace clang;
24 
25 //===----------------------------------------------------------------------===//
26 // Helper creation functions for constructing faux ASTs.
27 //===----------------------------------------------------------------------===//
28 
29 static bool isDispatchBlock(QualType Ty) {
30  // Is it a block pointer?
31  const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
32  if (!BPT)
33  return false;
34 
35  // Check if the block pointer type takes no arguments and
36  // returns void.
37  const FunctionProtoType *FT =
39  if (!FT || !FT->getReturnType()->isVoidType() || FT->getNumParams() != 0)
40  return false;
41 
42  return true;
43 }
44 
45 namespace {
46 class ASTMaker {
47 public:
48  ASTMaker(ASTContext &C) : C(C) {}
49 
50  /// Create a new BinaryOperator representing a simple assignment.
51  BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
52 
53  /// Create a new BinaryOperator representing a comparison.
54  BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
56 
57  /// Create a new compound stmt using the provided statements.
58  CompoundStmt *makeCompound(ArrayRef<Stmt*>);
59 
60  /// Create a new DeclRefExpr for the referenced variable.
61  DeclRefExpr *makeDeclRefExpr(const VarDecl *D);
62 
63  /// Create a new UnaryOperator representing a dereference.
64  UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
65 
66  /// Create an implicit cast for an integer conversion.
67  Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
68 
69  /// Create an implicit cast to a builtin boolean type.
70  ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
71 
72  // Create an implicit cast for lvalue-to-rvaluate conversions.
73  ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
74 
75  /// Create an Objective-C bool literal.
76  ObjCBoolLiteralExpr *makeObjCBool(bool Val);
77 
78  /// Create an Objective-C ivar reference.
79  ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
80 
81  /// Create a Return statement.
82  ReturnStmt *makeReturn(const Expr *RetVal);
83 
84 private:
85  ASTContext &C;
86 };
87 }
88 
89 BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
90  QualType Ty) {
91  return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
92  BO_Assign, Ty, VK_RValue,
93  OK_Ordinary, SourceLocation(), false);
94 }
95 
96 BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
98  assert(BinaryOperator::isLogicalOp(Op) ||
100  return new (C) BinaryOperator(const_cast<Expr*>(LHS),
101  const_cast<Expr*>(RHS),
102  Op,
103  C.getLogicalOperationType(),
104  VK_RValue,
105  OK_Ordinary, SourceLocation(), false);
106 }
107 
108 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
109  return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
110 }
111 
112 DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D) {
113  DeclRefExpr *DR =
114  DeclRefExpr::Create(/* Ctx = */ C,
115  /* QualifierLoc = */ NestedNameSpecifierLoc(),
116  /* TemplateKWLoc = */ SourceLocation(),
117  /* D = */ const_cast<VarDecl*>(D),
118  /* RefersToEnclosingVariableOrCapture = */ false,
119  /* NameLoc = */ SourceLocation(),
120  /* T = */ D->getType(),
121  /* VK = */ VK_LValue);
122  return DR;
123 }
124 
125 UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
126  return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
128 }
129 
130 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
132  const_cast<Expr*>(Arg), nullptr, VK_RValue);
133 }
134 
135 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
136  if (Arg->getType() == Ty)
137  return const_cast<Expr*>(Arg);
138 
140  const_cast<Expr*>(Arg), nullptr, VK_RValue);
141 }
142 
143 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
145  const_cast<Expr*>(Arg), nullptr, VK_RValue);
146 }
147 
148 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
149  QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
150  return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
151 }
152 
153 ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
154  const ObjCIvarDecl *IVar) {
155  return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
156  IVar->getType(), SourceLocation(),
157  SourceLocation(), const_cast<Expr*>(Base),
158  /*arrow=*/true, /*free=*/false);
159 }
160 
161 
162 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
163  return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
164  nullptr);
165 }
166 
167 //===----------------------------------------------------------------------===//
168 // Creation functions for faux ASTs.
169 //===----------------------------------------------------------------------===//
170 
171 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
172 
173 /// Create a fake body for dispatch_once.
175  // Check if we have at least two parameters.
176  if (D->param_size() != 2)
177  return nullptr;
178 
179  // Check if the first parameter is a pointer to integer type.
180  const ParmVarDecl *Predicate = D->getParamDecl(0);
181  QualType PredicateQPtrTy = Predicate->getType();
182  const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
183  if (!PredicatePtrTy)
184  return nullptr;
185  QualType PredicateTy = PredicatePtrTy->getPointeeType();
186  if (!PredicateTy->isIntegerType())
187  return nullptr;
188 
189  // Check if the second parameter is the proper block type.
190  const ParmVarDecl *Block = D->getParamDecl(1);
191  QualType Ty = Block->getType();
192  if (!isDispatchBlock(Ty))
193  return nullptr;
194 
195  // Everything checks out. Create a fakse body that checks the predicate,
196  // sets it, and calls the block. Basically, an AST dump of:
197  //
198  // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
199  // if (!*predicate) {
200  // *predicate = 1;
201  // block();
202  // }
203  // }
204 
205  ASTMaker M(C);
206 
207  // (1) Create the call.
208  DeclRefExpr *DR = M.makeDeclRefExpr(Block);
209  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
210  CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
211  SourceLocation());
212 
213  // (2) Create the assignment to the predicate.
214  IntegerLiteral *IL =
215  IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), (uint64_t) 1),
216  C.IntTy, SourceLocation());
217  BinaryOperator *B =
218  M.makeAssignment(
219  M.makeDereference(
220  M.makeLvalueToRvalue(
221  M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
222  PredicateTy),
223  M.makeIntegralCast(IL, PredicateTy),
224  PredicateTy);
225 
226  // (3) Create the compound statement.
227  Stmt *Stmts[] = { B, CE };
228  CompoundStmt *CS = M.makeCompound(Stmts);
229 
230  // (4) Create the 'if' condition.
231  ImplicitCastExpr *LValToRval =
232  M.makeLvalueToRvalue(
233  M.makeDereference(
234  M.makeLvalueToRvalue(
235  M.makeDeclRefExpr(Predicate),
236  PredicateQPtrTy),
237  PredicateTy),
238  PredicateTy);
239 
240  UnaryOperator *UO = new (C) UnaryOperator(LValToRval, UO_LNot, C.IntTy,
242  SourceLocation());
243 
244  // (5) Create the 'if' statement.
245  IfStmt *If = new (C) IfStmt(C, SourceLocation(), nullptr, UO, CS);
246  return If;
247 }
248 
249 /// Create a fake body for dispatch_sync.
251  // Check if we have at least two parameters.
252  if (D->param_size() != 2)
253  return nullptr;
254 
255  // Check if the second parameter is a block.
256  const ParmVarDecl *PV = D->getParamDecl(1);
257  QualType Ty = PV->getType();
258  if (!isDispatchBlock(Ty))
259  return nullptr;
260 
261  // Everything checks out. Create a fake body that just calls the block.
262  // This is basically just an AST dump of:
263  //
264  // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
265  // block();
266  // }
267  //
268  ASTMaker M(C);
269  DeclRefExpr *DR = M.makeDeclRefExpr(PV);
270  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
271  CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
272  SourceLocation());
273  return CE;
274 }
275 
277 {
278  // There are exactly 3 arguments.
279  if (D->param_size() != 3)
280  return nullptr;
281 
282  // Signature:
283  // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
284  // void *__newValue,
285  // void * volatile *__theValue)
286  // Generate body:
287  // if (oldValue == *theValue) {
288  // *theValue = newValue;
289  // return YES;
290  // }
291  // else return NO;
292 
293  QualType ResultTy = D->getReturnType();
294  bool isBoolean = ResultTy->isBooleanType();
295  if (!isBoolean && !ResultTy->isIntegralType(C))
296  return nullptr;
297 
298  const ParmVarDecl *OldValue = D->getParamDecl(0);
299  QualType OldValueTy = OldValue->getType();
300 
301  const ParmVarDecl *NewValue = D->getParamDecl(1);
302  QualType NewValueTy = NewValue->getType();
303 
304  assert(OldValueTy == NewValueTy);
305 
306  const ParmVarDecl *TheValue = D->getParamDecl(2);
307  QualType TheValueTy = TheValue->getType();
308  const PointerType *PT = TheValueTy->getAs<PointerType>();
309  if (!PT)
310  return nullptr;
311  QualType PointeeTy = PT->getPointeeType();
312 
313  ASTMaker M(C);
314  // Construct the comparison.
315  Expr *Comparison =
316  M.makeComparison(
317  M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
318  M.makeLvalueToRvalue(
319  M.makeDereference(
320  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
321  PointeeTy),
322  PointeeTy),
323  BO_EQ);
324 
325  // Construct the body of the IfStmt.
326  Stmt *Stmts[2];
327  Stmts[0] =
328  M.makeAssignment(
329  M.makeDereference(
330  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
331  PointeeTy),
332  M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
333  NewValueTy);
334 
335  Expr *BoolVal = M.makeObjCBool(true);
336  Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
337  : M.makeIntegralCast(BoolVal, ResultTy);
338  Stmts[1] = M.makeReturn(RetVal);
339  CompoundStmt *Body = M.makeCompound(Stmts);
340 
341  // Construct the else clause.
342  BoolVal = M.makeObjCBool(false);
343  RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
344  : M.makeIntegralCast(BoolVal, ResultTy);
345  Stmt *Else = M.makeReturn(RetVal);
346 
347  /// Construct the If.
348  Stmt *If =
349  new (C) IfStmt(C, SourceLocation(), nullptr, Comparison, Body,
350  SourceLocation(), Else);
351 
352  return If;
353 }
354 
356  D = D->getCanonicalDecl();
357 
358  Optional<Stmt *> &Val = Bodies[D];
359  if (Val.hasValue())
360  return Val.getValue();
361 
362  Val = nullptr;
363 
364  if (D->getIdentifier() == nullptr)
365  return nullptr;
366 
367  StringRef Name = D->getName();
368  if (Name.empty())
369  return nullptr;
370 
371  FunctionFarmer FF;
372 
373  if (Name.startswith("OSAtomicCompareAndSwap") ||
374  Name.startswith("objc_atomicCompareAndSwap")) {
376  }
377  else {
378  FF = llvm::StringSwitch<FunctionFarmer>(Name)
379  .Case("dispatch_sync", create_dispatch_sync)
380  .Case("dispatch_once", create_dispatch_once)
381  .Default(nullptr);
382  }
383 
384  if (FF) { Val = FF(C, D); }
385  else if (Injector) { Val = Injector->getBody(D); }
386  return Val.getValue();
387 }
388 
390  const ObjCPropertyDecl *Prop) {
391  // First, find the backing ivar.
392  const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
393  if (!IVar)
394  return nullptr;
395 
396  // Ignore weak variables, which have special behavior.
398  return nullptr;
399 
400  // Look to see if Sema has synthesized a body for us. This happens in
401  // Objective-C++ because the return value may be a C++ class type with a
402  // non-trivial copy constructor. We can only do this if we can find the
403  // @synthesize for this property, though (or if we know it's been auto-
404  // synthesized).
405  const ObjCImplementationDecl *ImplDecl =
407  if (ImplDecl) {
408  for (const auto *I : ImplDecl->property_impls()) {
409  if (I->getPropertyDecl() != Prop)
410  continue;
411 
412  if (I->getGetterCXXConstructor()) {
413  ASTMaker M(Ctx);
414  return M.makeReturn(I->getGetterCXXConstructor());
415  }
416  }
417  }
418 
419  // Sanity check that the property is the same type as the ivar, or a
420  // reference to it, and that it is either an object pointer or trivially
421  // copyable.
422  if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
423  Prop->getType().getNonReferenceType()))
424  return nullptr;
425  if (!IVar->getType()->isObjCLifetimeType() &&
426  !IVar->getType().isTriviallyCopyableType(Ctx))
427  return nullptr;
428 
429  // Generate our body:
430  // return self->_ivar;
431  ASTMaker M(Ctx);
432 
433  const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
434 
435  Expr *loadedIVar =
436  M.makeObjCIvarRef(
437  M.makeLvalueToRvalue(
438  M.makeDeclRefExpr(selfVar),
439  selfVar->getType()),
440  IVar);
441 
442  if (!Prop->getType()->isReferenceType())
443  loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
444 
445  return M.makeReturn(loadedIVar);
446 }
447 
449  // We currently only know how to synthesize property accessors.
450  if (!D->isPropertyAccessor())
451  return nullptr;
452 
453  D = D->getCanonicalDecl();
454 
455  Optional<Stmt *> &Val = Bodies[D];
456  if (Val.hasValue())
457  return Val.getValue();
458  Val = nullptr;
459 
460  const ObjCPropertyDecl *Prop = D->findPropertyDecl();
461  if (!Prop)
462  return nullptr;
463 
464  // For now, we only synthesize getters.
465  if (D->param_size() != 0)
466  return nullptr;
467 
468  Val = createObjCPropertyGetter(C, Prop);
469 
470  return Val.getValue();
471 }
472 
Defines the clang::ASTContext interface.
StringRef getName() const
Definition: Decl.h:168
IdentifierInfo * getIdentifier() const
Definition: Decl.h:163
bool isBooleanType() const
Definition: Type.h:5489
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method's selector.
Definition: DeclObjC.cpp:1174
static bool isDispatchBlock(QualType Ty)
Definition: BodyFarm.cpp:29
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1701
unsigned param_size() const
Definition: DeclObjC.h:348
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1334
bool isVoidType() const
Definition: Type.h:5426
QualType getType() const
Definition: DeclObjC.h:2505
unsigned getNumParams() const
Definition: Type.h:3133
bool isComparisonOp() const
Definition: Expr.h:3008
const ObjCInterfaceDecl * getContainingInterface() const
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1631
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
A C++ nested-name-specifier augmented with source location information.
bool isReferenceType() const
Definition: Type.h:5241
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
QualType getReturnType() const
Definition: Decl.h:1997
bool isLogicalOp() const
Definition: Expr.h:3038
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:367
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:1896
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:95
BinaryOperatorKind
QualType getReturnType() const
Definition: Type.h:2952
bool isObjCLifetimeType() const
Definition: Type.cpp:3561
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2918
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:726
An ordinary object is located at an address in memory.
Definition: Specifiers.h:111
propimpl_range property_impls() const
Definition: DeclObjC.h:2118
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:2516
QualType getType() const
Definition: Decl.h:538
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:826
virtual Stmt * getBody(const FunctionDecl *D)=0
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1737
unsigned param_size() const
Definition: Decl.h:1941
QualType getPointeeType() const
Definition: Type.h:2246
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:1968
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:411
static Stmt * create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:276
static Stmt * createObjCPropertyGetter(ASTContext &Ctx, const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:389
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
static Stmt * create_dispatch_sync(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_sync.
Definition: BodyFarm.cpp:250
CanQualType VoidTy
Definition: ASTContext.h:817
bool isPropertyAccessor() const
Definition: DeclObjC.h:426
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:2424
QualType getPointeeType() const
Definition: Type.h:2139
QualType getType() const
Definition: Expr.h:125
static Stmt * create_dispatch_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_once.
Definition: BodyFarm.cpp:174
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2598
Stmt * getBody(const FunctionDecl *D)
Factory method for creating bodies for ordinary functions.
Definition: BodyFarm.cpp:355
QualType getNonReferenceType() const
Definition: Type.h:5182
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:2581
bool isTriviallyCopyableType(ASTContext &Context) const
Definition: Type.cpp:2053
const T * getAs() const
Definition: Type.h:5555
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1393
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:474
Stmt *(* FunctionFarmer)(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:171
CanQualType IntTy
Definition: ASTContext.h:825
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:99
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2590
bool isIntegralType(ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1602
bool isIntegerType() const
Definition: Type.h:5448