blob: 9c1d529a685628913a0fca4a2f524df9f6c29f10 [file] [log] [blame]
Ted Kremenek14f779c2012-09-21 00:09:11 +00001//== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- C++ -*-//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// BodyFarm is a factory for creating faux implementations for functions/methods
11// for analysis purposes.
12//
13//===----------------------------------------------------------------------===//
14
George Karpenkov3d64d6e2017-10-23 23:59:52 +000015#include "clang/Analysis/BodyFarm.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
George Karpenkov657a5892017-09-30 00:03:22 +000017#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
George Karpenkov657a5892017-09-30 00:03:22 +000020#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/ExprObjC.h"
George Karpenkov657a5892017-09-30 00:03:22 +000022#include "clang/AST/NestedNameSpecifier.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "clang/Analysis/CodeInjector.h"
George Karpenkov657a5892017-09-30 00:03:22 +000024#include "clang/Basic/OperatorKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/StringSwitch.h"
George Karpenkov657a5892017-09-30 00:03:22 +000026#include "llvm/Support/Debug.h"
27
28#define DEBUG_TYPE "body-farm"
Ted Kremenek14f779c2012-09-21 00:09:11 +000029
30using namespace clang;
31
Ted Kremenek2b5c83c2012-09-21 17:54:32 +000032//===----------------------------------------------------------------------===//
33// Helper creation functions for constructing faux ASTs.
34//===----------------------------------------------------------------------===//
Ted Kremenek14f779c2012-09-21 00:09:11 +000035
Ted Kremenekd81a4a12012-09-21 00:52:24 +000036static 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>();
Alexander Kornienko090360d2015-11-06 01:08:38 +000046 return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
Ted Kremenekd81a4a12012-09-21 00:52:24 +000047}
48
Ted Kremenek72418132012-09-21 17:54:35 +000049namespace {
50class ASTMaker {
51public:
52 ASTMaker(ASTContext &C) : C(C) {}
Fangrui Song6907ce22018-07-30 19:24:48 +000053
Ted Kremenekf465dc12012-09-21 18:33:54 +000054 /// Create a new BinaryOperator representing a simple assignment.
55 BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000056
Ted Kremenek089ffd02012-10-11 20:58:18 +000057 /// Create a new BinaryOperator representing a comparison.
58 BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
59 BinaryOperator::Opcode Op);
Fangrui Song6907ce22018-07-30 19:24:48 +000060
Ted Kremenek089ffd02012-10-11 20:58:18 +000061 /// Create a new compound stmt using the provided statements.
62 CompoundStmt *makeCompound(ArrayRef<Stmt*>);
Fangrui Song6907ce22018-07-30 19:24:48 +000063
Ted Kremenek69bcb822012-09-21 18:13:23 +000064 /// Create a new DeclRefExpr for the referenced variable.
George Karpenkov657a5892017-09-30 00:03:22 +000065 DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
George Karpenkovb2a60c62017-10-17 22:28:18 +000066 bool RefersToEnclosingVariableOrCapture = false);
Fangrui Song6907ce22018-07-30 19:24:48 +000067
Ted Kremenekdff35532012-09-21 18:33:52 +000068 /// Create a new UnaryOperator representing a dereference.
69 UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000070
Ted Kremenek69bcb822012-09-21 18:13:23 +000071 /// Create an implicit cast for an integer conversion.
Ted Kremenek6fdefb52012-10-12 00:18:19 +000072 Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000073
Ted Kremenek089ffd02012-10-11 20:58:18 +000074 /// Create an implicit cast to a builtin boolean type.
75 ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
Fangrui Song6907ce22018-07-30 19:24:48 +000076
George Karpenkov657a5892017-09-30 00:03:22 +000077 /// Create an implicit cast for lvalue-to-rvaluate conversions.
Ted Kremenekca90ea52012-09-21 18:13:27 +000078 ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
Fangrui Song6907ce22018-07-30 19:24:48 +000079
George Karpenkov657a5892017-09-30 00:03:22 +000080 /// Make RValue out of variable declaration, creating a temporary
81 /// DeclRefExpr in the process.
82 ImplicitCastExpr *
83 makeLvalueToRvalue(const VarDecl *Decl,
George Karpenkovb2a60c62017-10-17 22:28:18 +000084 bool RefersToEnclosingVariableOrCapture = false);
George Karpenkov657a5892017-09-30 00:03:22 +000085
86 /// Create an implicit cast of the given type.
87 ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
88 CastKind CK = CK_LValueToRValue);
89
Ted Kremenek089ffd02012-10-11 20:58:18 +000090 /// Create an Objective-C bool literal.
91 ObjCBoolLiteralExpr *makeObjCBool(bool Val);
Jordan Rose1a866cd2014-01-10 20:06:06 +000092
93 /// Create an Objective-C ivar reference.
94 ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
Fangrui Song6907ce22018-07-30 19:24:48 +000095
Ted Kremenek089ffd02012-10-11 20:58:18 +000096 /// Create a Return statement.
97 ReturnStmt *makeReturn(const Expr *RetVal);
Fangrui Song6907ce22018-07-30 19:24:48 +000098
Devin Coughlin046833e2017-11-06 22:12:19 +000099 /// Create an integer literal expression of the given type.
100 IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
George Karpenkov657a5892017-09-30 00:03:22 +0000101
102 /// Create a member expression.
103 MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
104 bool IsArrow = false,
105 ExprValueKind ValueKind = VK_LValue);
106
107 /// Returns a *first* member field of a record declaration with a given name.
108 /// \return an nullptr if no member with such a name exists.
George Karpenkovc928e1f2017-10-11 20:53:01 +0000109 ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
George Karpenkov657a5892017-09-30 00:03:22 +0000110
Ted Kremenek72418132012-09-21 17:54:35 +0000111private:
112 ASTContext &C;
113};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000114}
Ted Kremenek72418132012-09-21 17:54:35 +0000115
Ted Kremenekf465dc12012-09-21 18:33:54 +0000116BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
117 QualType Ty) {
118 return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
119 BO_Assign, Ty, VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +0000120 OK_Ordinary, SourceLocation(), FPOptions());
Ted Kremenekf465dc12012-09-21 18:33:54 +0000121}
122
Ted Kremenek089ffd02012-10-11 20:58:18 +0000123BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
124 BinaryOperator::Opcode Op) {
125 assert(BinaryOperator::isLogicalOp(Op) ||
126 BinaryOperator::isComparisonOp(Op));
127 return new (C) BinaryOperator(const_cast<Expr*>(LHS),
128 const_cast<Expr*>(RHS),
129 Op,
130 C.getLogicalOperationType(),
131 VK_RValue,
Adam Nemet484aa452017-03-27 19:17:25 +0000132 OK_Ordinary, SourceLocation(), FPOptions());
Ted Kremenek089ffd02012-10-11 20:58:18 +0000133}
134
135CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
Benjamin Kramer07420902017-12-24 16:24:20 +0000136 return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
Ted Kremenek089ffd02012-10-11 20:58:18 +0000137}
138
George Karpenkovb2a60c62017-10-17 22:28:18 +0000139DeclRefExpr *ASTMaker::makeDeclRefExpr(
140 const VarDecl *D,
141 bool RefersToEnclosingVariableOrCapture) {
142 QualType Type = D->getType().getNonReferenceType();
George Karpenkov657a5892017-09-30 00:03:22 +0000143
144 DeclRefExpr *DR = DeclRefExpr::Create(
145 C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
146 RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
Ted Kremenek72418132012-09-21 17:54:35 +0000147 return DR;
148}
149
Ted Kremenekdff35532012-09-21 18:33:52 +0000150UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
151 return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
Aaron Ballmana5038552018-01-09 13:07:03 +0000152 VK_LValue, OK_Ordinary, SourceLocation(),
153 /*CanOverflow*/ false);
Ted Kremenekdff35532012-09-21 18:33:52 +0000154}
155
Ted Kremenekca90ea52012-09-21 18:13:27 +0000156ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
George Karpenkov657a5892017-09-30 00:03:22 +0000157 return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
158}
159
George Karpenkov657a5892017-09-30 00:03:22 +0000160ImplicitCastExpr *
161ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000162 bool RefersToEnclosingVariableOrCapture) {
163 QualType Type = Arg->getType().getNonReferenceType();
George Karpenkov657a5892017-09-30 00:03:22 +0000164 return makeLvalueToRvalue(makeDeclRefExpr(Arg,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000165 RefersToEnclosingVariableOrCapture),
George Karpenkov657a5892017-09-30 00:03:22 +0000166 Type);
167}
168
169ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
170 CastKind CK) {
171 return ImplicitCastExpr::Create(C, Ty,
George Karpenkova1329382017-10-25 00:03:45 +0000172 /* CastKind=*/ CK,
173 /* Expr=*/ const_cast<Expr *>(Arg),
174 /* CXXCastPath=*/ nullptr,
175 /* ExprValueKind=*/ VK_RValue);
Ted Kremenekca90ea52012-09-21 18:13:27 +0000176}
177
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000178Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
179 if (Arg->getType() == Ty)
180 return const_cast<Expr*>(Arg);
Craig Topper25542942014-05-20 04:30:07 +0000181
Ted Kremenek69bcb822012-09-21 18:13:23 +0000182 return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
Craig Topper25542942014-05-20 04:30:07 +0000183 const_cast<Expr*>(Arg), nullptr, VK_RValue);
Ted Kremenek69bcb822012-09-21 18:13:23 +0000184}
185
Ted Kremenek089ffd02012-10-11 20:58:18 +0000186ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
187 return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
Craig Topper25542942014-05-20 04:30:07 +0000188 const_cast<Expr*>(Arg), nullptr, VK_RValue);
Ted Kremenek089ffd02012-10-11 20:58:18 +0000189}
190
191ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
192 QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
193 return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
194}
195
Jordan Rose1a866cd2014-01-10 20:06:06 +0000196ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
197 const ObjCIvarDecl *IVar) {
198 return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
199 IVar->getType(), SourceLocation(),
200 SourceLocation(), const_cast<Expr*>(Base),
201 /*arrow=*/true, /*free=*/false);
202}
203
Ted Kremenek089ffd02012-10-11 20:58:18 +0000204ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
Bruno Ricci023b1d12018-10-30 14:40:49 +0000205 return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
206 /* NRVOCandidate=*/nullptr);
Ted Kremenek089ffd02012-10-11 20:58:18 +0000207}
208
Devin Coughlin046833e2017-11-06 22:12:19 +0000209IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
210 llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
211 return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
George Karpenkov657a5892017-09-30 00:03:22 +0000212}
213
214MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
215 bool IsArrow,
216 ExprValueKind ValueKind) {
217
218 DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
219 return MemberExpr::Create(
220 C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
221 SourceLocation(), MemberDecl, FoundDecl,
222 DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
George Karpenkova1329382017-10-25 00:03:45 +0000223 /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
George Karpenkov657a5892017-09-30 00:03:22 +0000224 OK_Ordinary);
225}
226
George Karpenkovc928e1f2017-10-11 20:53:01 +0000227ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
George Karpenkov657a5892017-09-30 00:03:22 +0000228
229 CXXBasePaths Paths(
230 /* FindAmbiguities=*/false,
231 /* RecordPaths=*/false,
George Karpenkova1329382017-10-25 00:03:45 +0000232 /* DetectVirtual=*/ false);
George Karpenkov657a5892017-09-30 00:03:22 +0000233 const IdentifierInfo &II = C.Idents.get(Name);
234 DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
235
236 DeclContextLookupResult Decls = RD->lookup(DeclName);
237 for (NamedDecl *FoundDecl : Decls)
238 if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
George Karpenkovc928e1f2017-10-11 20:53:01 +0000239 return cast<ValueDecl>(FoundDecl);
George Karpenkov657a5892017-09-30 00:03:22 +0000240
241 return nullptr;
242}
243
Ted Kremenek2b5c83c2012-09-21 17:54:32 +0000244//===----------------------------------------------------------------------===//
245// Creation functions for faux ASTs.
246//===----------------------------------------------------------------------===//
247
248typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
249
George Karpenkov6dda6712017-10-02 21:01:46 +0000250static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
251 const ParmVarDecl *Callback,
252 ArrayRef<Expr *> CallArgs) {
George Karpenkov657a5892017-09-30 00:03:22 +0000253
George Karpenkov98e81cd2017-10-24 00:13:18 +0000254 QualType Ty = Callback->getType();
255 DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
George Karpenkovfaa03f42018-05-16 00:29:13 +0000256 Expr *SubExpr;
George Karpenkov98e81cd2017-10-24 00:13:18 +0000257 if (Ty->isRValueReferenceType()) {
George Karpenkovfaa03f42018-05-16 00:29:13 +0000258 SubExpr = M.makeImplicitCast(
259 Call, Ty.getNonReferenceType(), CK_LValueToRValue);
260 } else if (Ty->isLValueReferenceType() &&
261 Call->getType()->isFunctionType()) {
George Karpenkov98e81cd2017-10-24 00:13:18 +0000262 Ty = C.getPointerType(Ty.getNonReferenceType());
George Karpenkovfaa03f42018-05-16 00:29:13 +0000263 SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
264 } else if (Ty->isLValueReferenceType()
265 && Call->getType()->isPointerType()
266 && Call->getType()->getPointeeType()->isFunctionType()){
267 SubExpr = Call;
268 } else {
269 llvm_unreachable("Unexpected state");
George Karpenkov98e81cd2017-10-24 00:13:18 +0000270 }
271
272 return new (C)
George Karpenkovfaa03f42018-05-16 00:29:13 +0000273 CallExpr(C, SubExpr, CallArgs, C.VoidTy, VK_RValue, SourceLocation());
George Karpenkov657a5892017-09-30 00:03:22 +0000274}
275
George Karpenkov6dda6712017-10-02 21:01:46 +0000276static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
277 const ParmVarDecl *Callback,
George Karpenkovbd4254c2017-10-20 23:29:59 +0000278 CXXRecordDecl *CallbackDecl,
George Karpenkov6dda6712017-10-02 21:01:46 +0000279 ArrayRef<Expr *> CallArgs) {
George Karpenkov657a5892017-09-30 00:03:22 +0000280 assert(CallbackDecl != nullptr);
281 assert(CallbackDecl->isLambda());
282 FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
283 assert(callOperatorDecl != nullptr);
284
285 DeclRefExpr *callOperatorDeclRef =
George Karpenkova1329382017-10-25 00:03:45 +0000286 DeclRefExpr::Create(/* Ctx =*/ C,
287 /* QualifierLoc =*/ NestedNameSpecifierLoc(),
288 /* TemplateKWLoc =*/ SourceLocation(),
George Karpenkov657a5892017-09-30 00:03:22 +0000289 const_cast<FunctionDecl *>(callOperatorDecl),
George Karpenkova1329382017-10-25 00:03:45 +0000290 /* RefersToEnclosingVariableOrCapture=*/ false,
291 /* NameLoc =*/ SourceLocation(),
292 /* T =*/ callOperatorDecl->getType(),
293 /* VK =*/ VK_LValue);
George Karpenkov657a5892017-09-30 00:03:22 +0000294
George Karpenkov657a5892017-09-30 00:03:22 +0000295 return new (C)
296 CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
297 /*args=*/CallArgs,
298 /*QualType=*/C.VoidTy,
299 /*ExprValueType=*/VK_RValue,
300 /*SourceLocation=*/SourceLocation(), FPOptions());
301}
302
303/// Create a fake body for std::call_once.
304/// Emulates the following function body:
305///
306/// \code
307/// typedef struct once_flag_s {
308/// unsigned long __state = 0;
309/// } once_flag;
310/// template<class Callable>
311/// void call_once(once_flag& o, Callable func) {
312/// if (!o.__state) {
313/// func();
314/// }
315/// o.__state = 1;
316/// }
317/// \endcode
318static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000319 LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
George Karpenkov657a5892017-09-30 00:03:22 +0000320
321 // We need at least two parameters.
322 if (D->param_size() < 2)
323 return nullptr;
324
325 ASTMaker M(C);
326
327 const ParmVarDecl *Flag = D->getParamDecl(0);
328 const ParmVarDecl *Callback = D->getParamDecl(1);
George Karpenkov03544832017-11-03 00:36:03 +0000329
330 if (!Callback->getType()->isReferenceType()) {
331 llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
332 return nullptr;
333 }
334 if (!Flag->getType()->isReferenceType()) {
335 llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
336 return nullptr;
337 }
338
George Karpenkov657a5892017-09-30 00:03:22 +0000339 QualType CallbackType = Callback->getType().getNonReferenceType();
George Karpenkovbd4254c2017-10-20 23:29:59 +0000340
341 // Nullable pointer, non-null iff function is a CXXRecordDecl.
342 CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000343 QualType FlagType = Flag->getType().getNonReferenceType();
George Karpenkov39e51372018-07-28 02:16:13 +0000344 auto *FlagRecordDecl = FlagType->getAsRecordDecl();
George Karpenkovc928e1f2017-10-11 20:53:01 +0000345
346 if (!FlagRecordDecl) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000347 LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
348 << "unknown std::call_once implementation, "
349 << "ignoring the call.\n");
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000350 return nullptr;
351 }
352
George Karpenkovc928e1f2017-10-11 20:53:01 +0000353 // We initially assume libc++ implementation of call_once,
354 // where the once_flag struct has a field `__state_`.
355 ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
356
357 // Otherwise, try libstdc++ implementation, with a field
358 // `_M_once`
359 if (!FlagFieldDecl) {
George Karpenkovc928e1f2017-10-11 20:53:01 +0000360 FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
361 }
362
363 if (!FlagFieldDecl) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000364 LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
365 << "std::once_flag struct: unknown std::call_once "
366 << "implementation, ignoring the call.");
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000367 return nullptr;
368 }
George Karpenkov657a5892017-09-30 00:03:22 +0000369
George Karpenkovbd4254c2017-10-20 23:29:59 +0000370 bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
371 if (CallbackRecordDecl && !isLambdaCall) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000372 LLVM_DEBUG(llvm::dbgs()
373 << "Not supported: synthesizing body for functors when "
374 << "body farming std::call_once, ignoring the call.");
George Karpenkovbd4254c2017-10-20 23:29:59 +0000375 return nullptr;
376 }
George Karpenkov6dda6712017-10-02 21:01:46 +0000377
George Karpenkov657a5892017-09-30 00:03:22 +0000378 SmallVector<Expr *, 5> CallArgs;
George Karpenkovbd4254c2017-10-20 23:29:59 +0000379 const FunctionProtoType *CallbackFunctionType;
380 if (isLambdaCall) {
George Karpenkov657a5892017-09-30 00:03:22 +0000381
George Karpenkov6dda6712017-10-02 21:01:46 +0000382 // Lambda requires callback itself inserted as a first parameter.
383 CallArgs.push_back(
384 M.makeDeclRefExpr(Callback,
George Karpenkova1329382017-10-25 00:03:45 +0000385 /* RefersToEnclosingVariableOrCapture=*/ true));
George Karpenkovbd4254c2017-10-20 23:29:59 +0000386 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
387 ->getType()
388 ->getAs<FunctionProtoType>();
George Karpenkov98e81cd2017-10-24 00:13:18 +0000389 } else if (!CallbackType->getPointeeType().isNull()) {
George Karpenkovbd4254c2017-10-20 23:29:59 +0000390 CallbackFunctionType =
391 CallbackType->getPointeeType()->getAs<FunctionProtoType>();
George Karpenkov98e81cd2017-10-24 00:13:18 +0000392 } else {
393 CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
George Karpenkovbd4254c2017-10-20 23:29:59 +0000394 }
George Karpenkov6dda6712017-10-02 21:01:46 +0000395
George Karpenkovbd4254c2017-10-20 23:29:59 +0000396 if (!CallbackFunctionType)
397 return nullptr;
398
399 // First two arguments are used for the flag and for the callback.
400 if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000401 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
402 << "params passed to std::call_once, "
403 << "ignoring the call\n");
George Karpenkovbd4254c2017-10-20 23:29:59 +0000404 return nullptr;
405 }
406
407 // All arguments past first two ones are passed to the callback,
408 // and we turn lvalues into rvalues if the argument is not passed by
409 // reference.
410 for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
411 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
George Karpenkov59202322018-02-02 01:44:07 +0000412 if (PDecl &&
413 CallbackFunctionType->getParamType(ParamIdx - 2)
414 .getNonReferenceType()
415 .getCanonicalType() !=
416 PDecl->getType().getNonReferenceType().getCanonicalType()) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000417 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
418 << "params passed to std::call_once, "
419 << "ignoring the call\n");
George Karpenkov59202322018-02-02 01:44:07 +0000420 return nullptr;
421 }
George Karpenkovbd4254c2017-10-20 23:29:59 +0000422 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
423 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
424 QualType PTy = PDecl->getType().getNonReferenceType();
425 ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
426 }
427 CallArgs.push_back(ParamExpr);
428 }
George Karpenkov657a5892017-09-30 00:03:22 +0000429
430 CallExpr *CallbackCall;
George Karpenkov6dda6712017-10-02 21:01:46 +0000431 if (isLambdaCall) {
George Karpenkov657a5892017-09-30 00:03:22 +0000432
George Karpenkovbd4254c2017-10-20 23:29:59 +0000433 CallbackCall = create_call_once_lambda_call(C, M, Callback,
434 CallbackRecordDecl, CallArgs);
George Karpenkov657a5892017-09-30 00:03:22 +0000435 } else {
436
437 // Function pointer case.
438 CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
439 }
440
George Karpenkov657a5892017-09-30 00:03:22 +0000441 DeclRefExpr *FlagDecl =
442 M.makeDeclRefExpr(Flag,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000443 /* RefersToEnclosingVariableOrCapture=*/true);
George Karpenkov657a5892017-09-30 00:03:22 +0000444
George Karpenkov657a5892017-09-30 00:03:22 +0000445
George Karpenkovc928e1f2017-10-11 20:53:01 +0000446 MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
George Karpenkov657a5892017-09-30 00:03:22 +0000447 assert(Deref->isLValue());
448 QualType DerefType = Deref->getType();
449
450 // Negation predicate.
451 UnaryOperator *FlagCheck = new (C) UnaryOperator(
George Karpenkova1329382017-10-25 00:03:45 +0000452 /* input=*/
George Karpenkov657a5892017-09-30 00:03:22 +0000453 M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
454 CK_IntegralToBoolean),
George Karpenkova1329382017-10-25 00:03:45 +0000455 /* opc=*/ UO_LNot,
456 /* QualType=*/ C.IntTy,
457 /* ExprValueKind=*/ VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +0000458 /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
459 /* CanOverflow*/ false);
George Karpenkov657a5892017-09-30 00:03:22 +0000460
461 // Create assignment.
462 BinaryOperator *FlagAssignment = M.makeAssignment(
Devin Coughlin046833e2017-11-06 22:12:19 +0000463 Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
464 DerefType);
George Karpenkov657a5892017-09-30 00:03:22 +0000465
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000466 auto *Out =
467 IfStmt::Create(C, SourceLocation(),
468 /* IsConstexpr=*/false,
469 /* init=*/nullptr,
470 /* var=*/nullptr,
471 /* cond=*/FlagCheck,
472 /* then=*/M.makeCompound({CallbackCall, FlagAssignment}));
George Karpenkov657a5892017-09-30 00:03:22 +0000473
474 return Out;
475}
476
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000477/// Create a fake body for dispatch_once.
478static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
479 // Check if we have at least two parameters.
480 if (D->param_size() != 2)
Craig Topper25542942014-05-20 04:30:07 +0000481 return nullptr;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000482
483 // Check if the first parameter is a pointer to integer type.
484 const ParmVarDecl *Predicate = D->getParamDecl(0);
485 QualType PredicateQPtrTy = Predicate->getType();
486 const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
487 if (!PredicatePtrTy)
Craig Topper25542942014-05-20 04:30:07 +0000488 return nullptr;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000489 QualType PredicateTy = PredicatePtrTy->getPointeeType();
490 if (!PredicateTy->isIntegerType())
Craig Topper25542942014-05-20 04:30:07 +0000491 return nullptr;
492
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000493 // Check if the second parameter is the proper block type.
494 const ParmVarDecl *Block = D->getParamDecl(1);
495 QualType Ty = Block->getType();
496 if (!isDispatchBlock(Ty))
Craig Topper25542942014-05-20 04:30:07 +0000497 return nullptr;
498
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000499 // Everything checks out. Create a fakse body that checks the predicate,
500 // sets it, and calls the block. Basically, an AST dump of:
501 //
502 // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
Devin Coughlin046833e2017-11-06 22:12:19 +0000503 // if (*predicate != ~0l) {
504 // *predicate = ~0l;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000505 // block();
506 // }
507 // }
Fangrui Song6907ce22018-07-30 19:24:48 +0000508
Ted Kremenek72418132012-09-21 17:54:35 +0000509 ASTMaker M(C);
Fangrui Song6907ce22018-07-30 19:24:48 +0000510
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000511 // (1) Create the call.
George Karpenkov657a5892017-09-30 00:03:22 +0000512 CallExpr *CE = new (C) CallExpr(
513 /*ASTContext=*/C,
514 /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
515 /*args=*/None,
516 /*QualType=*/C.VoidTy,
517 /*ExprValueType=*/VK_RValue,
518 /*SourceLocation=*/SourceLocation());
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000519
520 // (2) Create the assignment to the predicate.
Devin Coughlin046833e2017-11-06 22:12:19 +0000521 Expr *DoneValue =
522 new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
Aaron Ballmana5038552018-01-09 13:07:03 +0000523 VK_RValue, OK_Ordinary, SourceLocation(),
524 /*CanOverflow*/false);
George Karpenkov657a5892017-09-30 00:03:22 +0000525
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000526 BinaryOperator *B =
527 M.makeAssignment(
528 M.makeDereference(
529 M.makeLvalueToRvalue(
530 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
531 PredicateTy),
Devin Coughlin046833e2017-11-06 22:12:19 +0000532 M.makeIntegralCast(DoneValue, PredicateTy),
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000533 PredicateTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000534
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000535 // (3) Create the compound statement.
Craig Topper5fc8fc22014-08-27 06:28:36 +0000536 Stmt *Stmts[] = { B, CE };
537 CompoundStmt *CS = M.makeCompound(Stmts);
Fangrui Song6907ce22018-07-30 19:24:48 +0000538
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000539 // (4) Create the 'if' condition.
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000540 ImplicitCastExpr *LValToRval =
541 M.makeLvalueToRvalue(
542 M.makeDereference(
543 M.makeLvalueToRvalue(
544 M.makeDeclRefExpr(Predicate),
545 PredicateQPtrTy),
546 PredicateTy),
547 PredicateTy);
Devin Coughlin046833e2017-11-06 22:12:19 +0000548
549 Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000550 // (5) Create the 'if' statement.
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000551 auto *If = IfStmt::Create(C, SourceLocation(),
552 /* IsConstexpr=*/false,
553 /* init=*/nullptr,
554 /* var=*/nullptr,
555 /* cond=*/GuardCondition,
556 /* then=*/CS);
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000557 return If;
558}
559
Ted Kremenek14f779c2012-09-21 00:09:11 +0000560/// Create a fake body for dispatch_sync.
561static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
562 // Check if we have at least two parameters.
563 if (D->param_size() != 2)
Craig Topper25542942014-05-20 04:30:07 +0000564 return nullptr;
565
Ted Kremenek14f779c2012-09-21 00:09:11 +0000566 // Check if the second parameter is a block.
567 const ParmVarDecl *PV = D->getParamDecl(1);
568 QualType Ty = PV->getType();
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000569 if (!isDispatchBlock(Ty))
Craig Topper25542942014-05-20 04:30:07 +0000570 return nullptr;
571
Ted Kremenek14f779c2012-09-21 00:09:11 +0000572 // Everything checks out. Create a fake body that just calls the block.
573 // This is basically just an AST dump of:
574 //
575 // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
576 // block();
577 // }
Fangrui Song6907ce22018-07-30 19:24:48 +0000578 //
Ted Kremenek72418132012-09-21 17:54:35 +0000579 ASTMaker M(C);
580 DeclRefExpr *DR = M.makeDeclRefExpr(PV);
Ted Kremenekdff35532012-09-21 18:33:52 +0000581 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000582 CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
583 SourceLocation());
Ted Kremenek14f779c2012-09-21 00:09:11 +0000584 return CE;
585}
586
Ted Kremenek089ffd02012-10-11 20:58:18 +0000587static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
588{
589 // There are exactly 3 arguments.
590 if (D->param_size() != 3)
Craig Topper25542942014-05-20 04:30:07 +0000591 return nullptr;
592
Anna Zaks064185a2013-02-05 19:52:26 +0000593 // Signature:
594 // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
595 // void *__newValue,
596 // void * volatile *__theValue)
597 // Generate body:
Ted Kremenek089ffd02012-10-11 20:58:18 +0000598 // if (oldValue == *theValue) {
599 // *theValue = newValue;
600 // return YES;
601 // }
602 // else return NO;
Alp Toker314cc812014-01-25 16:55:45 +0000603
604 QualType ResultTy = D->getReturnType();
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000605 bool isBoolean = ResultTy->isBooleanType();
606 if (!isBoolean && !ResultTy->isIntegralType(C))
Craig Topper25542942014-05-20 04:30:07 +0000607 return nullptr;
608
Ted Kremenek089ffd02012-10-11 20:58:18 +0000609 const ParmVarDecl *OldValue = D->getParamDecl(0);
610 QualType OldValueTy = OldValue->getType();
611
612 const ParmVarDecl *NewValue = D->getParamDecl(1);
613 QualType NewValueTy = NewValue->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Ted Kremenek089ffd02012-10-11 20:58:18 +0000615 assert(OldValueTy == NewValueTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000616
Ted Kremenek089ffd02012-10-11 20:58:18 +0000617 const ParmVarDecl *TheValue = D->getParamDecl(2);
618 QualType TheValueTy = TheValue->getType();
619 const PointerType *PT = TheValueTy->getAs<PointerType>();
620 if (!PT)
Craig Topper25542942014-05-20 04:30:07 +0000621 return nullptr;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000622 QualType PointeeTy = PT->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000623
Ted Kremenek089ffd02012-10-11 20:58:18 +0000624 ASTMaker M(C);
625 // Construct the comparison.
626 Expr *Comparison =
627 M.makeComparison(
628 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
629 M.makeLvalueToRvalue(
630 M.makeDereference(
631 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
632 PointeeTy),
633 PointeeTy),
634 BO_EQ);
635
636 // Construct the body of the IfStmt.
637 Stmt *Stmts[2];
638 Stmts[0] =
639 M.makeAssignment(
640 M.makeDereference(
641 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
642 PointeeTy),
643 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
644 NewValueTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000645
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000646 Expr *BoolVal = M.makeObjCBool(true);
647 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
648 : M.makeIntegralCast(BoolVal, ResultTy);
649 Stmts[1] = M.makeReturn(RetVal);
Craig Topper5fc8fc22014-08-27 06:28:36 +0000650 CompoundStmt *Body = M.makeCompound(Stmts);
Fangrui Song6907ce22018-07-30 19:24:48 +0000651
Ted Kremenek089ffd02012-10-11 20:58:18 +0000652 // Construct the else clause.
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000653 BoolVal = M.makeObjCBool(false);
654 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
655 : M.makeIntegralCast(BoolVal, ResultTy);
656 Stmt *Else = M.makeReturn(RetVal);
Fangrui Song6907ce22018-07-30 19:24:48 +0000657
Ted Kremenek089ffd02012-10-11 20:58:18 +0000658 /// Construct the If.
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000659 auto *If = IfStmt::Create(C, SourceLocation(),
660 /* IsConstexpr=*/false,
661 /* init=*/nullptr,
662 /* var=*/nullptr, Comparison, Body,
663 SourceLocation(), Else);
Craig Topper25542942014-05-20 04:30:07 +0000664
Fangrui Song6907ce22018-07-30 19:24:48 +0000665 return If;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000666}
667
Ted Kremenek14f779c2012-09-21 00:09:11 +0000668Stmt *BodyFarm::getBody(const FunctionDecl *D) {
669 D = D->getCanonicalDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000670
David Blaikie05785d12013-02-20 22:23:23 +0000671 Optional<Stmt *> &Val = Bodies[D];
Ted Kremenek14f779c2012-09-21 00:09:11 +0000672 if (Val.hasValue())
673 return Val.getValue();
Craig Topper25542942014-05-20 04:30:07 +0000674
675 Val = nullptr;
676
677 if (D->getIdentifier() == nullptr)
678 return nullptr;
Ted Kremenek14f779c2012-09-21 00:09:11 +0000679
680 StringRef Name = D->getName();
681 if (Name.empty())
Craig Topper25542942014-05-20 04:30:07 +0000682 return nullptr;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000683
684 FunctionFarmer FF;
685
686 if (Name.startswith("OSAtomicCompareAndSwap") ||
687 Name.startswith("objc_atomicCompareAndSwap")) {
688 FF = create_OSAtomicCompareAndSwap;
George Karpenkov657a5892017-09-30 00:03:22 +0000689 } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
690 FF = create_call_once;
691 } else {
Ted Kremenek089ffd02012-10-11 20:58:18 +0000692 FF = llvm::StringSwitch<FunctionFarmer>(Name)
693 .Case("dispatch_sync", create_dispatch_sync)
694 .Case("dispatch_once", create_dispatch_once)
Craig Topper25542942014-05-20 04:30:07 +0000695 .Default(nullptr);
Ted Kremenek14f779c2012-09-21 00:09:11 +0000696 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000697
Ted Kremenek089ffd02012-10-11 20:58:18 +0000698 if (FF) { Val = FF(C, D); }
Ted Kremenekeeccb302014-08-27 15:14:15 +0000699 else if (Injector) { Val = Injector->getBody(D); }
Ted Kremenek14f779c2012-09-21 00:09:11 +0000700 return Val.getValue();
701}
702
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000703static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
704 const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
705
706 if (IVar)
707 return IVar;
708
709 // When a readonly property is shadowed in a class extensions with a
710 // a readwrite property, the instance variable belongs to the shadowing
711 // property rather than the shadowed property. If there is no instance
712 // variable on a readonly property, check to see whether the property is
713 // shadowed and if so try to get the instance variable from shadowing
714 // property.
715 if (!Prop->isReadOnly())
716 return nullptr;
717
718 auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
719 const ObjCInterfaceDecl *PrimaryInterface = nullptr;
720 if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
721 PrimaryInterface = InterfaceDecl;
722 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
723 PrimaryInterface = CategoryDecl->getClassInterface();
724 } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
725 PrimaryInterface = ImplDecl->getClassInterface();
726 } else {
727 return nullptr;
728 }
729
730 // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
731 // is guaranteed to find the shadowing property, if it exists, rather than
732 // the shadowed property.
733 auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
Manman Ren5b786402016-01-28 18:49:28 +0000734 Prop->getIdentifier(), Prop->getQueryKind());
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000735 if (ShadowingProp && ShadowingProp != Prop) {
736 IVar = ShadowingProp->getPropertyIvarDecl();
737 }
738
739 return IVar;
740}
741
Jordan Rose1a866cd2014-01-10 20:06:06 +0000742static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
743 const ObjCPropertyDecl *Prop) {
Jordan Roseddf19662014-01-23 03:59:10 +0000744 // First, find the backing ivar.
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000745 const ObjCIvarDecl *IVar = findBackingIvar(Prop);
Jordan Rose1a866cd2014-01-10 20:06:06 +0000746 if (!IVar)
Craig Topper25542942014-05-20 04:30:07 +0000747 return nullptr;
Jordan Roseddf19662014-01-23 03:59:10 +0000748
749 // Ignore weak variables, which have special behavior.
Jordan Rose1a866cd2014-01-10 20:06:06 +0000750 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
Craig Topper25542942014-05-20 04:30:07 +0000751 return nullptr;
Jordan Rosea3f27812014-01-14 17:29:06 +0000752
Jordan Roseddf19662014-01-23 03:59:10 +0000753 // Look to see if Sema has synthesized a body for us. This happens in
754 // Objective-C++ because the return value may be a C++ class type with a
755 // non-trivial copy constructor. We can only do this if we can find the
756 // @synthesize for this property, though (or if we know it's been auto-
757 // synthesized).
Jordan Rosea3f27812014-01-14 17:29:06 +0000758 const ObjCImplementationDecl *ImplDecl =
759 IVar->getContainingInterface()->getImplementation();
760 if (ImplDecl) {
Aaron Ballmand85eff42014-03-14 15:02:45 +0000761 for (const auto *I : ImplDecl->property_impls()) {
Jordan Rosea3f27812014-01-14 17:29:06 +0000762 if (I->getPropertyDecl() != Prop)
763 continue;
764
765 if (I->getGetterCXXConstructor()) {
766 ASTMaker M(Ctx);
767 return M.makeReturn(I->getGetterCXXConstructor());
768 }
769 }
770 }
771
Jordan Roseddf19662014-01-23 03:59:10 +0000772 // Sanity check that the property is the same type as the ivar, or a
773 // reference to it, and that it is either an object pointer or trivially
774 // copyable.
775 if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
776 Prop->getType().getNonReferenceType()))
Craig Topper25542942014-05-20 04:30:07 +0000777 return nullptr;
Jordan Roseddf19662014-01-23 03:59:10 +0000778 if (!IVar->getType()->isObjCLifetimeType() &&
779 !IVar->getType().isTriviallyCopyableType(Ctx))
Craig Topper25542942014-05-20 04:30:07 +0000780 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000781
Jordan Roseddf19662014-01-23 03:59:10 +0000782 // Generate our body:
783 // return self->_ivar;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000784 ASTMaker M(Ctx);
785
786 const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
Devin Coughlinaac894f2017-01-11 01:02:34 +0000787 if (!selfVar)
788 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000789
790 Expr *loadedIVar =
791 M.makeObjCIvarRef(
792 M.makeLvalueToRvalue(
793 M.makeDeclRefExpr(selfVar),
794 selfVar->getType()),
795 IVar);
796
797 if (!Prop->getType()->isReferenceType())
798 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
799
800 return M.makeReturn(loadedIVar);
801}
802
Jordan Roseddf19662014-01-23 03:59:10 +0000803Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
804 // We currently only know how to synthesize property accessors.
Jordan Rose1a866cd2014-01-10 20:06:06 +0000805 if (!D->isPropertyAccessor())
Craig Topper25542942014-05-20 04:30:07 +0000806 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000807
808 D = D->getCanonicalDecl();
809
810 Optional<Stmt *> &Val = Bodies[D];
811 if (Val.hasValue())
812 return Val.getValue();
Craig Topper25542942014-05-20 04:30:07 +0000813 Val = nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000814
Jordan Roseddf19662014-01-23 03:59:10 +0000815 const ObjCPropertyDecl *Prop = D->findPropertyDecl();
Jordan Rose1a866cd2014-01-10 20:06:06 +0000816 if (!Prop)
Craig Topper25542942014-05-20 04:30:07 +0000817 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000818
Jordan Roseddf19662014-01-23 03:59:10 +0000819 // For now, we only synthesize getters.
Devin Coughlinef3697e2016-02-18 19:37:39 +0000820 // Synthesizing setters would cause false negatives in the
821 // RetainCountChecker because the method body would bind the parameter
822 // to an instance variable, causing it to escape. This would prevent
823 // warning in the following common scenario:
824 //
825 // id foo = [[NSObject alloc] init];
826 // self.foo = foo; // We should warn that foo leaks here.
827 //
Jordan Rose1a866cd2014-01-10 20:06:06 +0000828 if (D->param_size() != 0)
Craig Topper25542942014-05-20 04:30:07 +0000829 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000830
831 Val = createObjCPropertyGetter(C, Prop);
832
833 return Val.getValue();
834}