blob: 43f9e715b3de2f9b269e6141469ff38d24e0f943 [file] [log] [blame]
Ted Kremenek14f779c2012-09-21 00:09:11 +00001//== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- C++ -*-//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Ted Kremenek14f779c2012-09-21 00:09:11 +00006//
7//===----------------------------------------------------------------------===//
8//
9// BodyFarm is a factory for creating faux implementations for functions/methods
10// for analysis purposes.
11//
12//===----------------------------------------------------------------------===//
13
George Karpenkov3d64d6e2017-10-23 23:59:52 +000014#include "clang/Analysis/BodyFarm.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
George Karpenkov657a5892017-09-30 00:03:22 +000016#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
George Karpenkov657a5892017-09-30 00:03:22 +000019#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprObjC.h"
George Karpenkov657a5892017-09-30 00:03:22 +000021#include "clang/AST/NestedNameSpecifier.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000022#include "clang/Analysis/CodeInjector.h"
George Karpenkov657a5892017-09-30 00:03:22 +000023#include "clang/Basic/OperatorKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/StringSwitch.h"
George Karpenkov657a5892017-09-30 00:03:22 +000025#include "llvm/Support/Debug.h"
26
27#define DEBUG_TYPE "body-farm"
Ted Kremenek14f779c2012-09-21 00:09:11 +000028
29using namespace clang;
30
Ted Kremenek2b5c83c2012-09-21 17:54:32 +000031//===----------------------------------------------------------------------===//
32// Helper creation functions for constructing faux ASTs.
33//===----------------------------------------------------------------------===//
Ted Kremenek14f779c2012-09-21 00:09:11 +000034
Ted Kremenekd81a4a12012-09-21 00:52:24 +000035static bool isDispatchBlock(QualType Ty) {
36 // Is it a block pointer?
37 const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
38 if (!BPT)
39 return false;
40
41 // Check if the block pointer type takes no arguments and
42 // returns void.
43 const FunctionProtoType *FT =
44 BPT->getPointeeType()->getAs<FunctionProtoType>();
Alexander Kornienko090360d2015-11-06 01:08:38 +000045 return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
Ted Kremenekd81a4a12012-09-21 00:52:24 +000046}
47
Ted Kremenek72418132012-09-21 17:54:35 +000048namespace {
49class ASTMaker {
50public:
51 ASTMaker(ASTContext &C) : C(C) {}
Fangrui Song6907ce22018-07-30 19:24:48 +000052
Ted Kremenekf465dc12012-09-21 18:33:54 +000053 /// Create a new BinaryOperator representing a simple assignment.
54 BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000055
Ted Kremenek089ffd02012-10-11 20:58:18 +000056 /// Create a new BinaryOperator representing a comparison.
57 BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
58 BinaryOperator::Opcode Op);
Fangrui Song6907ce22018-07-30 19:24:48 +000059
Ted Kremenek089ffd02012-10-11 20:58:18 +000060 /// Create a new compound stmt using the provided statements.
61 CompoundStmt *makeCompound(ArrayRef<Stmt*>);
Fangrui Song6907ce22018-07-30 19:24:48 +000062
Ted Kremenek69bcb822012-09-21 18:13:23 +000063 /// Create a new DeclRefExpr for the referenced variable.
George Karpenkov657a5892017-09-30 00:03:22 +000064 DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
George Karpenkovb2a60c62017-10-17 22:28:18 +000065 bool RefersToEnclosingVariableOrCapture = false);
Fangrui Song6907ce22018-07-30 19:24:48 +000066
Ted Kremenekdff35532012-09-21 18:33:52 +000067 /// Create a new UnaryOperator representing a dereference.
68 UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000069
Ted Kremenek69bcb822012-09-21 18:13:23 +000070 /// Create an implicit cast for an integer conversion.
Ted Kremenek6fdefb52012-10-12 00:18:19 +000071 Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000072
Ted Kremenek089ffd02012-10-11 20:58:18 +000073 /// Create an implicit cast to a builtin boolean type.
74 ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
Fangrui Song6907ce22018-07-30 19:24:48 +000075
George Karpenkov657a5892017-09-30 00:03:22 +000076 /// Create an implicit cast for lvalue-to-rvaluate conversions.
Ted Kremenekca90ea52012-09-21 18:13:27 +000077 ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000078
George Karpenkov657a5892017-09-30 00:03:22 +000079 /// Make RValue out of variable declaration, creating a temporary
80 /// DeclRefExpr in the process.
81 ImplicitCastExpr *
82 makeLvalueToRvalue(const VarDecl *Decl,
George Karpenkovb2a60c62017-10-17 22:28:18 +000083 bool RefersToEnclosingVariableOrCapture = false);
George Karpenkov657a5892017-09-30 00:03:22 +000084
85 /// Create an implicit cast of the given type.
86 ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
87 CastKind CK = CK_LValueToRValue);
88
Ted Kremenek089ffd02012-10-11 20:58:18 +000089 /// Create an Objective-C bool literal.
90 ObjCBoolLiteralExpr *makeObjCBool(bool Val);
Jordan Rose1a866cd2014-01-10 20:06:06 +000091
92 /// Create an Objective-C ivar reference.
93 ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
Fangrui Song6907ce22018-07-30 19:24:48 +000094
Ted Kremenek089ffd02012-10-11 20:58:18 +000095 /// Create a Return statement.
96 ReturnStmt *makeReturn(const Expr *RetVal);
Fangrui Song6907ce22018-07-30 19:24:48 +000097
Devin Coughlin046833e2017-11-06 22:12:19 +000098 /// Create an integer literal expression of the given type.
99 IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
George Karpenkov657a5892017-09-30 00:03:22 +0000100
101 /// Create a member expression.
102 MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
103 bool IsArrow = false,
104 ExprValueKind ValueKind = VK_LValue);
105
106 /// Returns a *first* member field of a record declaration with a given name.
107 /// \return an nullptr if no member with such a name exists.
George Karpenkovc928e1f2017-10-11 20:53:01 +0000108 ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
George Karpenkov657a5892017-09-30 00:03:22 +0000109
Ted Kremenek72418132012-09-21 17:54:35 +0000110private:
111 ASTContext &C;
112};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000113}
Ted Kremenek72418132012-09-21 17:54:35 +0000114
Ted Kremenekf465dc12012-09-21 18:33:54 +0000115BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
116 QualType Ty) {
117 return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
118 BO_Assign, Ty, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +0000119 OK_Ordinary, SourceLocation(), FPOptions());
Ted Kremenekf465dc12012-09-21 18:33:54 +0000120}
121
Ted Kremenek089ffd02012-10-11 20:58:18 +0000122BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
123 BinaryOperator::Opcode Op) {
124 assert(BinaryOperator::isLogicalOp(Op) ||
125 BinaryOperator::isComparisonOp(Op));
126 return new (C) BinaryOperator(const_cast<Expr*>(LHS),
127 const_cast<Expr*>(RHS),
128 Op,
129 C.getLogicalOperationType(),
130 VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +0000131 OK_Ordinary, SourceLocation(), FPOptions());
Ted Kremenek089ffd02012-10-11 20:58:18 +0000132}
133
134CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
Benjamin Kramer07420902017-12-24 16:24:20 +0000135 return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
Ted Kremenek089ffd02012-10-11 20:58:18 +0000136}
137
George Karpenkovb2a60c62017-10-17 22:28:18 +0000138DeclRefExpr *ASTMaker::makeDeclRefExpr(
139 const VarDecl *D,
140 bool RefersToEnclosingVariableOrCapture) {
141 QualType Type = D->getType().getNonReferenceType();
George Karpenkov657a5892017-09-30 00:03:22 +0000142
143 DeclRefExpr *DR = DeclRefExpr::Create(
144 C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
145 RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
Ted Kremenek72418132012-09-21 17:54:35 +0000146 return DR;
147}
148
Ted Kremenekdff35532012-09-21 18:33:52 +0000149UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
150 return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
Aaron Ballmana5038552018-01-09 13:07:03 +0000151 VK_LValue, OK_Ordinary, SourceLocation(),
152 /*CanOverflow*/ false);
Ted Kremenekdff35532012-09-21 18:33:52 +0000153}
154
Ted Kremenekca90ea52012-09-21 18:13:27 +0000155ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
George Karpenkov657a5892017-09-30 00:03:22 +0000156 return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
157}
158
George Karpenkov657a5892017-09-30 00:03:22 +0000159ImplicitCastExpr *
160ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000161 bool RefersToEnclosingVariableOrCapture) {
162 QualType Type = Arg->getType().getNonReferenceType();
George Karpenkov657a5892017-09-30 00:03:22 +0000163 return makeLvalueToRvalue(makeDeclRefExpr(Arg,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000164 RefersToEnclosingVariableOrCapture),
George Karpenkov657a5892017-09-30 00:03:22 +0000165 Type);
166}
167
168ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
169 CastKind CK) {
170 return ImplicitCastExpr::Create(C, Ty,
George Karpenkova1329382017-10-25 00:03:45 +0000171 /* CastKind=*/ CK,
172 /* Expr=*/ const_cast<Expr *>(Arg),
173 /* CXXCastPath=*/ nullptr,
174 /* ExprValueKind=*/ VK_RValue);
Ted Kremenekca90ea52012-09-21 18:13:27 +0000175}
176
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000177Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
178 if (Arg->getType() == Ty)
179 return const_cast<Expr*>(Arg);
Craig Topper25542942014-05-20 04:30:07 +0000180
Ted Kremenek69bcb822012-09-21 18:13:23 +0000181 return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
Craig Topper25542942014-05-20 04:30:07 +0000182 const_cast<Expr*>(Arg), nullptr, VK_RValue);
Ted Kremenek69bcb822012-09-21 18:13:23 +0000183}
184
Ted Kremenek089ffd02012-10-11 20:58:18 +0000185ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
186 return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
Craig Topper25542942014-05-20 04:30:07 +0000187 const_cast<Expr*>(Arg), nullptr, VK_RValue);
Ted Kremenek089ffd02012-10-11 20:58:18 +0000188}
189
190ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
191 QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
192 return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
193}
194
Jordan Rose1a866cd2014-01-10 20:06:06 +0000195ObjCIvarRefExpr *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
Ted Kremenek089ffd02012-10-11 20:58:18 +0000203ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
Bruno Ricci023b1d12018-10-30 14:40:49 +0000204 return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
205 /* NRVOCandidate=*/nullptr);
Ted Kremenek089ffd02012-10-11 20:58:18 +0000206}
207
Devin Coughlin046833e2017-11-06 22:12:19 +0000208IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
209 llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
210 return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
George Karpenkov657a5892017-09-30 00:03:22 +0000211}
212
213MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
214 bool IsArrow,
215 ExprValueKind ValueKind) {
216
217 DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
218 return MemberExpr::Create(
219 C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
220 SourceLocation(), MemberDecl, FoundDecl,
221 DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
George Karpenkova1329382017-10-25 00:03:45 +0000222 /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
Richard Smith1bbad592019-06-11 17:50:36 +0000223 OK_Ordinary, NOUR_None);
George Karpenkov657a5892017-09-30 00:03:22 +0000224}
225
George Karpenkovc928e1f2017-10-11 20:53:01 +0000226ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
George Karpenkov657a5892017-09-30 00:03:22 +0000227
228 CXXBasePaths Paths(
229 /* FindAmbiguities=*/false,
230 /* RecordPaths=*/false,
George Karpenkova1329382017-10-25 00:03:45 +0000231 /* DetectVirtual=*/ false);
George Karpenkov657a5892017-09-30 00:03:22 +0000232 const IdentifierInfo &II = C.Idents.get(Name);
233 DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
234
235 DeclContextLookupResult Decls = RD->lookup(DeclName);
236 for (NamedDecl *FoundDecl : Decls)
237 if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
George Karpenkovc928e1f2017-10-11 20:53:01 +0000238 return cast<ValueDecl>(FoundDecl);
George Karpenkov657a5892017-09-30 00:03:22 +0000239
240 return nullptr;
241}
242
Ted Kremenek2b5c83c2012-09-21 17:54:32 +0000243//===----------------------------------------------------------------------===//
244// Creation functions for faux ASTs.
245//===----------------------------------------------------------------------===//
246
247typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
248
George Karpenkov6dda6712017-10-02 21:01:46 +0000249static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
250 const ParmVarDecl *Callback,
251 ArrayRef<Expr *> CallArgs) {
George Karpenkov657a5892017-09-30 00:03:22 +0000252
George Karpenkov98e81cd2017-10-24 00:13:18 +0000253 QualType Ty = Callback->getType();
254 DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
George Karpenkovfaa03f42018-05-16 00:29:13 +0000255 Expr *SubExpr;
George Karpenkov98e81cd2017-10-24 00:13:18 +0000256 if (Ty->isRValueReferenceType()) {
George Karpenkovfaa03f42018-05-16 00:29:13 +0000257 SubExpr = M.makeImplicitCast(
258 Call, Ty.getNonReferenceType(), CK_LValueToRValue);
259 } else if (Ty->isLValueReferenceType() &&
260 Call->getType()->isFunctionType()) {
George Karpenkov98e81cd2017-10-24 00:13:18 +0000261 Ty = C.getPointerType(Ty.getNonReferenceType());
George Karpenkovfaa03f42018-05-16 00:29:13 +0000262 SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
263 } else if (Ty->isLValueReferenceType()
264 && Call->getType()->isPointerType()
265 && Call->getType()->getPointeeType()->isFunctionType()){
266 SubExpr = Call;
267 } else {
268 llvm_unreachable("Unexpected state");
George Karpenkov98e81cd2017-10-24 00:13:18 +0000269 }
270
Bruno Riccic5885cf2018-12-21 15:20:32 +0000271 return CallExpr::Create(C, SubExpr, CallArgs, C.VoidTy, VK_RValue,
272 SourceLocation());
George Karpenkov657a5892017-09-30 00:03:22 +0000273}
274
George Karpenkov6dda6712017-10-02 21:01:46 +0000275static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
276 const ParmVarDecl *Callback,
George Karpenkovbd4254c2017-10-20 23:29:59 +0000277 CXXRecordDecl *CallbackDecl,
George Karpenkov6dda6712017-10-02 21:01:46 +0000278 ArrayRef<Expr *> CallArgs) {
George Karpenkov657a5892017-09-30 00:03:22 +0000279 assert(CallbackDecl != nullptr);
280 assert(CallbackDecl->isLambda());
281 FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
282 assert(callOperatorDecl != nullptr);
283
284 DeclRefExpr *callOperatorDeclRef =
George Karpenkova1329382017-10-25 00:03:45 +0000285 DeclRefExpr::Create(/* Ctx =*/ C,
286 /* QualifierLoc =*/ NestedNameSpecifierLoc(),
287 /* TemplateKWLoc =*/ SourceLocation(),
George Karpenkov657a5892017-09-30 00:03:22 +0000288 const_cast<FunctionDecl *>(callOperatorDecl),
George Karpenkova1329382017-10-25 00:03:45 +0000289 /* RefersToEnclosingVariableOrCapture=*/ false,
290 /* NameLoc =*/ SourceLocation(),
291 /* T =*/ callOperatorDecl->getType(),
292 /* VK =*/ VK_LValue);
George Karpenkov657a5892017-09-30 00:03:22 +0000293
Bruno Riccic5885cf2018-12-21 15:20:32 +0000294 return CXXOperatorCallExpr::Create(
295 /*AstContext=*/C, OO_Call, callOperatorDeclRef,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000296 /*Args=*/CallArgs,
Bruno Riccic5885cf2018-12-21 15:20:32 +0000297 /*QualType=*/C.VoidTy,
298 /*ExprValueType=*/VK_RValue,
299 /*SourceLocation=*/SourceLocation(), FPOptions());
George Karpenkov657a5892017-09-30 00:03:22 +0000300}
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
317static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000318 LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
George Karpenkov657a5892017-09-30 00:03:22 +0000319
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);
George Karpenkov03544832017-11-03 00:36:03 +0000328
329 if (!Callback->getType()->isReferenceType()) {
330 llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
331 return nullptr;
332 }
333 if (!Flag->getType()->isReferenceType()) {
334 llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
335 return nullptr;
336 }
337
George Karpenkov657a5892017-09-30 00:03:22 +0000338 QualType CallbackType = Callback->getType().getNonReferenceType();
George Karpenkovbd4254c2017-10-20 23:29:59 +0000339
340 // Nullable pointer, non-null iff function is a CXXRecordDecl.
341 CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000342 QualType FlagType = Flag->getType().getNonReferenceType();
George Karpenkov39e51372018-07-28 02:16:13 +0000343 auto *FlagRecordDecl = FlagType->getAsRecordDecl();
George Karpenkovc928e1f2017-10-11 20:53:01 +0000344
345 if (!FlagRecordDecl) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000346 LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
347 << "unknown std::call_once implementation, "
348 << "ignoring the call.\n");
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000349 return nullptr;
350 }
351
George Karpenkovc928e1f2017-10-11 20:53:01 +0000352 // We initially assume libc++ implementation of call_once,
353 // where the once_flag struct has a field `__state_`.
354 ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
355
356 // Otherwise, try libstdc++ implementation, with a field
357 // `_M_once`
358 if (!FlagFieldDecl) {
George Karpenkovc928e1f2017-10-11 20:53:01 +0000359 FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
360 }
361
362 if (!FlagFieldDecl) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000363 LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
364 << "std::once_flag struct: unknown std::call_once "
365 << "implementation, ignoring the call.");
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000366 return nullptr;
367 }
George Karpenkov657a5892017-09-30 00:03:22 +0000368
George Karpenkovbd4254c2017-10-20 23:29:59 +0000369 bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
370 if (CallbackRecordDecl && !isLambdaCall) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000371 LLVM_DEBUG(llvm::dbgs()
372 << "Not supported: synthesizing body for functors when "
373 << "body farming std::call_once, ignoring the call.");
George Karpenkovbd4254c2017-10-20 23:29:59 +0000374 return nullptr;
375 }
George Karpenkov6dda6712017-10-02 21:01:46 +0000376
George Karpenkov657a5892017-09-30 00:03:22 +0000377 SmallVector<Expr *, 5> CallArgs;
George Karpenkovbd4254c2017-10-20 23:29:59 +0000378 const FunctionProtoType *CallbackFunctionType;
379 if (isLambdaCall) {
George Karpenkov657a5892017-09-30 00:03:22 +0000380
George Karpenkov6dda6712017-10-02 21:01:46 +0000381 // Lambda requires callback itself inserted as a first parameter.
382 CallArgs.push_back(
383 M.makeDeclRefExpr(Callback,
George Karpenkova1329382017-10-25 00:03:45 +0000384 /* RefersToEnclosingVariableOrCapture=*/ true));
George Karpenkovbd4254c2017-10-20 23:29:59 +0000385 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
386 ->getType()
387 ->getAs<FunctionProtoType>();
George Karpenkov98e81cd2017-10-24 00:13:18 +0000388 } else if (!CallbackType->getPointeeType().isNull()) {
George Karpenkovbd4254c2017-10-20 23:29:59 +0000389 CallbackFunctionType =
390 CallbackType->getPointeeType()->getAs<FunctionProtoType>();
George Karpenkov98e81cd2017-10-24 00:13:18 +0000391 } else {
392 CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
George Karpenkovbd4254c2017-10-20 23:29:59 +0000393 }
George Karpenkov6dda6712017-10-02 21:01:46 +0000394
George Karpenkovbd4254c2017-10-20 23:29:59 +0000395 if (!CallbackFunctionType)
396 return nullptr;
397
398 // First two arguments are used for the flag and for the callback.
399 if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000400 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
401 << "params passed to std::call_once, "
402 << "ignoring the call\n");
George Karpenkovbd4254c2017-10-20 23:29:59 +0000403 return nullptr;
404 }
405
406 // All arguments past first two ones are passed to the callback,
407 // and we turn lvalues into rvalues if the argument is not passed by
408 // reference.
409 for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
410 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
Artem Dergachev3517d102019-08-28 21:19:58 +0000411 assert(PDecl);
412 if (CallbackFunctionType->getParamType(ParamIdx - 2)
George Karpenkov59202322018-02-02 01:44:07 +0000413 .getNonReferenceType()
414 .getCanonicalType() !=
415 PDecl->getType().getNonReferenceType().getCanonicalType()) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000416 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
417 << "params passed to std::call_once, "
418 << "ignoring the call\n");
George Karpenkov59202322018-02-02 01:44:07 +0000419 return nullptr;
420 }
George Karpenkovbd4254c2017-10-20 23:29:59 +0000421 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
422 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
423 QualType PTy = PDecl->getType().getNonReferenceType();
424 ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
425 }
426 CallArgs.push_back(ParamExpr);
427 }
George Karpenkov657a5892017-09-30 00:03:22 +0000428
429 CallExpr *CallbackCall;
George Karpenkov6dda6712017-10-02 21:01:46 +0000430 if (isLambdaCall) {
George Karpenkov657a5892017-09-30 00:03:22 +0000431
George Karpenkovbd4254c2017-10-20 23:29:59 +0000432 CallbackCall = create_call_once_lambda_call(C, M, Callback,
433 CallbackRecordDecl, CallArgs);
George Karpenkov657a5892017-09-30 00:03:22 +0000434 } else {
435
436 // Function pointer case.
437 CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
438 }
439
George Karpenkov657a5892017-09-30 00:03:22 +0000440 DeclRefExpr *FlagDecl =
441 M.makeDeclRefExpr(Flag,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000442 /* RefersToEnclosingVariableOrCapture=*/true);
George Karpenkov657a5892017-09-30 00:03:22 +0000443
George Karpenkov657a5892017-09-30 00:03:22 +0000444
George Karpenkovc928e1f2017-10-11 20:53:01 +0000445 MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
George Karpenkov657a5892017-09-30 00:03:22 +0000446 assert(Deref->isLValue());
447 QualType DerefType = Deref->getType();
448
449 // Negation predicate.
450 UnaryOperator *FlagCheck = new (C) UnaryOperator(
George Karpenkova1329382017-10-25 00:03:45 +0000451 /* input=*/
George Karpenkov657a5892017-09-30 00:03:22 +0000452 M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
453 CK_IntegralToBoolean),
George Karpenkova1329382017-10-25 00:03:45 +0000454 /* opc=*/ UO_LNot,
455 /* QualType=*/ C.IntTy,
456 /* ExprValueKind=*/ VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +0000457 /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
458 /* CanOverflow*/ false);
George Karpenkov657a5892017-09-30 00:03:22 +0000459
460 // Create assignment.
461 BinaryOperator *FlagAssignment = M.makeAssignment(
Devin Coughlin046833e2017-11-06 22:12:19 +0000462 Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
463 DerefType);
George Karpenkov657a5892017-09-30 00:03:22 +0000464
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000465 auto *Out =
466 IfStmt::Create(C, SourceLocation(),
467 /* IsConstexpr=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000468 /* Init=*/nullptr,
469 /* Var=*/nullptr,
470 /* Cond=*/FlagCheck,
471 /* Then=*/M.makeCompound({CallbackCall, FlagAssignment}));
George Karpenkov657a5892017-09-30 00:03:22 +0000472
473 return Out;
474}
475
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000476/// Create a fake body for dispatch_once.
477static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
478 // Check if we have at least two parameters.
479 if (D->param_size() != 2)
Craig Topper25542942014-05-20 04:30:07 +0000480 return nullptr;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000481
482 // Check if the first parameter is a pointer to integer type.
483 const ParmVarDecl *Predicate = D->getParamDecl(0);
484 QualType PredicateQPtrTy = Predicate->getType();
485 const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
486 if (!PredicatePtrTy)
Craig Topper25542942014-05-20 04:30:07 +0000487 return nullptr;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000488 QualType PredicateTy = PredicatePtrTy->getPointeeType();
489 if (!PredicateTy->isIntegerType())
Craig Topper25542942014-05-20 04:30:07 +0000490 return nullptr;
491
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000492 // Check if the second parameter is the proper block type.
493 const ParmVarDecl *Block = D->getParamDecl(1);
494 QualType Ty = Block->getType();
495 if (!isDispatchBlock(Ty))
Craig Topper25542942014-05-20 04:30:07 +0000496 return nullptr;
497
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000498 // Everything checks out. Create a fakse body that checks the predicate,
499 // sets it, and calls the block. Basically, an AST dump of:
500 //
501 // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
Devin Coughlin046833e2017-11-06 22:12:19 +0000502 // if (*predicate != ~0l) {
503 // *predicate = ~0l;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000504 // block();
505 // }
506 // }
Fangrui Song6907ce22018-07-30 19:24:48 +0000507
Ted Kremenek72418132012-09-21 17:54:35 +0000508 ASTMaker M(C);
Fangrui Song6907ce22018-07-30 19:24:48 +0000509
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000510 // (1) Create the call.
Bruno Riccic5885cf2018-12-21 15:20:32 +0000511 CallExpr *CE = CallExpr::Create(
George Karpenkov657a5892017-09-30 00:03:22 +0000512 /*ASTContext=*/C,
513 /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000514 /*Args=*/None,
George Karpenkov657a5892017-09-30 00:03:22 +0000515 /*QualType=*/C.VoidTy,
516 /*ExprValueType=*/VK_RValue,
517 /*SourceLocation=*/SourceLocation());
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000518
519 // (2) Create the assignment to the predicate.
Devin Coughlin046833e2017-11-06 22:12:19 +0000520 Expr *DoneValue =
521 new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
Aaron Ballmana5038552018-01-09 13:07:03 +0000522 VK_RValue, OK_Ordinary, SourceLocation(),
523 /*CanOverflow*/false);
George Karpenkov657a5892017-09-30 00:03:22 +0000524
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000525 BinaryOperator *B =
526 M.makeAssignment(
527 M.makeDereference(
528 M.makeLvalueToRvalue(
529 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
530 PredicateTy),
Devin Coughlin046833e2017-11-06 22:12:19 +0000531 M.makeIntegralCast(DoneValue, PredicateTy),
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000532 PredicateTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000533
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000534 // (3) Create the compound statement.
Craig Topper5fc8fc22014-08-27 06:28:36 +0000535 Stmt *Stmts[] = { B, CE };
536 CompoundStmt *CS = M.makeCompound(Stmts);
Fangrui Song6907ce22018-07-30 19:24:48 +0000537
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000538 // (4) Create the 'if' condition.
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000539 ImplicitCastExpr *LValToRval =
540 M.makeLvalueToRvalue(
541 M.makeDereference(
542 M.makeLvalueToRvalue(
543 M.makeDeclRefExpr(Predicate),
544 PredicateQPtrTy),
545 PredicateTy),
546 PredicateTy);
Devin Coughlin046833e2017-11-06 22:12:19 +0000547
548 Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000549 // (5) Create the 'if' statement.
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000550 auto *If = IfStmt::Create(C, SourceLocation(),
551 /* IsConstexpr=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000552 /* Init=*/nullptr,
553 /* Var=*/nullptr,
554 /* Cond=*/GuardCondition,
555 /* Then=*/CS);
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000556 return If;
557}
558
Ted Kremenek14f779c2012-09-21 00:09:11 +0000559/// Create a fake body for dispatch_sync.
560static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
561 // Check if we have at least two parameters.
562 if (D->param_size() != 2)
Craig Topper25542942014-05-20 04:30:07 +0000563 return nullptr;
564
Ted Kremenek14f779c2012-09-21 00:09:11 +0000565 // Check if the second parameter is a block.
566 const ParmVarDecl *PV = D->getParamDecl(1);
567 QualType Ty = PV->getType();
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000568 if (!isDispatchBlock(Ty))
Craig Topper25542942014-05-20 04:30:07 +0000569 return nullptr;
570
Ted Kremenek14f779c2012-09-21 00:09:11 +0000571 // Everything checks out. Create a fake body that just calls the block.
572 // This is basically just an AST dump of:
573 //
574 // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
575 // block();
576 // }
Fangrui Song6907ce22018-07-30 19:24:48 +0000577 //
Ted Kremenek72418132012-09-21 17:54:35 +0000578 ASTMaker M(C);
579 DeclRefExpr *DR = M.makeDeclRefExpr(PV);
Ted Kremenekdff35532012-09-21 18:33:52 +0000580 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
Bruno Riccic5885cf2018-12-21 15:20:32 +0000581 CallExpr *CE =
582 CallExpr::Create(C, ICE, None, C.VoidTy, VK_RValue, SourceLocation());
Ted Kremenek14f779c2012-09-21 00:09:11 +0000583 return CE;
584}
585
Ted Kremenek089ffd02012-10-11 20:58:18 +0000586static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
587{
588 // There are exactly 3 arguments.
589 if (D->param_size() != 3)
Craig Topper25542942014-05-20 04:30:07 +0000590 return nullptr;
591
Anna Zaks064185a2013-02-05 19:52:26 +0000592 // Signature:
593 // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
594 // void *__newValue,
595 // void * volatile *__theValue)
596 // Generate body:
Ted Kremenek089ffd02012-10-11 20:58:18 +0000597 // if (oldValue == *theValue) {
598 // *theValue = newValue;
599 // return YES;
600 // }
601 // else return NO;
Alp Toker314cc812014-01-25 16:55:45 +0000602
603 QualType ResultTy = D->getReturnType();
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000604 bool isBoolean = ResultTy->isBooleanType();
605 if (!isBoolean && !ResultTy->isIntegralType(C))
Craig Topper25542942014-05-20 04:30:07 +0000606 return nullptr;
607
Ted Kremenek089ffd02012-10-11 20:58:18 +0000608 const ParmVarDecl *OldValue = D->getParamDecl(0);
609 QualType OldValueTy = OldValue->getType();
610
611 const ParmVarDecl *NewValue = D->getParamDecl(1);
612 QualType NewValueTy = NewValue->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000613
Ted Kremenek089ffd02012-10-11 20:58:18 +0000614 assert(OldValueTy == NewValueTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000615
Ted Kremenek089ffd02012-10-11 20:58:18 +0000616 const ParmVarDecl *TheValue = D->getParamDecl(2);
617 QualType TheValueTy = TheValue->getType();
618 const PointerType *PT = TheValueTy->getAs<PointerType>();
619 if (!PT)
Craig Topper25542942014-05-20 04:30:07 +0000620 return nullptr;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000621 QualType PointeeTy = PT->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000622
Ted Kremenek089ffd02012-10-11 20:58:18 +0000623 ASTMaker M(C);
624 // Construct the comparison.
625 Expr *Comparison =
626 M.makeComparison(
627 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
628 M.makeLvalueToRvalue(
629 M.makeDereference(
630 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
631 PointeeTy),
632 PointeeTy),
633 BO_EQ);
634
635 // Construct the body of the IfStmt.
636 Stmt *Stmts[2];
637 Stmts[0] =
638 M.makeAssignment(
639 M.makeDereference(
640 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
641 PointeeTy),
642 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
643 NewValueTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000644
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000645 Expr *BoolVal = M.makeObjCBool(true);
646 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
647 : M.makeIntegralCast(BoolVal, ResultTy);
648 Stmts[1] = M.makeReturn(RetVal);
Craig Topper5fc8fc22014-08-27 06:28:36 +0000649 CompoundStmt *Body = M.makeCompound(Stmts);
Fangrui Song6907ce22018-07-30 19:24:48 +0000650
Ted Kremenek089ffd02012-10-11 20:58:18 +0000651 // Construct the else clause.
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000652 BoolVal = M.makeObjCBool(false);
653 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
654 : M.makeIntegralCast(BoolVal, ResultTy);
655 Stmt *Else = M.makeReturn(RetVal);
Fangrui Song6907ce22018-07-30 19:24:48 +0000656
Ted Kremenek089ffd02012-10-11 20:58:18 +0000657 /// Construct the If.
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000658 auto *If = IfStmt::Create(C, SourceLocation(),
659 /* IsConstexpr=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000660 /* Init=*/nullptr,
661 /* Var=*/nullptr, Comparison, Body,
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000662 SourceLocation(), Else);
Craig Topper25542942014-05-20 04:30:07 +0000663
Fangrui Song6907ce22018-07-30 19:24:48 +0000664 return If;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000665}
666
Ted Kremenek14f779c2012-09-21 00:09:11 +0000667Stmt *BodyFarm::getBody(const FunctionDecl *D) {
David Blaikie05785d12013-02-20 22:23:23 +0000668 Optional<Stmt *> &Val = Bodies[D];
Ted Kremenek14f779c2012-09-21 00:09:11 +0000669 if (Val.hasValue())
670 return Val.getValue();
Craig Topper25542942014-05-20 04:30:07 +0000671
672 Val = nullptr;
673
674 if (D->getIdentifier() == nullptr)
675 return nullptr;
Ted Kremenek14f779c2012-09-21 00:09:11 +0000676
677 StringRef Name = D->getName();
678 if (Name.empty())
Craig Topper25542942014-05-20 04:30:07 +0000679 return nullptr;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000680
681 FunctionFarmer FF;
682
683 if (Name.startswith("OSAtomicCompareAndSwap") ||
684 Name.startswith("objc_atomicCompareAndSwap")) {
685 FF = create_OSAtomicCompareAndSwap;
George Karpenkov657a5892017-09-30 00:03:22 +0000686 } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
687 FF = create_call_once;
688 } else {
Ted Kremenek089ffd02012-10-11 20:58:18 +0000689 FF = llvm::StringSwitch<FunctionFarmer>(Name)
690 .Case("dispatch_sync", create_dispatch_sync)
691 .Case("dispatch_once", create_dispatch_once)
Craig Topper25542942014-05-20 04:30:07 +0000692 .Default(nullptr);
Ted Kremenek14f779c2012-09-21 00:09:11 +0000693 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000694
Ted Kremenek089ffd02012-10-11 20:58:18 +0000695 if (FF) { Val = FF(C, D); }
Ted Kremenekeeccb302014-08-27 15:14:15 +0000696 else if (Injector) { Val = Injector->getBody(D); }
Ted Kremenek14f779c2012-09-21 00:09:11 +0000697 return Val.getValue();
698}
699
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000700static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
701 const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
702
703 if (IVar)
704 return IVar;
705
706 // When a readonly property is shadowed in a class extensions with a
707 // a readwrite property, the instance variable belongs to the shadowing
708 // property rather than the shadowed property. If there is no instance
709 // variable on a readonly property, check to see whether the property is
710 // shadowed and if so try to get the instance variable from shadowing
711 // property.
712 if (!Prop->isReadOnly())
713 return nullptr;
714
715 auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
716 const ObjCInterfaceDecl *PrimaryInterface = nullptr;
717 if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
718 PrimaryInterface = InterfaceDecl;
719 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
720 PrimaryInterface = CategoryDecl->getClassInterface();
721 } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
722 PrimaryInterface = ImplDecl->getClassInterface();
723 } else {
724 return nullptr;
725 }
726
727 // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
728 // is guaranteed to find the shadowing property, if it exists, rather than
729 // the shadowed property.
730 auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
Manman Ren5b786402016-01-28 18:49:28 +0000731 Prop->getIdentifier(), Prop->getQueryKind());
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000732 if (ShadowingProp && ShadowingProp != Prop) {
733 IVar = ShadowingProp->getPropertyIvarDecl();
734 }
735
736 return IVar;
737}
738
Jordan Rose1a866cd2014-01-10 20:06:06 +0000739static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
740 const ObjCPropertyDecl *Prop) {
Jordan Roseddf19662014-01-23 03:59:10 +0000741 // First, find the backing ivar.
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000742 const ObjCIvarDecl *IVar = findBackingIvar(Prop);
Jordan Rose1a866cd2014-01-10 20:06:06 +0000743 if (!IVar)
Craig Topper25542942014-05-20 04:30:07 +0000744 return nullptr;
Jordan Roseddf19662014-01-23 03:59:10 +0000745
746 // Ignore weak variables, which have special behavior.
Jordan Rose1a866cd2014-01-10 20:06:06 +0000747 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
Craig Topper25542942014-05-20 04:30:07 +0000748 return nullptr;
Jordan Rosea3f27812014-01-14 17:29:06 +0000749
Jordan Roseddf19662014-01-23 03:59:10 +0000750 // Look to see if Sema has synthesized a body for us. This happens in
751 // Objective-C++ because the return value may be a C++ class type with a
752 // non-trivial copy constructor. We can only do this if we can find the
753 // @synthesize for this property, though (or if we know it's been auto-
754 // synthesized).
Jordan Rosea3f27812014-01-14 17:29:06 +0000755 const ObjCImplementationDecl *ImplDecl =
756 IVar->getContainingInterface()->getImplementation();
757 if (ImplDecl) {
Aaron Ballmand85eff42014-03-14 15:02:45 +0000758 for (const auto *I : ImplDecl->property_impls()) {
Jordan Rosea3f27812014-01-14 17:29:06 +0000759 if (I->getPropertyDecl() != Prop)
760 continue;
761
762 if (I->getGetterCXXConstructor()) {
763 ASTMaker M(Ctx);
764 return M.makeReturn(I->getGetterCXXConstructor());
765 }
766 }
767 }
768
Jordan Roseddf19662014-01-23 03:59:10 +0000769 // Sanity check that the property is the same type as the ivar, or a
770 // reference to it, and that it is either an object pointer or trivially
771 // copyable.
772 if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
773 Prop->getType().getNonReferenceType()))
Craig Topper25542942014-05-20 04:30:07 +0000774 return nullptr;
Jordan Roseddf19662014-01-23 03:59:10 +0000775 if (!IVar->getType()->isObjCLifetimeType() &&
776 !IVar->getType().isTriviallyCopyableType(Ctx))
Craig Topper25542942014-05-20 04:30:07 +0000777 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000778
Jordan Roseddf19662014-01-23 03:59:10 +0000779 // Generate our body:
780 // return self->_ivar;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000781 ASTMaker M(Ctx);
782
783 const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
Devin Coughlinaac894f2017-01-11 01:02:34 +0000784 if (!selfVar)
785 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000786
787 Expr *loadedIVar =
788 M.makeObjCIvarRef(
789 M.makeLvalueToRvalue(
790 M.makeDeclRefExpr(selfVar),
791 selfVar->getType()),
792 IVar);
793
794 if (!Prop->getType()->isReferenceType())
795 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
796
797 return M.makeReturn(loadedIVar);
798}
799
Jordan Roseddf19662014-01-23 03:59:10 +0000800Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
801 // We currently only know how to synthesize property accessors.
Jordan Rose1a866cd2014-01-10 20:06:06 +0000802 if (!D->isPropertyAccessor())
Craig Topper25542942014-05-20 04:30:07 +0000803 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000804
805 D = D->getCanonicalDecl();
806
Artem Dergachevc2c47f22019-01-18 22:52:13 +0000807 // We should not try to synthesize explicitly redefined accessors.
808 // We do not know for sure how they behave.
809 if (!D->isImplicit())
810 return nullptr;
811
Jordan Rose1a866cd2014-01-10 20:06:06 +0000812 Optional<Stmt *> &Val = Bodies[D];
813 if (Val.hasValue())
814 return Val.getValue();
Craig Topper25542942014-05-20 04:30:07 +0000815 Val = nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000816
Jordan Roseddf19662014-01-23 03:59:10 +0000817 const ObjCPropertyDecl *Prop = D->findPropertyDecl();
Jordan Rose1a866cd2014-01-10 20:06:06 +0000818 if (!Prop)
Craig Topper25542942014-05-20 04:30:07 +0000819 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000820
Jordan Roseddf19662014-01-23 03:59:10 +0000821 // For now, we only synthesize getters.
Devin Coughlinef3697e2016-02-18 19:37:39 +0000822 // Synthesizing setters would cause false negatives in the
823 // RetainCountChecker because the method body would bind the parameter
824 // to an instance variable, causing it to escape. This would prevent
825 // warning in the following common scenario:
826 //
827 // id foo = [[NSObject alloc] init];
828 // self.foo = foo; // We should warn that foo leaks here.
829 //
Jordan Rose1a866cd2014-01-10 20:06:06 +0000830 if (D->param_size() != 0)
Craig Topper25542942014-05-20 04:30:07 +0000831 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000832
833 Val = createObjCPropertyGetter(C, Prop);
834
835 return Val.getValue();
836}