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