BodyFarm.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. #include "clang/Analysis/BodyFarm.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/NestedNameSpecifier.h"
  21. #include "clang/Analysis/CodeInjector.h"
  22. #include "clang/Basic/OperatorKinds.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/Support/Debug.h"
  25. #define DEBUG_TYPE "body-farm"
  26. using namespace clang;
  27. //===----------------------------------------------------------------------===//
  28. // Helper creation functions for constructing faux ASTs.
  29. //===----------------------------------------------------------------------===//
  30. static bool isDispatchBlock(QualType Ty) {
  31. // Is it a block pointer?
  32. const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
  33. if (!BPT)
  34. return false;
  35. // Check if the block pointer type takes no arguments and
  36. // returns void.
  37. const FunctionProtoType *FT =
  38. BPT->getPointeeType()->getAs<FunctionProtoType>();
  39. return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
  40. }
  41. namespace {
  42. class ASTMaker {
  43. public:
  44. ASTMaker(ASTContext &C) : C(C) {}
  45. /// Create a new BinaryOperator representing a simple assignment.
  46. BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
  47. /// Create a new BinaryOperator representing a comparison.
  48. BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
  49. BinaryOperator::Opcode Op);
  50. /// Create a new compound stmt using the provided statements.
  51. CompoundStmt *makeCompound(ArrayRef<Stmt*>);
  52. /// Create a new DeclRefExpr for the referenced variable.
  53. DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
  54. bool RefersToEnclosingVariableOrCapture = false);
  55. /// Create a new UnaryOperator representing a dereference.
  56. UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
  57. /// Create an implicit cast for an integer conversion.
  58. Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
  59. /// Create an implicit cast to a builtin boolean type.
  60. ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
  61. /// Create an implicit cast for lvalue-to-rvaluate conversions.
  62. ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
  63. /// Make RValue out of variable declaration, creating a temporary
  64. /// DeclRefExpr in the process.
  65. ImplicitCastExpr *
  66. makeLvalueToRvalue(const VarDecl *Decl,
  67. bool RefersToEnclosingVariableOrCapture = false);
  68. /// Create an implicit cast of the given type.
  69. ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
  70. CastKind CK = CK_LValueToRValue);
  71. /// Create an Objective-C bool literal.
  72. ObjCBoolLiteralExpr *makeObjCBool(bool Val);
  73. /// Create an Objective-C ivar reference.
  74. ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
  75. /// Create a Return statement.
  76. ReturnStmt *makeReturn(const Expr *RetVal);
  77. /// Create an integer literal expression of the given type.
  78. IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
  79. /// Create a member expression.
  80. MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
  81. bool IsArrow = false,
  82. ExprValueKind ValueKind = VK_LValue);
  83. /// Returns a *first* member field of a record declaration with a given name.
  84. /// \return an nullptr if no member with such a name exists.
  85. ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
  86. private:
  87. ASTContext &C;
  88. };
  89. }
  90. BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
  91. QualType Ty) {
  92. return BinaryOperator::Create(
  93. C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), BO_Assign, Ty,
  94. VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride());
  95. }
  96. BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
  97. BinaryOperator::Opcode Op) {
  98. assert(BinaryOperator::isLogicalOp(Op) ||
  99. BinaryOperator::isComparisonOp(Op));
  100. return BinaryOperator::Create(
  101. C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), Op,
  102. C.getLogicalOperationType(), VK_PRValue, OK_Ordinary, SourceLocation(),
  103. FPOptionsOverride());
  104. }
  105. CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
  106. return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
  107. }
  108. DeclRefExpr *ASTMaker::makeDeclRefExpr(
  109. const VarDecl *D,
  110. bool RefersToEnclosingVariableOrCapture) {
  111. QualType Type = D->getType().getNonReferenceType();
  112. DeclRefExpr *DR = DeclRefExpr::Create(
  113. C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
  114. RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
  115. return DR;
  116. }
  117. UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
  118. return UnaryOperator::Create(C, const_cast<Expr *>(Arg), UO_Deref, Ty,
  119. VK_LValue, OK_Ordinary, SourceLocation(),
  120. /*CanOverflow*/ false, FPOptionsOverride());
  121. }
  122. ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
  123. return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
  124. }
  125. ImplicitCastExpr *
  126. ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
  127. bool RefersToEnclosingVariableOrCapture) {
  128. QualType Type = Arg->getType().getNonReferenceType();
  129. return makeLvalueToRvalue(makeDeclRefExpr(Arg,
  130. RefersToEnclosingVariableOrCapture),
  131. Type);
  132. }
  133. ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
  134. CastKind CK) {
  135. return ImplicitCastExpr::Create(C, Ty,
  136. /* CastKind=*/CK,
  137. /* Expr=*/const_cast<Expr *>(Arg),
  138. /* CXXCastPath=*/nullptr,
  139. /* ExprValueKind=*/VK_PRValue,
  140. /* FPFeatures */ FPOptionsOverride());
  141. }
  142. Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
  143. if (Arg->getType() == Ty)
  144. return const_cast<Expr*>(Arg);
  145. return makeImplicitCast(Arg, Ty, CK_IntegralCast);
  146. }
  147. ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
  148. return makeImplicitCast(Arg, C.BoolTy, CK_IntegralToBoolean);
  149. }
  150. ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
  151. QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
  152. return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
  153. }
  154. ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
  155. const ObjCIvarDecl *IVar) {
  156. return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
  157. IVar->getType(), SourceLocation(),
  158. SourceLocation(), const_cast<Expr*>(Base),
  159. /*arrow=*/true, /*free=*/false);
  160. }
  161. ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
  162. return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
  163. /* NRVOCandidate=*/nullptr);
  164. }
  165. IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
  166. llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
  167. return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
  168. }
  169. MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
  170. bool IsArrow,
  171. ExprValueKind ValueKind) {
  172. DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
  173. return MemberExpr::Create(
  174. C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
  175. SourceLocation(), MemberDecl, FoundDecl,
  176. DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
  177. /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
  178. OK_Ordinary, NOUR_None);
  179. }
  180. ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
  181. CXXBasePaths Paths(
  182. /* FindAmbiguities=*/false,
  183. /* RecordPaths=*/false,
  184. /* DetectVirtual=*/ false);
  185. const IdentifierInfo &II = C.Idents.get(Name);
  186. DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
  187. DeclContextLookupResult Decls = RD->lookup(DeclName);
  188. for (NamedDecl *FoundDecl : Decls)
  189. if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
  190. return cast<ValueDecl>(FoundDecl);
  191. return nullptr;
  192. }
  193. //===----------------------------------------------------------------------===//
  194. // Creation functions for faux ASTs.
  195. //===----------------------------------------------------------------------===//
  196. typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
  197. static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
  198. const ParmVarDecl *Callback,
  199. ArrayRef<Expr *> CallArgs) {
  200. QualType Ty = Callback->getType();
  201. DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
  202. Expr *SubExpr;
  203. if (Ty->isRValueReferenceType()) {
  204. SubExpr = M.makeImplicitCast(
  205. Call, Ty.getNonReferenceType(), CK_LValueToRValue);
  206. } else if (Ty->isLValueReferenceType() &&
  207. Call->getType()->isFunctionType()) {
  208. Ty = C.getPointerType(Ty.getNonReferenceType());
  209. SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
  210. } else if (Ty->isLValueReferenceType()
  211. && Call->getType()->isPointerType()
  212. && Call->getType()->getPointeeType()->isFunctionType()){
  213. SubExpr = Call;
  214. } else {
  215. llvm_unreachable("Unexpected state");
  216. }
  217. return CallExpr::Create(C, SubExpr, CallArgs, C.VoidTy, VK_PRValue,
  218. SourceLocation(), FPOptionsOverride());
  219. }
  220. static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
  221. const ParmVarDecl *Callback,
  222. CXXRecordDecl *CallbackDecl,
  223. ArrayRef<Expr *> CallArgs) {
  224. assert(CallbackDecl != nullptr);
  225. assert(CallbackDecl->isLambda());
  226. FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
  227. assert(callOperatorDecl != nullptr);
  228. DeclRefExpr *callOperatorDeclRef =
  229. DeclRefExpr::Create(/* Ctx =*/ C,
  230. /* QualifierLoc =*/ NestedNameSpecifierLoc(),
  231. /* TemplateKWLoc =*/ SourceLocation(),
  232. const_cast<FunctionDecl *>(callOperatorDecl),
  233. /* RefersToEnclosingVariableOrCapture=*/ false,
  234. /* NameLoc =*/ SourceLocation(),
  235. /* T =*/ callOperatorDecl->getType(),
  236. /* VK =*/ VK_LValue);
  237. return CXXOperatorCallExpr::Create(
  238. /*AstContext=*/C, OO_Call, callOperatorDeclRef,
  239. /*Args=*/CallArgs,
  240. /*QualType=*/C.VoidTy,
  241. /*ExprValueType=*/VK_PRValue,
  242. /*SourceLocation=*/SourceLocation(),
  243. /*FPFeatures=*/FPOptionsOverride());
  244. }
  245. /// Create a fake body for std::call_once.
  246. /// Emulates the following function body:
  247. ///
  248. /// \code
  249. /// typedef struct once_flag_s {
  250. /// unsigned long __state = 0;
  251. /// } once_flag;
  252. /// template<class Callable>
  253. /// void call_once(once_flag& o, Callable func) {
  254. /// if (!o.__state) {
  255. /// func();
  256. /// }
  257. /// o.__state = 1;
  258. /// }
  259. /// \endcode
  260. static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
  261. LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
  262. // We need at least two parameters.
  263. if (D->param_size() < 2)
  264. return nullptr;
  265. ASTMaker M(C);
  266. const ParmVarDecl *Flag = D->getParamDecl(0);
  267. const ParmVarDecl *Callback = D->getParamDecl(1);
  268. if (!Callback->getType()->isReferenceType()) {
  269. llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
  270. return nullptr;
  271. }
  272. if (!Flag->getType()->isReferenceType()) {
  273. llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
  274. return nullptr;
  275. }
  276. QualType CallbackType = Callback->getType().getNonReferenceType();
  277. // Nullable pointer, non-null iff function is a CXXRecordDecl.
  278. CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
  279. QualType FlagType = Flag->getType().getNonReferenceType();
  280. auto *FlagRecordDecl = FlagType->getAsRecordDecl();
  281. if (!FlagRecordDecl) {
  282. LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
  283. << "unknown std::call_once implementation, "
  284. << "ignoring the call.\n");
  285. return nullptr;
  286. }
  287. // We initially assume libc++ implementation of call_once,
  288. // where the once_flag struct has a field `__state_`.
  289. ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
  290. // Otherwise, try libstdc++ implementation, with a field
  291. // `_M_once`
  292. if (!FlagFieldDecl) {
  293. FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
  294. }
  295. if (!FlagFieldDecl) {
  296. LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
  297. << "std::once_flag struct: unknown std::call_once "
  298. << "implementation, ignoring the call.");
  299. return nullptr;
  300. }
  301. bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
  302. if (CallbackRecordDecl && !isLambdaCall) {
  303. LLVM_DEBUG(llvm::dbgs()
  304. << "Not supported: synthesizing body for functors when "
  305. << "body farming std::call_once, ignoring the call.");
  306. return nullptr;
  307. }
  308. SmallVector<Expr *, 5> CallArgs;
  309. const FunctionProtoType *CallbackFunctionType;
  310. if (isLambdaCall) {
  311. // Lambda requires callback itself inserted as a first parameter.
  312. CallArgs.push_back(
  313. M.makeDeclRefExpr(Callback,
  314. /* RefersToEnclosingVariableOrCapture=*/ true));
  315. CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
  316. ->getType()
  317. ->getAs<FunctionProtoType>();
  318. } else if (!CallbackType->getPointeeType().isNull()) {
  319. CallbackFunctionType =
  320. CallbackType->getPointeeType()->getAs<FunctionProtoType>();
  321. } else {
  322. CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
  323. }
  324. if (!CallbackFunctionType)
  325. return nullptr;
  326. // First two arguments are used for the flag and for the callback.
  327. if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
  328. LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
  329. << "params passed to std::call_once, "
  330. << "ignoring the call\n");
  331. return nullptr;
  332. }
  333. // All arguments past first two ones are passed to the callback,
  334. // and we turn lvalues into rvalues if the argument is not passed by
  335. // reference.
  336. for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
  337. const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
  338. assert(PDecl);
  339. if (CallbackFunctionType->getParamType(ParamIdx - 2)
  340. .getNonReferenceType()
  341. .getCanonicalType() !=
  342. PDecl->getType().getNonReferenceType().getCanonicalType()) {
  343. LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
  344. << "params passed to std::call_once, "
  345. << "ignoring the call\n");
  346. return nullptr;
  347. }
  348. Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
  349. if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
  350. QualType PTy = PDecl->getType().getNonReferenceType();
  351. ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
  352. }
  353. CallArgs.push_back(ParamExpr);
  354. }
  355. CallExpr *CallbackCall;
  356. if (isLambdaCall) {
  357. CallbackCall = create_call_once_lambda_call(C, M, Callback,
  358. CallbackRecordDecl, CallArgs);
  359. } else {
  360. // Function pointer case.
  361. CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
  362. }
  363. DeclRefExpr *FlagDecl =
  364. M.makeDeclRefExpr(Flag,
  365. /* RefersToEnclosingVariableOrCapture=*/true);
  366. MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
  367. assert(Deref->isLValue());
  368. QualType DerefType = Deref->getType();
  369. // Negation predicate.
  370. UnaryOperator *FlagCheck = UnaryOperator::Create(
  371. C,
  372. /* input=*/
  373. M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
  374. CK_IntegralToBoolean),
  375. /* opc=*/UO_LNot,
  376. /* QualType=*/C.IntTy,
  377. /* ExprValueKind=*/VK_PRValue,
  378. /* ExprObjectKind=*/OK_Ordinary, SourceLocation(),
  379. /* CanOverflow*/ false, FPOptionsOverride());
  380. // Create assignment.
  381. BinaryOperator *FlagAssignment = M.makeAssignment(
  382. Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
  383. DerefType);
  384. auto *Out =
  385. IfStmt::Create(C, SourceLocation(), IfStatementKind::Ordinary,
  386. /* Init=*/nullptr,
  387. /* Var=*/nullptr,
  388. /* Cond=*/FlagCheck,
  389. /* LPL=*/SourceLocation(),
  390. /* RPL=*/SourceLocation(),
  391. /* Then=*/M.makeCompound({CallbackCall, FlagAssignment}));
  392. return Out;
  393. }
  394. /// Create a fake body for dispatch_once.
  395. static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
  396. // Check if we have at least two parameters.
  397. if (D->param_size() != 2)
  398. return nullptr;
  399. // Check if the first parameter is a pointer to integer type.
  400. const ParmVarDecl *Predicate = D->getParamDecl(0);
  401. QualType PredicateQPtrTy = Predicate->getType();
  402. const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
  403. if (!PredicatePtrTy)
  404. return nullptr;
  405. QualType PredicateTy = PredicatePtrTy->getPointeeType();
  406. if (!PredicateTy->isIntegerType())
  407. return nullptr;
  408. // Check if the second parameter is the proper block type.
  409. const ParmVarDecl *Block = D->getParamDecl(1);
  410. QualType Ty = Block->getType();
  411. if (!isDispatchBlock(Ty))
  412. return nullptr;
  413. // Everything checks out. Create a fakse body that checks the predicate,
  414. // sets it, and calls the block. Basically, an AST dump of:
  415. //
  416. // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
  417. // if (*predicate != ~0l) {
  418. // *predicate = ~0l;
  419. // block();
  420. // }
  421. // }
  422. ASTMaker M(C);
  423. // (1) Create the call.
  424. CallExpr *CE = CallExpr::Create(
  425. /*ASTContext=*/C,
  426. /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
  427. /*Args=*/None,
  428. /*QualType=*/C.VoidTy,
  429. /*ExprValueType=*/VK_PRValue,
  430. /*SourceLocation=*/SourceLocation(), FPOptionsOverride());
  431. // (2) Create the assignment to the predicate.
  432. Expr *DoneValue =
  433. UnaryOperator::Create(C, M.makeIntegerLiteral(0, C.LongTy), UO_Not,
  434. C.LongTy, VK_PRValue, OK_Ordinary, SourceLocation(),
  435. /*CanOverflow*/ false, FPOptionsOverride());
  436. BinaryOperator *B =
  437. M.makeAssignment(
  438. M.makeDereference(
  439. M.makeLvalueToRvalue(
  440. M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
  441. PredicateTy),
  442. M.makeIntegralCast(DoneValue, PredicateTy),
  443. PredicateTy);
  444. // (3) Create the compound statement.
  445. Stmt *Stmts[] = { B, CE };
  446. CompoundStmt *CS = M.makeCompound(Stmts);
  447. // (4) Create the 'if' condition.
  448. ImplicitCastExpr *LValToRval =
  449. M.makeLvalueToRvalue(
  450. M.makeDereference(
  451. M.makeLvalueToRvalue(
  452. M.makeDeclRefExpr(Predicate),
  453. PredicateQPtrTy),
  454. PredicateTy),
  455. PredicateTy);
  456. Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
  457. // (5) Create the 'if' statement.
  458. auto *If = IfStmt::Create(C, SourceLocation(), IfStatementKind::Ordinary,
  459. /* Init=*/nullptr,
  460. /* Var=*/nullptr,
  461. /* Cond=*/GuardCondition,
  462. /* LPL=*/SourceLocation(),
  463. /* RPL=*/SourceLocation(),
  464. /* Then=*/CS);
  465. return If;
  466. }
  467. /// Create a fake body for dispatch_sync.
  468. static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
  469. // Check if we have at least two parameters.
  470. if (D->param_size() != 2)
  471. return nullptr;
  472. // Check if the second parameter is a block.
  473. const ParmVarDecl *PV = D->getParamDecl(1);
  474. QualType Ty = PV->getType();
  475. if (!isDispatchBlock(Ty))
  476. return nullptr;
  477. // Everything checks out. Create a fake body that just calls the block.
  478. // This is basically just an AST dump of:
  479. //
  480. // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
  481. // block();
  482. // }
  483. //
  484. ASTMaker M(C);
  485. DeclRefExpr *DR = M.makeDeclRefExpr(PV);
  486. ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
  487. CallExpr *CE = CallExpr::Create(C, ICE, None, C.VoidTy, VK_PRValue,
  488. SourceLocation(), FPOptionsOverride());
  489. return CE;
  490. }
  491. static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
  492. {
  493. // There are exactly 3 arguments.
  494. if (D->param_size() != 3)
  495. return nullptr;
  496. // Signature:
  497. // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
  498. // void *__newValue,
  499. // void * volatile *__theValue)
  500. // Generate body:
  501. // if (oldValue == *theValue) {
  502. // *theValue = newValue;
  503. // return YES;
  504. // }
  505. // else return NO;
  506. QualType ResultTy = D->getReturnType();
  507. bool isBoolean = ResultTy->isBooleanType();
  508. if (!isBoolean && !ResultTy->isIntegralType(C))
  509. return nullptr;
  510. const ParmVarDecl *OldValue = D->getParamDecl(0);
  511. QualType OldValueTy = OldValue->getType();
  512. const ParmVarDecl *NewValue = D->getParamDecl(1);
  513. QualType NewValueTy = NewValue->getType();
  514. assert(OldValueTy == NewValueTy);
  515. const ParmVarDecl *TheValue = D->getParamDecl(2);
  516. QualType TheValueTy = TheValue->getType();
  517. const PointerType *PT = TheValueTy->getAs<PointerType>();
  518. if (!PT)
  519. return nullptr;
  520. QualType PointeeTy = PT->getPointeeType();
  521. ASTMaker M(C);
  522. // Construct the comparison.
  523. Expr *Comparison =
  524. M.makeComparison(
  525. M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
  526. M.makeLvalueToRvalue(
  527. M.makeDereference(
  528. M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
  529. PointeeTy),
  530. PointeeTy),
  531. BO_EQ);
  532. // Construct the body of the IfStmt.
  533. Stmt *Stmts[2];
  534. Stmts[0] =
  535. M.makeAssignment(
  536. M.makeDereference(
  537. M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
  538. PointeeTy),
  539. M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
  540. NewValueTy);
  541. Expr *BoolVal = M.makeObjCBool(true);
  542. Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
  543. : M.makeIntegralCast(BoolVal, ResultTy);
  544. Stmts[1] = M.makeReturn(RetVal);
  545. CompoundStmt *Body = M.makeCompound(Stmts);
  546. // Construct the else clause.
  547. BoolVal = M.makeObjCBool(false);
  548. RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
  549. : M.makeIntegralCast(BoolVal, ResultTy);
  550. Stmt *Else = M.makeReturn(RetVal);
  551. /// Construct the If.
  552. auto *If =
  553. IfStmt::Create(C, SourceLocation(), IfStatementKind::Ordinary,
  554. /* Init=*/nullptr,
  555. /* Var=*/nullptr, Comparison,
  556. /* LPL=*/SourceLocation(),
  557. /* RPL=*/SourceLocation(), Body, SourceLocation(), Else);
  558. return If;
  559. }
  560. Stmt *BodyFarm::getBody(const FunctionDecl *D) {
  561. Optional<Stmt *> &Val = Bodies[D];
  562. if (Val.hasValue())
  563. return Val.getValue();
  564. Val = nullptr;
  565. if (D->getIdentifier() == nullptr)
  566. return nullptr;
  567. StringRef Name = D->getName();
  568. if (Name.empty())
  569. return nullptr;
  570. FunctionFarmer FF;
  571. if (Name.startswith("OSAtomicCompareAndSwap") ||
  572. Name.startswith("objc_atomicCompareAndSwap")) {
  573. FF = create_OSAtomicCompareAndSwap;
  574. } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
  575. FF = create_call_once;
  576. } else {
  577. FF = llvm::StringSwitch<FunctionFarmer>(Name)
  578. .Case("dispatch_sync", create_dispatch_sync)
  579. .Case("dispatch_once", create_dispatch_once)
  580. .Default(nullptr);
  581. }
  582. if (FF) { Val = FF(C, D); }
  583. else if (Injector) { Val = Injector->getBody(D); }
  584. return Val.getValue();
  585. }
  586. static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
  587. const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
  588. if (IVar)
  589. return IVar;
  590. // When a readonly property is shadowed in a class extensions with a
  591. // a readwrite property, the instance variable belongs to the shadowing
  592. // property rather than the shadowed property. If there is no instance
  593. // variable on a readonly property, check to see whether the property is
  594. // shadowed and if so try to get the instance variable from shadowing
  595. // property.
  596. if (!Prop->isReadOnly())
  597. return nullptr;
  598. auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
  599. const ObjCInterfaceDecl *PrimaryInterface = nullptr;
  600. if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
  601. PrimaryInterface = InterfaceDecl;
  602. } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
  603. PrimaryInterface = CategoryDecl->getClassInterface();
  604. } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
  605. PrimaryInterface = ImplDecl->getClassInterface();
  606. } else {
  607. return nullptr;
  608. }
  609. // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
  610. // is guaranteed to find the shadowing property, if it exists, rather than
  611. // the shadowed property.
  612. auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
  613. Prop->getIdentifier(), Prop->getQueryKind());
  614. if (ShadowingProp && ShadowingProp != Prop) {
  615. IVar = ShadowingProp->getPropertyIvarDecl();
  616. }
  617. return IVar;
  618. }
  619. static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
  620. const ObjCMethodDecl *MD) {
  621. // First, find the backing ivar.
  622. const ObjCIvarDecl *IVar = nullptr;
  623. const ObjCPropertyDecl *Prop = nullptr;
  624. // Property accessor stubs sometimes do not correspond to any property decl
  625. // in the current interface (but in a superclass). They still have a
  626. // corresponding property impl decl in this case.
  627. if (MD->isSynthesizedAccessorStub()) {
  628. const ObjCInterfaceDecl *IntD = MD->getClassInterface();
  629. const ObjCImplementationDecl *ImpD = IntD->getImplementation();
  630. for (const auto *PI : ImpD->property_impls()) {
  631. if (const ObjCPropertyDecl *Candidate = PI->getPropertyDecl()) {
  632. if (Candidate->getGetterName() == MD->getSelector()) {
  633. Prop = Candidate;
  634. IVar = Prop->getPropertyIvarDecl();
  635. }
  636. }
  637. }
  638. }
  639. if (!IVar) {
  640. Prop = MD->findPropertyDecl();
  641. IVar = findBackingIvar(Prop);
  642. }
  643. if (!IVar || !Prop)
  644. return nullptr;
  645. // Ignore weak variables, which have special behavior.
  646. if (Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
  647. return nullptr;
  648. // Look to see if Sema has synthesized a body for us. This happens in
  649. // Objective-C++ because the return value may be a C++ class type with a
  650. // non-trivial copy constructor. We can only do this if we can find the
  651. // @synthesize for this property, though (or if we know it's been auto-
  652. // synthesized).
  653. const ObjCImplementationDecl *ImplDecl =
  654. IVar->getContainingInterface()->getImplementation();
  655. if (ImplDecl) {
  656. for (const auto *I : ImplDecl->property_impls()) {
  657. if (I->getPropertyDecl() != Prop)
  658. continue;
  659. if (I->getGetterCXXConstructor()) {
  660. ASTMaker M(Ctx);
  661. return M.makeReturn(I->getGetterCXXConstructor());
  662. }
  663. }
  664. }
  665. // We expect that the property is the same type as the ivar, or a reference to
  666. // it, and that it is either an object pointer or trivially copyable.
  667. if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
  668. Prop->getType().getNonReferenceType()))
  669. return nullptr;
  670. if (!IVar->getType()->isObjCLifetimeType() &&
  671. !IVar->getType().isTriviallyCopyableType(Ctx))
  672. return nullptr;
  673. // Generate our body:
  674. // return self->_ivar;
  675. ASTMaker M(Ctx);
  676. const VarDecl *selfVar = MD->getSelfDecl();
  677. if (!selfVar)
  678. return nullptr;
  679. Expr *loadedIVar = M.makeObjCIvarRef(
  680. M.makeLvalueToRvalue(M.makeDeclRefExpr(selfVar), selfVar->getType()),
  681. IVar);
  682. if (!MD->getReturnType()->isReferenceType())
  683. loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
  684. return M.makeReturn(loadedIVar);
  685. }
  686. Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
  687. // We currently only know how to synthesize property accessors.
  688. if (!D->isPropertyAccessor())
  689. return nullptr;
  690. D = D->getCanonicalDecl();
  691. // We should not try to synthesize explicitly redefined accessors.
  692. // We do not know for sure how they behave.
  693. if (!D->isImplicit())
  694. return nullptr;
  695. Optional<Stmt *> &Val = Bodies[D];
  696. if (Val.hasValue())
  697. return Val.getValue();
  698. Val = nullptr;
  699. // For now, we only synthesize getters.
  700. // Synthesizing setters would cause false negatives in the
  701. // RetainCountChecker because the method body would bind the parameter
  702. // to an instance variable, causing it to escape. This would prevent
  703. // warning in the following common scenario:
  704. //
  705. // id foo = [[NSObject alloc] init];
  706. // self.foo = foo; // We should warn that foo leaks here.
  707. //
  708. if (D->param_size() != 0)
  709. return nullptr;
  710. // If the property was defined in an extension, search the extensions for
  711. // overrides.
  712. const ObjCInterfaceDecl *OID = D->getClassInterface();
  713. if (dyn_cast<ObjCInterfaceDecl>(D->getParent()) != OID)
  714. for (auto *Ext : OID->known_extensions()) {
  715. auto *OMD = Ext->getInstanceMethod(D->getSelector());
  716. if (OMD && !OMD->isImplicit())
  717. return nullptr;
  718. }
  719. Val = createObjCPropertyGetter(C, D);
  720. return Val.getValue();
  721. }