clang  7.0.0svn
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 
16 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/Debug.h"
27 
28 #define DEBUG_TYPE "body-farm"
29 
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Helper creation functions for constructing faux ASTs.
34 //===----------------------------------------------------------------------===//
35 
36 static bool isDispatchBlock(QualType Ty) {
37  // Is it a block pointer?
38  const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
39  if (!BPT)
40  return false;
41 
42  // Check if the block pointer type takes no arguments and
43  // returns void.
44  const FunctionProtoType *FT =
46  return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
47 }
48 
49 namespace {
50 class ASTMaker {
51 public:
52  ASTMaker(ASTContext &C) : C(C) {}
53 
54  /// Create a new BinaryOperator representing a simple assignment.
55  BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
56 
57  /// Create a new BinaryOperator representing a comparison.
58  BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
60 
61  /// Create a new compound stmt using the provided statements.
62  CompoundStmt *makeCompound(ArrayRef<Stmt*>);
63 
64  /// Create a new DeclRefExpr for the referenced variable.
65  DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
66  bool RefersToEnclosingVariableOrCapture = false);
67 
68  /// Create a new UnaryOperator representing a dereference.
69  UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
70 
71  /// Create an implicit cast for an integer conversion.
72  Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
73 
74  /// Create an implicit cast to a builtin boolean type.
75  ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
76 
77  /// Create an implicit cast for lvalue-to-rvaluate conversions.
78  ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
79 
80  /// Make RValue out of variable declaration, creating a temporary
81  /// DeclRefExpr in the process.
83  makeLvalueToRvalue(const VarDecl *Decl,
84  bool RefersToEnclosingVariableOrCapture = false);
85 
86  /// Create an implicit cast of the given type.
87  ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
88  CastKind CK = CK_LValueToRValue);
89 
90  /// Create an Objective-C bool literal.
91  ObjCBoolLiteralExpr *makeObjCBool(bool Val);
92 
93  /// Create an Objective-C ivar reference.
94  ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
95 
96  /// Create a Return statement.
97  ReturnStmt *makeReturn(const Expr *RetVal);
98 
99  /// Create an integer literal expression of the given type.
100  IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
101 
102  /// Create a member expression.
103  MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
104  bool IsArrow = false,
105  ExprValueKind ValueKind = VK_LValue);
106 
107  /// Returns a *first* member field of a record declaration with a given name.
108  /// \return an nullptr if no member with such a name exists.
109  ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
110 
111 private:
112  ASTContext &C;
113 };
114 }
115 
116 BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
117  QualType Ty) {
118  return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
119  BO_Assign, Ty, VK_RValue,
121 }
122 
123 BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
125  assert(BinaryOperator::isLogicalOp(Op) ||
127  return new (C) BinaryOperator(const_cast<Expr*>(LHS),
128  const_cast<Expr*>(RHS),
129  Op,
130  C.getLogicalOperationType(),
131  VK_RValue,
133 }
134 
135 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
137 }
138 
139 DeclRefExpr *ASTMaker::makeDeclRefExpr(
140  const VarDecl *D,
141  bool RefersToEnclosingVariableOrCapture) {
143 
145  C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
146  RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
147  return DR;
148 }
149 
150 UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
151  return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
153  /*CanOverflow*/ false);
154 }
155 
156 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
157  return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
158 }
159 
161 ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
162  bool RefersToEnclosingVariableOrCapture) {
164  return makeLvalueToRvalue(makeDeclRefExpr(Arg,
165  RefersToEnclosingVariableOrCapture),
166  Type);
167 }
168 
169 ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
170  CastKind CK) {
171  return ImplicitCastExpr::Create(C, Ty,
172  /* CastKind=*/ CK,
173  /* Expr=*/ const_cast<Expr *>(Arg),
174  /* CXXCastPath=*/ nullptr,
175  /* ExprValueKind=*/ VK_RValue);
176 }
177 
178 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
179  if (Arg->getType() == Ty)
180  return const_cast<Expr*>(Arg);
181 
182  return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
183  const_cast<Expr*>(Arg), nullptr, VK_RValue);
184 }
185 
186 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
187  return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
188  const_cast<Expr*>(Arg), nullptr, VK_RValue);
189 }
190 
191 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
192  QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
193  return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
194 }
195 
196 ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
197  const ObjCIvarDecl *IVar) {
198  return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
199  IVar->getType(), SourceLocation(),
200  SourceLocation(), const_cast<Expr*>(Base),
201  /*arrow=*/true, /*free=*/false);
202 }
203 
204 
205 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
206  return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
207  nullptr);
208 }
209 
210 IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
211  llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
212  return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
213 }
214 
215 MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
216  bool IsArrow,
217  ExprValueKind ValueKind) {
218 
219  DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
220  return MemberExpr::Create(
221  C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
222  SourceLocation(), MemberDecl, FoundDecl,
224  /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
225  OK_Ordinary);
226 }
227 
228 ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
229 
230  CXXBasePaths Paths(
231  /* FindAmbiguities=*/false,
232  /* RecordPaths=*/false,
233  /* DetectVirtual=*/ false);
234  const IdentifierInfo &II = C.Idents.get(Name);
235  DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
236 
237  DeclContextLookupResult Decls = RD->lookup(DeclName);
238  for (NamedDecl *FoundDecl : Decls)
239  if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
240  return cast<ValueDecl>(FoundDecl);
241 
242  return nullptr;
243 }
244 
245 //===----------------------------------------------------------------------===//
246 // Creation functions for faux ASTs.
247 //===----------------------------------------------------------------------===//
248 
249 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
250 
252  const ParmVarDecl *Callback,
253  ArrayRef<Expr *> CallArgs) {
254 
255  QualType Ty = Callback->getType();
256  DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
257  CastKind CK;
258  if (Ty->isRValueReferenceType()) {
259  CK = CK_LValueToRValue;
260  } else {
261  assert(Ty->isLValueReferenceType());
262  CK = CK_FunctionToPointerDecay;
263  Ty = C.getPointerType(Ty.getNonReferenceType());
264  }
265 
266  return new (C)
267  CallExpr(C, M.makeImplicitCast(Call, Ty.getNonReferenceType(), CK),
268  /*args=*/CallArgs,
269  /*QualType=*/C.VoidTy,
270  /*ExprValueType=*/VK_RValue,
271  /*SourceLocation=*/SourceLocation());
272 }
273 
275  const ParmVarDecl *Callback,
276  CXXRecordDecl *CallbackDecl,
277  ArrayRef<Expr *> CallArgs) {
278  assert(CallbackDecl != nullptr);
279  assert(CallbackDecl->isLambda());
280  FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
281  assert(callOperatorDecl != nullptr);
282 
283  DeclRefExpr *callOperatorDeclRef =
284  DeclRefExpr::Create(/* Ctx =*/ C,
285  /* QualifierLoc =*/ NestedNameSpecifierLoc(),
286  /* TemplateKWLoc =*/ SourceLocation(),
287  const_cast<FunctionDecl *>(callOperatorDecl),
288  /* RefersToEnclosingVariableOrCapture=*/ false,
289  /* NameLoc =*/ SourceLocation(),
290  /* T =*/ callOperatorDecl->getType(),
291  /* VK =*/ VK_LValue);
292 
293  return new (C)
294  CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
295  /*args=*/CallArgs,
296  /*QualType=*/C.VoidTy,
297  /*ExprValueType=*/VK_RValue,
298  /*SourceLocation=*/SourceLocation(), FPOptions());
299 }
300 
301 /// Create a fake body for std::call_once.
302 /// Emulates the following function body:
303 ///
304 /// \code
305 /// typedef struct once_flag_s {
306 /// unsigned long __state = 0;
307 /// } once_flag;
308 /// template<class Callable>
309 /// void call_once(once_flag& o, Callable func) {
310 /// if (!o.__state) {
311 /// func();
312 /// }
313 /// o.__state = 1;
314 /// }
315 /// \endcode
317  DEBUG(llvm::dbgs() << "Generating body for call_once\n");
318 
319  // We need at least two parameters.
320  if (D->param_size() < 2)
321  return nullptr;
322 
323  ASTMaker M(C);
324 
325  const ParmVarDecl *Flag = D->getParamDecl(0);
326  const ParmVarDecl *Callback = D->getParamDecl(1);
327 
328  if (!Callback->getType()->isReferenceType()) {
329  llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
330  return nullptr;
331  }
332  if (!Flag->getType()->isReferenceType()) {
333  llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
334  return nullptr;
335  }
336 
337  QualType CallbackType = Callback->getType().getNonReferenceType();
338 
339  // Nullable pointer, non-null iff function is a CXXRecordDecl.
340  CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
341  QualType FlagType = Flag->getType().getNonReferenceType();
342  auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl());
343 
344  if (!FlagRecordDecl) {
345  DEBUG(llvm::dbgs() << "Flag field is not a record: "
346  << "unknown std::call_once implementation, "
347  << "ignoring the call.\n");
348  return nullptr;
349  }
350 
351  // We initially assume libc++ implementation of call_once,
352  // where the once_flag struct has a field `__state_`.
353  ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
354 
355  // Otherwise, try libstdc++ implementation, with a field
356  // `_M_once`
357  if (!FlagFieldDecl) {
358  FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
359  }
360 
361  if (!FlagFieldDecl) {
362  DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
363  << "std::once_flag struct: unknown std::call_once "
364  << "implementation, ignoring the call.");
365  return nullptr;
366  }
367 
368  bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
369  if (CallbackRecordDecl && !isLambdaCall) {
370  DEBUG(llvm::dbgs() << "Not supported: synthesizing body for functors when "
371  << "body farming std::call_once, ignoring the call.");
372  return nullptr;
373  }
374 
375  SmallVector<Expr *, 5> CallArgs;
376  const FunctionProtoType *CallbackFunctionType;
377  if (isLambdaCall) {
378 
379  // Lambda requires callback itself inserted as a first parameter.
380  CallArgs.push_back(
381  M.makeDeclRefExpr(Callback,
382  /* RefersToEnclosingVariableOrCapture=*/ true));
383  CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
384  ->getType()
386  } else if (!CallbackType->getPointeeType().isNull()) {
387  CallbackFunctionType =
388  CallbackType->getPointeeType()->getAs<FunctionProtoType>();
389  } else {
390  CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
391  }
392 
393  if (!CallbackFunctionType)
394  return nullptr;
395 
396  // First two arguments are used for the flag and for the callback.
397  if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
398  DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
399  << "params passed to std::call_once, "
400  << "ignoring the call\n");
401  return nullptr;
402  }
403 
404  // All arguments past first two ones are passed to the callback,
405  // and we turn lvalues into rvalues if the argument is not passed by
406  // reference.
407  for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
408  const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
409  Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
410  if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
411  QualType PTy = PDecl->getType().getNonReferenceType();
412  ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
413  }
414  CallArgs.push_back(ParamExpr);
415  }
416 
417  CallExpr *CallbackCall;
418  if (isLambdaCall) {
419 
420  CallbackCall = create_call_once_lambda_call(C, M, Callback,
421  CallbackRecordDecl, CallArgs);
422  } else {
423 
424  // Function pointer case.
425  CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
426  }
427 
428  DeclRefExpr *FlagDecl =
429  M.makeDeclRefExpr(Flag,
430  /* RefersToEnclosingVariableOrCapture=*/true);
431 
432 
433  MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
434  assert(Deref->isLValue());
435  QualType DerefType = Deref->getType();
436 
437  // Negation predicate.
438  UnaryOperator *FlagCheck = new (C) UnaryOperator(
439  /* input=*/
440  M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
441  CK_IntegralToBoolean),
442  /* opc=*/ UO_LNot,
443  /* QualType=*/ C.IntTy,
444  /* ExprValueKind=*/ VK_RValue,
445  /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
446  /* CanOverflow*/ false);
447 
448  // Create assignment.
449  BinaryOperator *FlagAssignment = M.makeAssignment(
450  Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
451  DerefType);
452 
453  IfStmt *Out = new (C)
454  IfStmt(C, SourceLocation(),
455  /* IsConstexpr=*/ false,
456  /* init=*/ nullptr,
457  /* var=*/ nullptr,
458  /* cond=*/ FlagCheck,
459  /* then=*/ M.makeCompound({CallbackCall, FlagAssignment}));
460 
461  return Out;
462 }
463 
464 /// Create a fake body for dispatch_once.
466  // Check if we have at least two parameters.
467  if (D->param_size() != 2)
468  return nullptr;
469 
470  // Check if the first parameter is a pointer to integer type.
471  const ParmVarDecl *Predicate = D->getParamDecl(0);
472  QualType PredicateQPtrTy = Predicate->getType();
473  const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
474  if (!PredicatePtrTy)
475  return nullptr;
476  QualType PredicateTy = PredicatePtrTy->getPointeeType();
477  if (!PredicateTy->isIntegerType())
478  return nullptr;
479 
480  // Check if the second parameter is the proper block type.
481  const ParmVarDecl *Block = D->getParamDecl(1);
482  QualType Ty = Block->getType();
483  if (!isDispatchBlock(Ty))
484  return nullptr;
485 
486  // Everything checks out. Create a fakse body that checks the predicate,
487  // sets it, and calls the block. Basically, an AST dump of:
488  //
489  // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
490  // if (*predicate != ~0l) {
491  // *predicate = ~0l;
492  // block();
493  // }
494  // }
495 
496  ASTMaker M(C);
497 
498  // (1) Create the call.
499  CallExpr *CE = new (C) CallExpr(
500  /*ASTContext=*/C,
501  /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
502  /*args=*/None,
503  /*QualType=*/C.VoidTy,
504  /*ExprValueType=*/VK_RValue,
505  /*SourceLocation=*/SourceLocation());
506 
507  // (2) Create the assignment to the predicate.
508  Expr *DoneValue =
509  new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
511  /*CanOverflow*/false);
512 
513  BinaryOperator *B =
514  M.makeAssignment(
515  M.makeDereference(
516  M.makeLvalueToRvalue(
517  M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
518  PredicateTy),
519  M.makeIntegralCast(DoneValue, PredicateTy),
520  PredicateTy);
521 
522  // (3) Create the compound statement.
523  Stmt *Stmts[] = { B, CE };
524  CompoundStmt *CS = M.makeCompound(Stmts);
525 
526  // (4) Create the 'if' condition.
527  ImplicitCastExpr *LValToRval =
528  M.makeLvalueToRvalue(
529  M.makeDereference(
530  M.makeLvalueToRvalue(
531  M.makeDeclRefExpr(Predicate),
532  PredicateQPtrTy),
533  PredicateTy),
534  PredicateTy);
535 
536  Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
537  // (5) Create the 'if' statement.
538  IfStmt *If = new (C) IfStmt(C, SourceLocation(),
539  /* IsConstexpr=*/ false,
540  /* init=*/ nullptr,
541  /* var=*/ nullptr,
542  /* cond=*/ GuardCondition,
543  /* then=*/ CS);
544  return If;
545 }
546 
547 /// Create a fake body for dispatch_sync.
549  // Check if we have at least two parameters.
550  if (D->param_size() != 2)
551  return nullptr;
552 
553  // Check if the second parameter is a block.
554  const ParmVarDecl *PV = D->getParamDecl(1);
555  QualType Ty = PV->getType();
556  if (!isDispatchBlock(Ty))
557  return nullptr;
558 
559  // Everything checks out. Create a fake body that just calls the block.
560  // This is basically just an AST dump of:
561  //
562  // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
563  // block();
564  // }
565  //
566  ASTMaker M(C);
567  DeclRefExpr *DR = M.makeDeclRefExpr(PV);
568  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
569  CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
570  SourceLocation());
571  return CE;
572 }
573 
575 {
576  // There are exactly 3 arguments.
577  if (D->param_size() != 3)
578  return nullptr;
579 
580  // Signature:
581  // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
582  // void *__newValue,
583  // void * volatile *__theValue)
584  // Generate body:
585  // if (oldValue == *theValue) {
586  // *theValue = newValue;
587  // return YES;
588  // }
589  // else return NO;
590 
591  QualType ResultTy = D->getReturnType();
592  bool isBoolean = ResultTy->isBooleanType();
593  if (!isBoolean && !ResultTy->isIntegralType(C))
594  return nullptr;
595 
596  const ParmVarDecl *OldValue = D->getParamDecl(0);
597  QualType OldValueTy = OldValue->getType();
598 
599  const ParmVarDecl *NewValue = D->getParamDecl(1);
600  QualType NewValueTy = NewValue->getType();
601 
602  assert(OldValueTy == NewValueTy);
603 
604  const ParmVarDecl *TheValue = D->getParamDecl(2);
605  QualType TheValueTy = TheValue->getType();
606  const PointerType *PT = TheValueTy->getAs<PointerType>();
607  if (!PT)
608  return nullptr;
609  QualType PointeeTy = PT->getPointeeType();
610 
611  ASTMaker M(C);
612  // Construct the comparison.
613  Expr *Comparison =
614  M.makeComparison(
615  M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
616  M.makeLvalueToRvalue(
617  M.makeDereference(
618  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
619  PointeeTy),
620  PointeeTy),
621  BO_EQ);
622 
623  // Construct the body of the IfStmt.
624  Stmt *Stmts[2];
625  Stmts[0] =
626  M.makeAssignment(
627  M.makeDereference(
628  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
629  PointeeTy),
630  M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
631  NewValueTy);
632 
633  Expr *BoolVal = M.makeObjCBool(true);
634  Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
635  : M.makeIntegralCast(BoolVal, ResultTy);
636  Stmts[1] = M.makeReturn(RetVal);
637  CompoundStmt *Body = M.makeCompound(Stmts);
638 
639  // Construct the else clause.
640  BoolVal = M.makeObjCBool(false);
641  RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
642  : M.makeIntegralCast(BoolVal, ResultTy);
643  Stmt *Else = M.makeReturn(RetVal);
644 
645  /// Construct the If.
646  Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr,
647  Comparison, Body, SourceLocation(), Else);
648 
649  return If;
650 }
651 
653  D = D->getCanonicalDecl();
654 
655  Optional<Stmt *> &Val = Bodies[D];
656  if (Val.hasValue())
657  return Val.getValue();
658 
659  Val = nullptr;
660 
661  if (D->getIdentifier() == nullptr)
662  return nullptr;
663 
664  StringRef Name = D->getName();
665  if (Name.empty())
666  return nullptr;
667 
668  FunctionFarmer FF;
669 
670  if (Name.startswith("OSAtomicCompareAndSwap") ||
671  Name.startswith("objc_atomicCompareAndSwap")) {
673  } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
674  FF = create_call_once;
675  } else {
676  FF = llvm::StringSwitch<FunctionFarmer>(Name)
677  .Case("dispatch_sync", create_dispatch_sync)
678  .Case("dispatch_once", create_dispatch_once)
679  .Default(nullptr);
680  }
681 
682  if (FF) { Val = FF(C, D); }
683  else if (Injector) { Val = Injector->getBody(D); }
684  return Val.getValue();
685 }
686 
687 static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
688  const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
689 
690  if (IVar)
691  return IVar;
692 
693  // When a readonly property is shadowed in a class extensions with a
694  // a readwrite property, the instance variable belongs to the shadowing
695  // property rather than the shadowed property. If there is no instance
696  // variable on a readonly property, check to see whether the property is
697  // shadowed and if so try to get the instance variable from shadowing
698  // property.
699  if (!Prop->isReadOnly())
700  return nullptr;
701 
702  auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
703  const ObjCInterfaceDecl *PrimaryInterface = nullptr;
704  if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
705  PrimaryInterface = InterfaceDecl;
706  } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
707  PrimaryInterface = CategoryDecl->getClassInterface();
708  } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
709  PrimaryInterface = ImplDecl->getClassInterface();
710  } else {
711  return nullptr;
712  }
713 
714  // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
715  // is guaranteed to find the shadowing property, if it exists, rather than
716  // the shadowed property.
717  auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
718  Prop->getIdentifier(), Prop->getQueryKind());
719  if (ShadowingProp && ShadowingProp != Prop) {
720  IVar = ShadowingProp->getPropertyIvarDecl();
721  }
722 
723  return IVar;
724 }
725 
727  const ObjCPropertyDecl *Prop) {
728  // First, find the backing ivar.
729  const ObjCIvarDecl *IVar = findBackingIvar(Prop);
730  if (!IVar)
731  return nullptr;
732 
733  // Ignore weak variables, which have special behavior.
735  return nullptr;
736 
737  // Look to see if Sema has synthesized a body for us. This happens in
738  // Objective-C++ because the return value may be a C++ class type with a
739  // non-trivial copy constructor. We can only do this if we can find the
740  // @synthesize for this property, though (or if we know it's been auto-
741  // synthesized).
742  const ObjCImplementationDecl *ImplDecl =
744  if (ImplDecl) {
745  for (const auto *I : ImplDecl->property_impls()) {
746  if (I->getPropertyDecl() != Prop)
747  continue;
748 
749  if (I->getGetterCXXConstructor()) {
750  ASTMaker M(Ctx);
751  return M.makeReturn(I->getGetterCXXConstructor());
752  }
753  }
754  }
755 
756  // Sanity check that the property is the same type as the ivar, or a
757  // reference to it, and that it is either an object pointer or trivially
758  // copyable.
759  if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
760  Prop->getType().getNonReferenceType()))
761  return nullptr;
762  if (!IVar->getType()->isObjCLifetimeType() &&
763  !IVar->getType().isTriviallyCopyableType(Ctx))
764  return nullptr;
765 
766  // Generate our body:
767  // return self->_ivar;
768  ASTMaker M(Ctx);
769 
770  const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
771  if (!selfVar)
772  return nullptr;
773 
774  Expr *loadedIVar =
775  M.makeObjCIvarRef(
776  M.makeLvalueToRvalue(
777  M.makeDeclRefExpr(selfVar),
778  selfVar->getType()),
779  IVar);
780 
781  if (!Prop->getType()->isReferenceType())
782  loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
783 
784  return M.makeReturn(loadedIVar);
785 }
786 
788  // We currently only know how to synthesize property accessors.
789  if (!D->isPropertyAccessor())
790  return nullptr;
791 
792  D = D->getCanonicalDecl();
793 
794  Optional<Stmt *> &Val = Bodies[D];
795  if (Val.hasValue())
796  return Val.getValue();
797  Val = nullptr;
798 
799  const ObjCPropertyDecl *Prop = D->findPropertyDecl();
800  if (!Prop)
801  return nullptr;
802 
803  // For now, we only synthesize getters.
804  // Synthesizing setters would cause false negatives in the
805  // RetainCountChecker because the method body would bind the parameter
806  // to an instance variable, causing it to escape. This would prevent
807  // warning in the following common scenario:
808  //
809  // id foo = [[NSObject alloc] init];
810  // self.foo = foo; // We should warn that foo leaks here.
811  //
812  if (D->param_size() != 0)
813  return nullptr;
814 
815  Val = createObjCPropertyGetter(C, Prop);
816 
817  return Val.getValue();
818 }
819 
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
Defines the clang::ASTContext interface.
ObjCPropertyQueryKind getQueryKind() const
Definition: DeclObjC.h:898
An instance of this class is created to represent a function declaration or definition.
Definition: Decl.h:1697
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2283
QualType getPointeeType() const
Definition: Type.h:2296
A (possibly-)qualified type.
Definition: Type.h:653
unsigned param_size() const
Definition: DeclObjC.h:379
Stmt - This represents one statement.
Definition: Stmt.h:66
IfStmt - This represents an if/then/else.
Definition: Stmt.h:933
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
bool isLogicalOp() const
Definition: Expr.h:3115
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static Stmt * create_call_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for std::call_once.
Definition: BodyFarm.cpp:316
static CallExpr * create_call_once_funcptr_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, ArrayRef< Expr *> CallArgs)
Definition: BodyFarm.cpp:251
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5891
The base class of the type hierarchy.
Definition: Type.h:1351
CanQualType LongTy
Definition: ASTContext.h:1004
Floating point control options.
Definition: LangOptions.h:208
size_t param_size() const
Definition: Decl.h:2196
static bool isDispatchBlock(QualType Ty)
Definition: BodyFarm.cpp:36
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:806
QualType getReturnType() const
Definition: Decl.h:2220
unsigned getNumParams() const
Definition: Type.h:3489
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6305
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1513
Defines the clang::Expr interface and subclasses for C++ expressions.
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3501
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
One of these records is kept for each identifier that is lexed.
QualType getPointeeType() const
Definition: Type.h:2400
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
A C++ nested-name-specifier augmented with source location information.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1178
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3844
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
bool isReferenceType() const
Definition: Type.h:5954
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:391
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
BinaryOperatorKind
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2166
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:857
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2994
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:316
bool isRValueReferenceType() const
Definition: Type.h:5962
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:880
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1152
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:748
An ordinary object is located at an address in memory.
Definition: Specifiers.h:123
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
Stmt *(* FunctionFarmer)(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:249
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:910
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1523
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:595
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3268
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1718
static const ObjCIvarDecl * findBackingIvar(const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:687
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:627
Expr - This represents one expression.
Definition: Expr.h:106
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:104
Defines an enumeration for C++ overloaded operators.
DeclContext * getDeclContext()
Definition: DeclBase.h:425
ObjCPropertyDecl * FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId, ObjCPropertyQueryKind QueryKind) const
FindPropertyVisibleInPrimaryClass - Finds declaration of the property with name &#39;PropertyId&#39; in the p...
Definition: DeclObjC.cpp:361
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1380
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1594
propimpl_range property_impls() const
Definition: DeclObjC.h:2486
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1417
static Stmt * create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:574
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1717
static Stmt * createObjCPropertyGetter(ASTContext &Ctx, const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:726
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:444
QualType getType() const
Definition: DeclObjC.h:846
bool isComparisonOp() const
Definition: Expr.h:3085
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3201
static Stmt * create_dispatch_sync(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_sync.
Definition: BodyFarm.cpp:548
static CallExpr * create_call_once_lambda_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, CXXRecordDecl *CallbackDecl, ArrayRef< Expr *> CallArgs)
Definition: BodyFarm.cpp:274
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1722
bool isStdNamespace() const
Definition: DeclBase.cpp:1012
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2203
CanQualType VoidTy
Definition: ASTContext.h:996
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:746
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2831
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:249
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1513
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2221
static MemberExpr * Create(const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *memberdecl, DeclAccessPair founddecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *targs, QualType ty, ExprValueKind VK, ExprObjectKind OK)
Definition: Expr.cpp:1437
A POD class for pairing a NamedDecl* with an access specifier.
static Stmt * create_dispatch_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_once.
Definition: BodyFarm.cpp:465
Dataflow Directional Tag Classes.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1121
DeclarationName - The name of a declaration.
bool isBooleanType() const
Definition: Type.h:6232
Stmt * getBody(const FunctionDecl *D)
Factory method for creating bodies for ordinary functions.
Definition: BodyFarm.cpp:652
const ObjCInterfaceDecl * getContainingInterface() const
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1754
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Pointer to a block type.
Definition: Type.h:2385
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2571
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6191
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
bool isLValueReferenceType() const
Definition: Type.h:5958
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method&#39;s selector.
Definition: DeclObjC.cpp:1261
QualType getParamType(unsigned i) const
Definition: Type.h:3491
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2396
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
bool isVoidType() const
Definition: Type.h:6169
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1964
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:962
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2218
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
CanQualType IntTy
Definition: ASTContext.h:1004
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:82
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
QualType getType() const
Definition: Decl.h:638
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2845
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:939
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
bool isPropertyAccessor() const
Definition: DeclObjC.h:459
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:2910
Comparison