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 "clang/Analysis/BodyFarm.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CXXInheritance.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"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/Analysis/CodeInjector.h"
24 #include "clang/Basic/OperatorKinds.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 =
45   BPT->getPointeeType()->getAs<FunctionProtoType>();
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,
59                                  BinaryOperator::Opcode Op);
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.
82   ImplicitCastExpr *
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.
100   IntegerLiteral *makeIntegerLiteral(uint64_t value);
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,
120                                OK_Ordinary, SourceLocation(), FPOptions());
121 }
122 
123 BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
124                                          BinaryOperator::Opcode Op) {
125   assert(BinaryOperator::isLogicalOp(Op) ||
126          BinaryOperator::isComparisonOp(Op));
127   return new (C) BinaryOperator(const_cast<Expr*>(LHS),
128                                 const_cast<Expr*>(RHS),
129                                 Op,
130                                 C.getLogicalOperationType(),
131                                 VK_RValue,
132                                 OK_Ordinary, SourceLocation(), FPOptions());
133 }
134 
135 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
136   return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
137 }
138 
139 DeclRefExpr *ASTMaker::makeDeclRefExpr(
140     const VarDecl *D,
141     bool RefersToEnclosingVariableOrCapture) {
142   QualType Type = D->getType().getNonReferenceType();
143 
144   DeclRefExpr *DR = DeclRefExpr::Create(
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,
152                                VK_LValue, OK_Ordinary, SourceLocation());
153 }
154 
155 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
156   return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
157 }
158 
159 ImplicitCastExpr *
160 ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
161                              bool RefersToEnclosingVariableOrCapture) {
162   QualType Type = Arg->getType().getNonReferenceType();
163   return makeLvalueToRvalue(makeDeclRefExpr(Arg,
164                                             RefersToEnclosingVariableOrCapture),
165                             Type);
166 }
167 
168 ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
169                                              CastKind CK) {
170   return ImplicitCastExpr::Create(C, Ty,
171                                   /* CastKind=*/ CK,
172                                   /* Expr=*/ const_cast<Expr *>(Arg),
173                                   /* CXXCastPath=*/ nullptr,
174                                   /* ExprValueKind=*/ VK_RValue);
175 }
176 
177 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
178   if (Arg->getType() == Ty)
179     return const_cast<Expr*>(Arg);
180 
181   return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
182                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
183 }
184 
185 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
186   return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
187                                   const_cast<Expr*>(Arg), nullptr, VK_RValue);
188 }
189 
190 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
191   QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
192   return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
193 }
194 
195 ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
196                                            const ObjCIvarDecl *IVar) {
197   return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
198                                  IVar->getType(), SourceLocation(),
199                                  SourceLocation(), const_cast<Expr*>(Base),
200                                  /*arrow=*/true, /*free=*/false);
201 }
202 
203 
204 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
205   return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
206                             nullptr);
207 }
208 
209 IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t value) {
210   return IntegerLiteral::Create(C,
211                                 llvm::APInt(
212                                     /*numBits=*/C.getTypeSize(C.IntTy), value),
213                                 /*QualType=*/C.IntTy, SourceLocation());
214 }
215 
216 MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
217                                            bool IsArrow,
218                                            ExprValueKind ValueKind) {
219 
220   DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
221   return MemberExpr::Create(
222       C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
223       SourceLocation(), MemberDecl, FoundDecl,
224       DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
225       /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
226       OK_Ordinary);
227 }
228 
229 ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
230 
231   CXXBasePaths Paths(
232       /* FindAmbiguities=*/false,
233       /* RecordPaths=*/false,
234       /* DetectVirtual=*/ false);
235   const IdentifierInfo &II = C.Idents.get(Name);
236   DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
237 
238   DeclContextLookupResult Decls = RD->lookup(DeclName);
239   for (NamedDecl *FoundDecl : Decls)
240     if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
241       return cast<ValueDecl>(FoundDecl);
242 
243   return nullptr;
244 }
245 
246 //===----------------------------------------------------------------------===//
247 // Creation functions for faux ASTs.
248 //===----------------------------------------------------------------------===//
249 
250 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
251 
252 static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
253                                                const ParmVarDecl *Callback,
254                                                ArrayRef<Expr *> CallArgs) {
255 
256   QualType Ty = Callback->getType();
257   DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
258   CastKind CK;
259   if (Ty->isRValueReferenceType()) {
260     CK = CK_LValueToRValue;
261   } else {
262     assert(Ty->isLValueReferenceType());
263     CK = CK_FunctionToPointerDecay;
264     Ty = C.getPointerType(Ty.getNonReferenceType());
265   }
266 
267   return new (C)
268       CallExpr(C, M.makeImplicitCast(Call, Ty.getNonReferenceType(), CK),
269                /*args=*/CallArgs,
270                /*QualType=*/C.VoidTy,
271                /*ExprValueType=*/VK_RValue,
272                /*SourceLocation=*/SourceLocation());
273 }
274 
275 static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
276                                               const ParmVarDecl *Callback,
277                                               CXXRecordDecl *CallbackDecl,
278                                               ArrayRef<Expr *> CallArgs) {
279   assert(CallbackDecl != nullptr);
280   assert(CallbackDecl->isLambda());
281   FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
282   assert(callOperatorDecl != nullptr);
283 
284   DeclRefExpr *callOperatorDeclRef =
285       DeclRefExpr::Create(/* Ctx =*/ C,
286                           /* QualifierLoc =*/ NestedNameSpecifierLoc(),
287                           /* TemplateKWLoc =*/ SourceLocation(),
288                           const_cast<FunctionDecl *>(callOperatorDecl),
289                           /* RefersToEnclosingVariableOrCapture=*/ false,
290                           /* NameLoc =*/ SourceLocation(),
291                           /* T =*/ callOperatorDecl->getType(),
292                           /* VK =*/ VK_LValue);
293 
294   return new (C)
295       CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
296                           /*args=*/CallArgs,
297                           /*QualType=*/C.VoidTy,
298                           /*ExprValueType=*/VK_RValue,
299                           /*SourceLocation=*/SourceLocation(), FPOptions());
300 }
301 
302 /// Create a fake body for std::call_once.
303 /// Emulates the following function body:
304 ///
305 /// \code
306 /// typedef struct once_flag_s {
307 ///   unsigned long __state = 0;
308 /// } once_flag;
309 /// template<class Callable>
310 /// void call_once(once_flag& o, Callable func) {
311 ///   if (!o.__state) {
312 ///     func();
313 ///   }
314 ///   o.__state = 1;
315 /// }
316 /// \endcode
317 static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
318   DEBUG(llvm::dbgs() << "Generating body for call_once\n");
319 
320   // We need at least two parameters.
321   if (D->param_size() < 2)
322     return nullptr;
323 
324   ASTMaker M(C);
325 
326   const ParmVarDecl *Flag = D->getParamDecl(0);
327   const ParmVarDecl *Callback = D->getParamDecl(1);
328 
329   if (!Callback->getType()->isReferenceType()) {
330     llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
331     return nullptr;
332   }
333   if (!Flag->getType()->isReferenceType()) {
334     llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
335     return nullptr;
336   }
337 
338   QualType CallbackType = Callback->getType().getNonReferenceType();
339 
340   // Nullable pointer, non-null iff function is a CXXRecordDecl.
341   CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
342   QualType FlagType = Flag->getType().getNonReferenceType();
343   auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl());
344 
345   if (!FlagRecordDecl) {
346     DEBUG(llvm::dbgs() << "Flag field is not a record: "
347                        << "unknown std::call_once implementation, "
348                        << "ignoring the call.\n");
349     return nullptr;
350   }
351 
352   // We initially assume libc++ implementation of call_once,
353   // where the once_flag struct has a field `__state_`.
354   ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
355 
356   // Otherwise, try libstdc++ implementation, with a field
357   // `_M_once`
358   if (!FlagFieldDecl) {
359     FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
360   }
361 
362   if (!FlagFieldDecl) {
363     DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
364                        << "std::once_flag struct: unknown std::call_once "
365                        << "implementation, ignoring the call.");
366     return nullptr;
367   }
368 
369   bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
370   if (CallbackRecordDecl && !isLambdaCall) {
371     DEBUG(llvm::dbgs() << "Not supported: synthesizing body for functors when "
372                        << "body farming std::call_once, ignoring the call.");
373     return nullptr;
374   }
375 
376   SmallVector<Expr *, 5> CallArgs;
377   const FunctionProtoType *CallbackFunctionType;
378   if (isLambdaCall) {
379 
380     // Lambda requires callback itself inserted as a first parameter.
381     CallArgs.push_back(
382         M.makeDeclRefExpr(Callback,
383                           /* RefersToEnclosingVariableOrCapture=*/ true));
384     CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
385                                ->getType()
386                                ->getAs<FunctionProtoType>();
387   } else if (!CallbackType->getPointeeType().isNull()) {
388     CallbackFunctionType =
389         CallbackType->getPointeeType()->getAs<FunctionProtoType>();
390   } else {
391     CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
392   }
393 
394   if (!CallbackFunctionType)
395     return nullptr;
396 
397   // First two arguments are used for the flag and for the callback.
398   if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
399     DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
400                        << "params passed to std::call_once, "
401                        << "ignoring the call\n");
402     return nullptr;
403   }
404 
405   // All arguments past first two ones are passed to the callback,
406   // and we turn lvalues into rvalues if the argument is not passed by
407   // reference.
408   for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
409     const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
410     Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
411     if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
412       QualType PTy = PDecl->getType().getNonReferenceType();
413       ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
414     }
415     CallArgs.push_back(ParamExpr);
416   }
417 
418   CallExpr *CallbackCall;
419   if (isLambdaCall) {
420 
421     CallbackCall = create_call_once_lambda_call(C, M, Callback,
422                                                 CallbackRecordDecl, CallArgs);
423   } else {
424 
425     // Function pointer case.
426     CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
427   }
428 
429   DeclRefExpr *FlagDecl =
430       M.makeDeclRefExpr(Flag,
431                         /* RefersToEnclosingVariableOrCapture=*/true);
432 
433 
434   MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
435   assert(Deref->isLValue());
436   QualType DerefType = Deref->getType();
437 
438   // Negation predicate.
439   UnaryOperator *FlagCheck = new (C) UnaryOperator(
440       /* input=*/
441       M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
442                          CK_IntegralToBoolean),
443       /* opc=*/ UO_LNot,
444       /* QualType=*/ C.IntTy,
445       /* ExprValueKind=*/ VK_RValue,
446       /* ExprObjectKind=*/ OK_Ordinary, SourceLocation());
447 
448   // Create assignment.
449   BinaryOperator *FlagAssignment = M.makeAssignment(
450       Deref, M.makeIntegralCast(M.makeIntegerLiteral(1), DerefType), DerefType);
451 
452   IfStmt *Out = new (C)
453       IfStmt(C, SourceLocation(),
454              /* IsConstexpr=*/ false,
455              /* init=*/ nullptr,
456              /* var=*/ nullptr,
457              /* cond=*/ FlagCheck,
458              /* then=*/ M.makeCompound({CallbackCall, FlagAssignment}));
459 
460   return Out;
461 }
462 
463 /// Create a fake body for dispatch_once.
464 static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
465   // Check if we have at least two parameters.
466   if (D->param_size() != 2)
467     return nullptr;
468 
469   // Check if the first parameter is a pointer to integer type.
470   const ParmVarDecl *Predicate = D->getParamDecl(0);
471   QualType PredicateQPtrTy = Predicate->getType();
472   const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
473   if (!PredicatePtrTy)
474     return nullptr;
475   QualType PredicateTy = PredicatePtrTy->getPointeeType();
476   if (!PredicateTy->isIntegerType())
477     return nullptr;
478 
479   // Check if the second parameter is the proper block type.
480   const ParmVarDecl *Block = D->getParamDecl(1);
481   QualType Ty = Block->getType();
482   if (!isDispatchBlock(Ty))
483     return nullptr;
484 
485   // Everything checks out.  Create a fakse body that checks the predicate,
486   // sets it, and calls the block.  Basically, an AST dump of:
487   //
488   // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
489   //  if (!*predicate) {
490   //    *predicate = 1;
491   //    block();
492   //  }
493   // }
494 
495   ASTMaker M(C);
496 
497   // (1) Create the call.
498   CallExpr *CE = new (C) CallExpr(
499       /*ASTContext=*/C,
500       /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
501       /*args=*/None,
502       /*QualType=*/C.VoidTy,
503       /*ExprValueType=*/VK_RValue,
504       /*SourceLocation=*/SourceLocation());
505 
506   // (2) Create the assignment to the predicate.
507   IntegerLiteral *IL = M.makeIntegerLiteral(1);
508 
509   BinaryOperator *B =
510     M.makeAssignment(
511        M.makeDereference(
512           M.makeLvalueToRvalue(
513             M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
514             PredicateTy),
515        M.makeIntegralCast(IL, PredicateTy),
516        PredicateTy);
517 
518   // (3) Create the compound statement.
519   Stmt *Stmts[] = { B, CE };
520   CompoundStmt *CS = M.makeCompound(Stmts);
521 
522   // (4) Create the 'if' condition.
523   ImplicitCastExpr *LValToRval =
524     M.makeLvalueToRvalue(
525       M.makeDereference(
526         M.makeLvalueToRvalue(
527           M.makeDeclRefExpr(Predicate),
528           PredicateQPtrTy),
529         PredicateTy),
530     PredicateTy);
531 
532   UnaryOperator *UO = new (C) UnaryOperator(
533       /* input=*/ LValToRval,
534       /* opc=*/ UO_LNot,
535       /* QualType=*/ C.IntTy,
536       /* ExprValueKind=*/ VK_RValue,
537       /* ExprObjectKind=*/ OK_Ordinary, SourceLocation());
538 
539   // (5) Create the 'if' statement.
540   IfStmt *If = new (C) IfStmt(C, SourceLocation(),
541                               /* IsConstexpr=*/ false,
542                               /* init=*/ nullptr,
543                               /* var=*/ nullptr,
544                               /* cond=*/ UO,
545                               /* then=*/ CS);
546   return If;
547 }
548 
549 /// Create a fake body for dispatch_sync.
550 static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
551   // Check if we have at least two parameters.
552   if (D->param_size() != 2)
553     return nullptr;
554 
555   // Check if the second parameter is a block.
556   const ParmVarDecl *PV = D->getParamDecl(1);
557   QualType Ty = PV->getType();
558   if (!isDispatchBlock(Ty))
559     return nullptr;
560 
561   // Everything checks out.  Create a fake body that just calls the block.
562   // This is basically just an AST dump of:
563   //
564   // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
565   //   block();
566   // }
567   //
568   ASTMaker M(C);
569   DeclRefExpr *DR = M.makeDeclRefExpr(PV);
570   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
571   CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
572                                   SourceLocation());
573   return CE;
574 }
575 
576 static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
577 {
578   // There are exactly 3 arguments.
579   if (D->param_size() != 3)
580     return nullptr;
581 
582   // Signature:
583   // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
584   //                                 void *__newValue,
585   //                                 void * volatile *__theValue)
586   // Generate body:
587   //   if (oldValue == *theValue) {
588   //    *theValue = newValue;
589   //    return YES;
590   //   }
591   //   else return NO;
592 
593   QualType ResultTy = D->getReturnType();
594   bool isBoolean = ResultTy->isBooleanType();
595   if (!isBoolean && !ResultTy->isIntegralType(C))
596     return nullptr;
597 
598   const ParmVarDecl *OldValue = D->getParamDecl(0);
599   QualType OldValueTy = OldValue->getType();
600 
601   const ParmVarDecl *NewValue = D->getParamDecl(1);
602   QualType NewValueTy = NewValue->getType();
603 
604   assert(OldValueTy == NewValueTy);
605 
606   const ParmVarDecl *TheValue = D->getParamDecl(2);
607   QualType TheValueTy = TheValue->getType();
608   const PointerType *PT = TheValueTy->getAs<PointerType>();
609   if (!PT)
610     return nullptr;
611   QualType PointeeTy = PT->getPointeeType();
612 
613   ASTMaker M(C);
614   // Construct the comparison.
615   Expr *Comparison =
616     M.makeComparison(
617       M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
618       M.makeLvalueToRvalue(
619         M.makeDereference(
620           M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
621           PointeeTy),
622         PointeeTy),
623       BO_EQ);
624 
625   // Construct the body of the IfStmt.
626   Stmt *Stmts[2];
627   Stmts[0] =
628     M.makeAssignment(
629       M.makeDereference(
630         M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
631         PointeeTy),
632       M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
633       NewValueTy);
634 
635   Expr *BoolVal = M.makeObjCBool(true);
636   Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
637                            : M.makeIntegralCast(BoolVal, ResultTy);
638   Stmts[1] = M.makeReturn(RetVal);
639   CompoundStmt *Body = M.makeCompound(Stmts);
640 
641   // Construct the else clause.
642   BoolVal = M.makeObjCBool(false);
643   RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
644                      : M.makeIntegralCast(BoolVal, ResultTy);
645   Stmt *Else = M.makeReturn(RetVal);
646 
647   /// Construct the If.
648   Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr,
649                             Comparison, Body, SourceLocation(), Else);
650 
651   return If;
652 }
653 
654 Stmt *BodyFarm::getBody(const FunctionDecl *D) {
655   D = D->getCanonicalDecl();
656 
657   Optional<Stmt *> &Val = Bodies[D];
658   if (Val.hasValue())
659     return Val.getValue();
660 
661   Val = nullptr;
662 
663   if (D->getIdentifier() == nullptr)
664     return nullptr;
665 
666   StringRef Name = D->getName();
667   if (Name.empty())
668     return nullptr;
669 
670   FunctionFarmer FF;
671 
672   if (Name.startswith("OSAtomicCompareAndSwap") ||
673       Name.startswith("objc_atomicCompareAndSwap")) {
674     FF = create_OSAtomicCompareAndSwap;
675   } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
676     FF = create_call_once;
677   } else {
678     FF = llvm::StringSwitch<FunctionFarmer>(Name)
679           .Case("dispatch_sync", create_dispatch_sync)
680           .Case("dispatch_once", create_dispatch_once)
681           .Default(nullptr);
682   }
683 
684   if (FF) { Val = FF(C, D); }
685   else if (Injector) { Val = Injector->getBody(D); }
686   return Val.getValue();
687 }
688 
689 static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
690   const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
691 
692   if (IVar)
693     return IVar;
694 
695   // When a readonly property is shadowed in a class extensions with a
696   // a readwrite property, the instance variable belongs to the shadowing
697   // property rather than the shadowed property. If there is no instance
698   // variable on a readonly property, check to see whether the property is
699   // shadowed and if so try to get the instance variable from shadowing
700   // property.
701   if (!Prop->isReadOnly())
702     return nullptr;
703 
704   auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
705   const ObjCInterfaceDecl *PrimaryInterface = nullptr;
706   if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
707     PrimaryInterface = InterfaceDecl;
708   } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
709     PrimaryInterface = CategoryDecl->getClassInterface();
710   } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
711     PrimaryInterface = ImplDecl->getClassInterface();
712   } else {
713     return nullptr;
714   }
715 
716   // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
717   // is guaranteed to find the shadowing property, if it exists, rather than
718   // the shadowed property.
719   auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
720       Prop->getIdentifier(), Prop->getQueryKind());
721   if (ShadowingProp && ShadowingProp != Prop) {
722     IVar = ShadowingProp->getPropertyIvarDecl();
723   }
724 
725   return IVar;
726 }
727 
728 static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
729                                       const ObjCPropertyDecl *Prop) {
730   // First, find the backing ivar.
731   const ObjCIvarDecl *IVar = findBackingIvar(Prop);
732   if (!IVar)
733     return nullptr;
734 
735   // Ignore weak variables, which have special behavior.
736   if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
737     return nullptr;
738 
739   // Look to see if Sema has synthesized a body for us. This happens in
740   // Objective-C++ because the return value may be a C++ class type with a
741   // non-trivial copy constructor. We can only do this if we can find the
742   // @synthesize for this property, though (or if we know it's been auto-
743   // synthesized).
744   const ObjCImplementationDecl *ImplDecl =
745     IVar->getContainingInterface()->getImplementation();
746   if (ImplDecl) {
747     for (const auto *I : ImplDecl->property_impls()) {
748       if (I->getPropertyDecl() != Prop)
749         continue;
750 
751       if (I->getGetterCXXConstructor()) {
752         ASTMaker M(Ctx);
753         return M.makeReturn(I->getGetterCXXConstructor());
754       }
755     }
756   }
757 
758   // Sanity check that the property is the same type as the ivar, or a
759   // reference to it, and that it is either an object pointer or trivially
760   // copyable.
761   if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
762                                   Prop->getType().getNonReferenceType()))
763     return nullptr;
764   if (!IVar->getType()->isObjCLifetimeType() &&
765       !IVar->getType().isTriviallyCopyableType(Ctx))
766     return nullptr;
767 
768   // Generate our body:
769   //   return self->_ivar;
770   ASTMaker M(Ctx);
771 
772   const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
773   if (!selfVar)
774     return nullptr;
775 
776   Expr *loadedIVar =
777     M.makeObjCIvarRef(
778       M.makeLvalueToRvalue(
779         M.makeDeclRefExpr(selfVar),
780         selfVar->getType()),
781       IVar);
782 
783   if (!Prop->getType()->isReferenceType())
784     loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
785 
786   return M.makeReturn(loadedIVar);
787 }
788 
789 Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
790   // We currently only know how to synthesize property accessors.
791   if (!D->isPropertyAccessor())
792     return nullptr;
793 
794   D = D->getCanonicalDecl();
795 
796   Optional<Stmt *> &Val = Bodies[D];
797   if (Val.hasValue())
798     return Val.getValue();
799   Val = nullptr;
800 
801   const ObjCPropertyDecl *Prop = D->findPropertyDecl();
802   if (!Prop)
803     return nullptr;
804 
805   // For now, we only synthesize getters.
806   // Synthesizing setters would cause false negatives in the
807   // RetainCountChecker because the method body would bind the parameter
808   // to an instance variable, causing it to escape. This would prevent
809   // warning in the following common scenario:
810   //
811   //  id foo = [[NSObject alloc] init];
812   //  self.foo = foo; // We should warn that foo leaks here.
813   //
814   if (D->param_size() != 0)
815     return nullptr;
816 
817   Val = createObjCPropertyGetter(C, Prop);
818 
819   return Val.getValue();
820 }
821 
822