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   QualType CallbackType = Callback->getType().getNonReferenceType();
329 
330   // Nullable pointer, non-null iff function is a CXXRecordDecl.
331   CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
332   QualType FlagType = Flag->getType().getNonReferenceType();
333   auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl());
334 
335   if (!FlagRecordDecl) {
336     DEBUG(llvm::dbgs() << "Flag field is not a record: "
337                        << "unknown std::call_once implementation, "
338                        << "ignoring the call.\n");
339     return nullptr;
340   }
341 
342   // We initially assume libc++ implementation of call_once,
343   // where the once_flag struct has a field `__state_`.
344   ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
345 
346   // Otherwise, try libstdc++ implementation, with a field
347   // `_M_once`
348   if (!FlagFieldDecl) {
349     DEBUG(llvm::dbgs() << "No field __state_ found on std::once_flag struct, "
350                        << "assuming libstdc++ implementation\n");
351     FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
352   }
353 
354   if (!FlagFieldDecl) {
355     DEBUG(llvm::dbgs() << "No field _M_once found on std::once flag struct: "
356                        << "unknown std::call_once implementation, "
357                        << "ignoring the call");
358     return nullptr;
359   }
360 
361   bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
362   if (CallbackRecordDecl && !isLambdaCall) {
363     DEBUG(llvm::dbgs() << "Not supported: synthesizing body for functors when "
364                        << "body farming std::call_once, ignoring the call.");
365     return nullptr;
366   }
367 
368   SmallVector<Expr *, 5> CallArgs;
369   const FunctionProtoType *CallbackFunctionType;
370   if (isLambdaCall) {
371 
372     // Lambda requires callback itself inserted as a first parameter.
373     CallArgs.push_back(
374         M.makeDeclRefExpr(Callback,
375                           /* RefersToEnclosingVariableOrCapture= */ true));
376     CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
377                                ->getType()
378                                ->getAs<FunctionProtoType>();
379   } else if (!CallbackType->getPointeeType().isNull()) {
380     CallbackFunctionType =
381         CallbackType->getPointeeType()->getAs<FunctionProtoType>();
382   } else {
383     CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
384   }
385 
386   if (!CallbackFunctionType)
387     return nullptr;
388 
389   // First two arguments are used for the flag and for the callback.
390   if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
391     DEBUG(llvm::dbgs() << "Number of params of the callback does not match "
392                        << "the number of params passed to std::call_once, "
393                        << "ignoring the call");
394     return nullptr;
395   }
396 
397   // All arguments past first two ones are passed to the callback,
398   // and we turn lvalues into rvalues if the argument is not passed by
399   // reference.
400   for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
401     const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
402     Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
403     if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
404       QualType PTy = PDecl->getType().getNonReferenceType();
405       ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
406     }
407     CallArgs.push_back(ParamExpr);
408   }
409 
410   CallExpr *CallbackCall;
411   if (isLambdaCall) {
412 
413     CallbackCall = create_call_once_lambda_call(C, M, Callback,
414                                                 CallbackRecordDecl, CallArgs);
415   } else {
416 
417     // Function pointer case.
418     CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
419   }
420 
421   DeclRefExpr *FlagDecl =
422       M.makeDeclRefExpr(Flag,
423                         /* RefersToEnclosingVariableOrCapture=*/true);
424 
425 
426   MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
427   assert(Deref->isLValue());
428   QualType DerefType = Deref->getType();
429 
430   // Negation predicate.
431   UnaryOperator *FlagCheck = new (C) UnaryOperator(
432       /* input= */
433       M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
434                          CK_IntegralToBoolean),
435       /* opc= */ UO_LNot,
436       /* QualType= */ C.IntTy,
437       /* ExprValueKind= */ VK_RValue,
438       /* ExprObjectKind= */ OK_Ordinary, SourceLocation());
439 
440   // Create assignment.
441   BinaryOperator *FlagAssignment = M.makeAssignment(
442       Deref, M.makeIntegralCast(M.makeIntegerLiteral(1), DerefType), DerefType);
443 
444   IfStmt *Out = new (C)
445       IfStmt(C, SourceLocation(),
446              /* IsConstexpr= */ false,
447              /* init= */ nullptr,
448              /* var= */ nullptr,
449              /* cond= */ FlagCheck,
450              /* then= */ M.makeCompound({CallbackCall, FlagAssignment}));
451 
452   return Out;
453 }
454 
455 /// Create a fake body for dispatch_once.
456 static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
457   // Check if we have at least two parameters.
458   if (D->param_size() != 2)
459     return nullptr;
460 
461   // Check if the first parameter is a pointer to integer type.
462   const ParmVarDecl *Predicate = D->getParamDecl(0);
463   QualType PredicateQPtrTy = Predicate->getType();
464   const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
465   if (!PredicatePtrTy)
466     return nullptr;
467   QualType PredicateTy = PredicatePtrTy->getPointeeType();
468   if (!PredicateTy->isIntegerType())
469     return nullptr;
470 
471   // Check if the second parameter is the proper block type.
472   const ParmVarDecl *Block = D->getParamDecl(1);
473   QualType Ty = Block->getType();
474   if (!isDispatchBlock(Ty))
475     return nullptr;
476 
477   // Everything checks out.  Create a fakse body that checks the predicate,
478   // sets it, and calls the block.  Basically, an AST dump of:
479   //
480   // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
481   //  if (!*predicate) {
482   //    *predicate = 1;
483   //    block();
484   //  }
485   // }
486 
487   ASTMaker M(C);
488 
489   // (1) Create the call.
490   CallExpr *CE = new (C) CallExpr(
491       /*ASTContext=*/C,
492       /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
493       /*args=*/None,
494       /*QualType=*/C.VoidTy,
495       /*ExprValueType=*/VK_RValue,
496       /*SourceLocation=*/SourceLocation());
497 
498   // (2) Create the assignment to the predicate.
499   IntegerLiteral *IL = M.makeIntegerLiteral(1);
500 
501   BinaryOperator *B =
502     M.makeAssignment(
503        M.makeDereference(
504           M.makeLvalueToRvalue(
505             M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
506             PredicateTy),
507        M.makeIntegralCast(IL, PredicateTy),
508        PredicateTy);
509 
510   // (3) Create the compound statement.
511   Stmt *Stmts[] = { B, CE };
512   CompoundStmt *CS = M.makeCompound(Stmts);
513 
514   // (4) Create the 'if' condition.
515   ImplicitCastExpr *LValToRval =
516     M.makeLvalueToRvalue(
517       M.makeDereference(
518         M.makeLvalueToRvalue(
519           M.makeDeclRefExpr(Predicate),
520           PredicateQPtrTy),
521         PredicateTy),
522     PredicateTy);
523 
524   UnaryOperator *UO = new (C) UnaryOperator(
525       /* input= */ LValToRval,
526       /* opc= */ UO_LNot,
527       /* QualType= */ C.IntTy,
528       /* ExprValueKind= */ VK_RValue,
529       /* ExprObjectKind= */ OK_Ordinary, SourceLocation());
530 
531   // (5) Create the 'if' statement.
532   IfStmt *If = new (C) IfStmt(C, SourceLocation(),
533                               /* IsConstexpr= */ false,
534                               /* init= */ nullptr,
535                               /* var= */ nullptr,
536                               /* cond= */ UO,
537                               /* then= */ CS);
538   return If;
539 }
540 
541 /// Create a fake body for dispatch_sync.
542 static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
543   // Check if we have at least two parameters.
544   if (D->param_size() != 2)
545     return nullptr;
546 
547   // Check if the second parameter is a block.
548   const ParmVarDecl *PV = D->getParamDecl(1);
549   QualType Ty = PV->getType();
550   if (!isDispatchBlock(Ty))
551     return nullptr;
552 
553   // Everything checks out.  Create a fake body that just calls the block.
554   // This is basically just an AST dump of:
555   //
556   // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
557   //   block();
558   // }
559   //
560   ASTMaker M(C);
561   DeclRefExpr *DR = M.makeDeclRefExpr(PV);
562   ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
563   CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
564                                   SourceLocation());
565   return CE;
566 }
567 
568 static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
569 {
570   // There are exactly 3 arguments.
571   if (D->param_size() != 3)
572     return nullptr;
573 
574   // Signature:
575   // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
576   //                                 void *__newValue,
577   //                                 void * volatile *__theValue)
578   // Generate body:
579   //   if (oldValue == *theValue) {
580   //    *theValue = newValue;
581   //    return YES;
582   //   }
583   //   else return NO;
584 
585   QualType ResultTy = D->getReturnType();
586   bool isBoolean = ResultTy->isBooleanType();
587   if (!isBoolean && !ResultTy->isIntegralType(C))
588     return nullptr;
589 
590   const ParmVarDecl *OldValue = D->getParamDecl(0);
591   QualType OldValueTy = OldValue->getType();
592 
593   const ParmVarDecl *NewValue = D->getParamDecl(1);
594   QualType NewValueTy = NewValue->getType();
595 
596   assert(OldValueTy == NewValueTy);
597 
598   const ParmVarDecl *TheValue = D->getParamDecl(2);
599   QualType TheValueTy = TheValue->getType();
600   const PointerType *PT = TheValueTy->getAs<PointerType>();
601   if (!PT)
602     return nullptr;
603   QualType PointeeTy = PT->getPointeeType();
604 
605   ASTMaker M(C);
606   // Construct the comparison.
607   Expr *Comparison =
608     M.makeComparison(
609       M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
610       M.makeLvalueToRvalue(
611         M.makeDereference(
612           M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
613           PointeeTy),
614         PointeeTy),
615       BO_EQ);
616 
617   // Construct the body of the IfStmt.
618   Stmt *Stmts[2];
619   Stmts[0] =
620     M.makeAssignment(
621       M.makeDereference(
622         M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
623         PointeeTy),
624       M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
625       NewValueTy);
626 
627   Expr *BoolVal = M.makeObjCBool(true);
628   Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
629                            : M.makeIntegralCast(BoolVal, ResultTy);
630   Stmts[1] = M.makeReturn(RetVal);
631   CompoundStmt *Body = M.makeCompound(Stmts);
632 
633   // Construct the else clause.
634   BoolVal = M.makeObjCBool(false);
635   RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
636                      : M.makeIntegralCast(BoolVal, ResultTy);
637   Stmt *Else = M.makeReturn(RetVal);
638 
639   /// Construct the If.
640   Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr,
641                             Comparison, Body, SourceLocation(), Else);
642 
643   return If;
644 }
645 
646 Stmt *BodyFarm::getBody(const FunctionDecl *D) {
647   D = D->getCanonicalDecl();
648 
649   Optional<Stmt *> &Val = Bodies[D];
650   if (Val.hasValue())
651     return Val.getValue();
652 
653   Val = nullptr;
654 
655   if (D->getIdentifier() == nullptr)
656     return nullptr;
657 
658   StringRef Name = D->getName();
659   if (Name.empty())
660     return nullptr;
661 
662   FunctionFarmer FF;
663 
664   if (Name.startswith("OSAtomicCompareAndSwap") ||
665       Name.startswith("objc_atomicCompareAndSwap")) {
666     FF = create_OSAtomicCompareAndSwap;
667   } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
668     FF = create_call_once;
669   } else {
670     FF = llvm::StringSwitch<FunctionFarmer>(Name)
671           .Case("dispatch_sync", create_dispatch_sync)
672           .Case("dispatch_once", create_dispatch_once)
673           .Default(nullptr);
674   }
675 
676   if (FF) { Val = FF(C, D); }
677   else if (Injector) { Val = Injector->getBody(D); }
678   return Val.getValue();
679 }
680 
681 static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
682   const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
683 
684   if (IVar)
685     return IVar;
686 
687   // When a readonly property is shadowed in a class extensions with a
688   // a readwrite property, the instance variable belongs to the shadowing
689   // property rather than the shadowed property. If there is no instance
690   // variable on a readonly property, check to see whether the property is
691   // shadowed and if so try to get the instance variable from shadowing
692   // property.
693   if (!Prop->isReadOnly())
694     return nullptr;
695 
696   auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
697   const ObjCInterfaceDecl *PrimaryInterface = nullptr;
698   if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
699     PrimaryInterface = InterfaceDecl;
700   } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
701     PrimaryInterface = CategoryDecl->getClassInterface();
702   } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
703     PrimaryInterface = ImplDecl->getClassInterface();
704   } else {
705     return nullptr;
706   }
707 
708   // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
709   // is guaranteed to find the shadowing property, if it exists, rather than
710   // the shadowed property.
711   auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
712       Prop->getIdentifier(), Prop->getQueryKind());
713   if (ShadowingProp && ShadowingProp != Prop) {
714     IVar = ShadowingProp->getPropertyIvarDecl();
715   }
716 
717   return IVar;
718 }
719 
720 static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
721                                       const ObjCPropertyDecl *Prop) {
722   // First, find the backing ivar.
723   const ObjCIvarDecl *IVar = findBackingIvar(Prop);
724   if (!IVar)
725     return nullptr;
726 
727   // Ignore weak variables, which have special behavior.
728   if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
729     return nullptr;
730 
731   // Look to see if Sema has synthesized a body for us. This happens in
732   // Objective-C++ because the return value may be a C++ class type with a
733   // non-trivial copy constructor. We can only do this if we can find the
734   // @synthesize for this property, though (or if we know it's been auto-
735   // synthesized).
736   const ObjCImplementationDecl *ImplDecl =
737     IVar->getContainingInterface()->getImplementation();
738   if (ImplDecl) {
739     for (const auto *I : ImplDecl->property_impls()) {
740       if (I->getPropertyDecl() != Prop)
741         continue;
742 
743       if (I->getGetterCXXConstructor()) {
744         ASTMaker M(Ctx);
745         return M.makeReturn(I->getGetterCXXConstructor());
746       }
747     }
748   }
749 
750   // Sanity check that the property is the same type as the ivar, or a
751   // reference to it, and that it is either an object pointer or trivially
752   // copyable.
753   if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
754                                   Prop->getType().getNonReferenceType()))
755     return nullptr;
756   if (!IVar->getType()->isObjCLifetimeType() &&
757       !IVar->getType().isTriviallyCopyableType(Ctx))
758     return nullptr;
759 
760   // Generate our body:
761   //   return self->_ivar;
762   ASTMaker M(Ctx);
763 
764   const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
765   if (!selfVar)
766     return nullptr;
767 
768   Expr *loadedIVar =
769     M.makeObjCIvarRef(
770       M.makeLvalueToRvalue(
771         M.makeDeclRefExpr(selfVar),
772         selfVar->getType()),
773       IVar);
774 
775   if (!Prop->getType()->isReferenceType())
776     loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
777 
778   return M.makeReturn(loadedIVar);
779 }
780 
781 Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
782   // We currently only know how to synthesize property accessors.
783   if (!D->isPropertyAccessor())
784     return nullptr;
785 
786   D = D->getCanonicalDecl();
787 
788   Optional<Stmt *> &Val = Bodies[D];
789   if (Val.hasValue())
790     return Val.getValue();
791   Val = nullptr;
792 
793   const ObjCPropertyDecl *Prop = D->findPropertyDecl();
794   if (!Prop)
795     return nullptr;
796 
797   // For now, we only synthesize getters.
798   // Synthesizing setters would cause false negatives in the
799   // RetainCountChecker because the method body would bind the parameter
800   // to an instance variable, causing it to escape. This would prevent
801   // warning in the following common scenario:
802   //
803   //  id foo = [[NSObject alloc] init];
804   //  self.foo = foo; // We should warn that foo leaks here.
805   //
806   if (D->param_size() != 0)
807     return nullptr;
808 
809   Val = createObjCPropertyGetter(C, Prop);
810 
811   return Val.getValue();
812 }
813 
814