blob: 57e7d8dfdb070f52885563e4ae2fe03a823fba0d [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
204
Ted Kremenek089ffd02012-10-11 20:58:18 +0000205ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
Craig Topper25542942014-05-20 04:30:07 +0000206 return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
207 nullptr);
Ted Kremenek089ffd02012-10-11 20:58:18 +0000208}
209
Devin Coughlin046833e2017-11-06 22:12:19 +0000210IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
211 llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
212 return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
George Karpenkov657a5892017-09-30 00:03:22 +0000213}
214
215MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
216 bool IsArrow,
217 ExprValueKind ValueKind) {
218
219 DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
220 return MemberExpr::Create(
221 C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
222 SourceLocation(), MemberDecl, FoundDecl,
223 DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
George Karpenkova1329382017-10-25 00:03:45 +0000224 /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
George Karpenkov657a5892017-09-30 00:03:22 +0000225 OK_Ordinary);
226}
227
George Karpenkovc928e1f2017-10-11 20:53:01 +0000228ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
George Karpenkov657a5892017-09-30 00:03:22 +0000229
230 CXXBasePaths Paths(
231 /* FindAmbiguities=*/false,
232 /* RecordPaths=*/false,
George Karpenkova1329382017-10-25 00:03:45 +0000233 /* DetectVirtual=*/ false);
George Karpenkov657a5892017-09-30 00:03:22 +0000234 const IdentifierInfo &II = C.Idents.get(Name);
235 DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
236
237 DeclContextLookupResult Decls = RD->lookup(DeclName);
238 for (NamedDecl *FoundDecl : Decls)
239 if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
George Karpenkovc928e1f2017-10-11 20:53:01 +0000240 return cast<ValueDecl>(FoundDecl);
George Karpenkov657a5892017-09-30 00:03:22 +0000241
242 return nullptr;
243}
244
Ted Kremenek2b5c83c2012-09-21 17:54:32 +0000245//===----------------------------------------------------------------------===//
246// Creation functions for faux ASTs.
247//===----------------------------------------------------------------------===//
248
249typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
250
George Karpenkov6dda6712017-10-02 21:01:46 +0000251static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
252 const ParmVarDecl *Callback,
253 ArrayRef<Expr *> CallArgs) {
George Karpenkov657a5892017-09-30 00:03:22 +0000254
George Karpenkov98e81cd2017-10-24 00:13:18 +0000255 QualType Ty = Callback->getType();
256 DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
George Karpenkovfaa03f42018-05-16 00:29:13 +0000257 Expr *SubExpr;
George Karpenkov98e81cd2017-10-24 00:13:18 +0000258 if (Ty->isRValueReferenceType()) {
George Karpenkovfaa03f42018-05-16 00:29:13 +0000259 SubExpr = M.makeImplicitCast(
260 Call, Ty.getNonReferenceType(), CK_LValueToRValue);
261 } else if (Ty->isLValueReferenceType() &&
262 Call->getType()->isFunctionType()) {
George Karpenkov98e81cd2017-10-24 00:13:18 +0000263 Ty = C.getPointerType(Ty.getNonReferenceType());
George Karpenkovfaa03f42018-05-16 00:29:13 +0000264 SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
265 } else if (Ty->isLValueReferenceType()
266 && Call->getType()->isPointerType()
267 && Call->getType()->getPointeeType()->isFunctionType()){
268 SubExpr = Call;
269 } else {
270 llvm_unreachable("Unexpected state");
George Karpenkov98e81cd2017-10-24 00:13:18 +0000271 }
272
273 return new (C)
George Karpenkovfaa03f42018-05-16 00:29:13 +0000274 CallExpr(C, SubExpr, CallArgs, C.VoidTy, VK_RValue, SourceLocation());
George Karpenkov657a5892017-09-30 00:03:22 +0000275}
276
George Karpenkov6dda6712017-10-02 21:01:46 +0000277static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
278 const ParmVarDecl *Callback,
George Karpenkovbd4254c2017-10-20 23:29:59 +0000279 CXXRecordDecl *CallbackDecl,
George Karpenkov6dda6712017-10-02 21:01:46 +0000280 ArrayRef<Expr *> CallArgs) {
George Karpenkov657a5892017-09-30 00:03:22 +0000281 assert(CallbackDecl != nullptr);
282 assert(CallbackDecl->isLambda());
283 FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
284 assert(callOperatorDecl != nullptr);
285
286 DeclRefExpr *callOperatorDeclRef =
George Karpenkova1329382017-10-25 00:03:45 +0000287 DeclRefExpr::Create(/* Ctx =*/ C,
288 /* QualifierLoc =*/ NestedNameSpecifierLoc(),
289 /* TemplateKWLoc =*/ SourceLocation(),
George Karpenkov657a5892017-09-30 00:03:22 +0000290 const_cast<FunctionDecl *>(callOperatorDecl),
George Karpenkova1329382017-10-25 00:03:45 +0000291 /* RefersToEnclosingVariableOrCapture=*/ false,
292 /* NameLoc =*/ SourceLocation(),
293 /* T =*/ callOperatorDecl->getType(),
294 /* VK =*/ VK_LValue);
George Karpenkov657a5892017-09-30 00:03:22 +0000295
George Karpenkov657a5892017-09-30 00:03:22 +0000296 return new (C)
297 CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
298 /*args=*/CallArgs,
299 /*QualType=*/C.VoidTy,
300 /*ExprValueType=*/VK_RValue,
301 /*SourceLocation=*/SourceLocation(), FPOptions());
302}
303
304/// Create a fake body for std::call_once.
305/// Emulates the following function body:
306///
307/// \code
308/// typedef struct once_flag_s {
309/// unsigned long __state = 0;
310/// } once_flag;
311/// template<class Callable>
312/// void call_once(once_flag& o, Callable func) {
313/// if (!o.__state) {
314/// func();
315/// }
316/// o.__state = 1;
317/// }
318/// \endcode
319static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000320 LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
George Karpenkov657a5892017-09-30 00:03:22 +0000321
322 // We need at least two parameters.
323 if (D->param_size() < 2)
324 return nullptr;
325
326 ASTMaker M(C);
327
328 const ParmVarDecl *Flag = D->getParamDecl(0);
329 const ParmVarDecl *Callback = D->getParamDecl(1);
George Karpenkov03544832017-11-03 00:36:03 +0000330
331 if (!Callback->getType()->isReferenceType()) {
332 llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
333 return nullptr;
334 }
335 if (!Flag->getType()->isReferenceType()) {
336 llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
337 return nullptr;
338 }
339
George Karpenkov657a5892017-09-30 00:03:22 +0000340 QualType CallbackType = Callback->getType().getNonReferenceType();
George Karpenkovbd4254c2017-10-20 23:29:59 +0000341
342 // Nullable pointer, non-null iff function is a CXXRecordDecl.
343 CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000344 QualType FlagType = Flag->getType().getNonReferenceType();
George Karpenkov39e51372018-07-28 02:16:13 +0000345 auto *FlagRecordDecl = FlagType->getAsRecordDecl();
George Karpenkovc928e1f2017-10-11 20:53:01 +0000346
347 if (!FlagRecordDecl) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000348 LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
349 << "unknown std::call_once implementation, "
350 << "ignoring the call.\n");
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000351 return nullptr;
352 }
353
George Karpenkovc928e1f2017-10-11 20:53:01 +0000354 // We initially assume libc++ implementation of call_once,
355 // where the once_flag struct has a field `__state_`.
356 ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
357
358 // Otherwise, try libstdc++ implementation, with a field
359 // `_M_once`
360 if (!FlagFieldDecl) {
George Karpenkovc928e1f2017-10-11 20:53:01 +0000361 FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
362 }
363
364 if (!FlagFieldDecl) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000365 LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
366 << "std::once_flag struct: unknown std::call_once "
367 << "implementation, ignoring the call.");
George Karpenkov8b53f7c2017-10-09 23:20:46 +0000368 return nullptr;
369 }
George Karpenkov657a5892017-09-30 00:03:22 +0000370
George Karpenkovbd4254c2017-10-20 23:29:59 +0000371 bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
372 if (CallbackRecordDecl && !isLambdaCall) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000373 LLVM_DEBUG(llvm::dbgs()
374 << "Not supported: synthesizing body for functors when "
375 << "body farming std::call_once, ignoring the call.");
George Karpenkovbd4254c2017-10-20 23:29:59 +0000376 return nullptr;
377 }
George Karpenkov6dda6712017-10-02 21:01:46 +0000378
George Karpenkov657a5892017-09-30 00:03:22 +0000379 SmallVector<Expr *, 5> CallArgs;
George Karpenkovbd4254c2017-10-20 23:29:59 +0000380 const FunctionProtoType *CallbackFunctionType;
381 if (isLambdaCall) {
George Karpenkov657a5892017-09-30 00:03:22 +0000382
George Karpenkov6dda6712017-10-02 21:01:46 +0000383 // Lambda requires callback itself inserted as a first parameter.
384 CallArgs.push_back(
385 M.makeDeclRefExpr(Callback,
George Karpenkova1329382017-10-25 00:03:45 +0000386 /* RefersToEnclosingVariableOrCapture=*/ true));
George Karpenkovbd4254c2017-10-20 23:29:59 +0000387 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
388 ->getType()
389 ->getAs<FunctionProtoType>();
George Karpenkov98e81cd2017-10-24 00:13:18 +0000390 } else if (!CallbackType->getPointeeType().isNull()) {
George Karpenkovbd4254c2017-10-20 23:29:59 +0000391 CallbackFunctionType =
392 CallbackType->getPointeeType()->getAs<FunctionProtoType>();
George Karpenkov98e81cd2017-10-24 00:13:18 +0000393 } else {
394 CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
George Karpenkovbd4254c2017-10-20 23:29:59 +0000395 }
George Karpenkov6dda6712017-10-02 21:01:46 +0000396
George Karpenkovbd4254c2017-10-20 23:29:59 +0000397 if (!CallbackFunctionType)
398 return nullptr;
399
400 // First two arguments are used for the flag and for the callback.
401 if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000402 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
403 << "params passed to std::call_once, "
404 << "ignoring the call\n");
George Karpenkovbd4254c2017-10-20 23:29:59 +0000405 return nullptr;
406 }
407
408 // All arguments past first two ones are passed to the callback,
409 // and we turn lvalues into rvalues if the argument is not passed by
410 // reference.
411 for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
412 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
George Karpenkov59202322018-02-02 01:44:07 +0000413 if (PDecl &&
414 CallbackFunctionType->getParamType(ParamIdx - 2)
415 .getNonReferenceType()
416 .getCanonicalType() !=
417 PDecl->getType().getNonReferenceType().getCanonicalType()) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000418 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
419 << "params passed to std::call_once, "
420 << "ignoring the call\n");
George Karpenkov59202322018-02-02 01:44:07 +0000421 return nullptr;
422 }
George Karpenkovbd4254c2017-10-20 23:29:59 +0000423 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
424 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
425 QualType PTy = PDecl->getType().getNonReferenceType();
426 ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
427 }
428 CallArgs.push_back(ParamExpr);
429 }
George Karpenkov657a5892017-09-30 00:03:22 +0000430
431 CallExpr *CallbackCall;
George Karpenkov6dda6712017-10-02 21:01:46 +0000432 if (isLambdaCall) {
George Karpenkov657a5892017-09-30 00:03:22 +0000433
George Karpenkovbd4254c2017-10-20 23:29:59 +0000434 CallbackCall = create_call_once_lambda_call(C, M, Callback,
435 CallbackRecordDecl, CallArgs);
George Karpenkov657a5892017-09-30 00:03:22 +0000436 } else {
437
438 // Function pointer case.
439 CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
440 }
441
George Karpenkov657a5892017-09-30 00:03:22 +0000442 DeclRefExpr *FlagDecl =
443 M.makeDeclRefExpr(Flag,
George Karpenkovb2a60c62017-10-17 22:28:18 +0000444 /* RefersToEnclosingVariableOrCapture=*/true);
George Karpenkov657a5892017-09-30 00:03:22 +0000445
George Karpenkov657a5892017-09-30 00:03:22 +0000446
George Karpenkovc928e1f2017-10-11 20:53:01 +0000447 MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
George Karpenkov657a5892017-09-30 00:03:22 +0000448 assert(Deref->isLValue());
449 QualType DerefType = Deref->getType();
450
451 // Negation predicate.
452 UnaryOperator *FlagCheck = new (C) UnaryOperator(
George Karpenkova1329382017-10-25 00:03:45 +0000453 /* input=*/
George Karpenkov657a5892017-09-30 00:03:22 +0000454 M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
455 CK_IntegralToBoolean),
George Karpenkova1329382017-10-25 00:03:45 +0000456 /* opc=*/ UO_LNot,
457 /* QualType=*/ C.IntTy,
458 /* ExprValueKind=*/ VK_RValue,
Aaron Ballmana5038552018-01-09 13:07:03 +0000459 /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
460 /* CanOverflow*/ false);
George Karpenkov657a5892017-09-30 00:03:22 +0000461
462 // Create assignment.
463 BinaryOperator *FlagAssignment = M.makeAssignment(
Devin Coughlin046833e2017-11-06 22:12:19 +0000464 Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
465 DerefType);
George Karpenkov657a5892017-09-30 00:03:22 +0000466
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000467 auto *Out =
468 IfStmt::Create(C, SourceLocation(),
469 /* IsConstexpr=*/false,
470 /* init=*/nullptr,
471 /* var=*/nullptr,
472 /* cond=*/FlagCheck,
473 /* then=*/M.makeCompound({CallbackCall, FlagAssignment}));
George Karpenkov657a5892017-09-30 00:03:22 +0000474
475 return Out;
476}
477
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000478/// Create a fake body for dispatch_once.
479static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
480 // Check if we have at least two parameters.
481 if (D->param_size() != 2)
Craig Topper25542942014-05-20 04:30:07 +0000482 return nullptr;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000483
484 // Check if the first parameter is a pointer to integer type.
485 const ParmVarDecl *Predicate = D->getParamDecl(0);
486 QualType PredicateQPtrTy = Predicate->getType();
487 const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
488 if (!PredicatePtrTy)
Craig Topper25542942014-05-20 04:30:07 +0000489 return nullptr;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000490 QualType PredicateTy = PredicatePtrTy->getPointeeType();
491 if (!PredicateTy->isIntegerType())
Craig Topper25542942014-05-20 04:30:07 +0000492 return nullptr;
493
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000494 // Check if the second parameter is the proper block type.
495 const ParmVarDecl *Block = D->getParamDecl(1);
496 QualType Ty = Block->getType();
497 if (!isDispatchBlock(Ty))
Craig Topper25542942014-05-20 04:30:07 +0000498 return nullptr;
499
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000500 // Everything checks out. Create a fakse body that checks the predicate,
501 // sets it, and calls the block. Basically, an AST dump of:
502 //
503 // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
Devin Coughlin046833e2017-11-06 22:12:19 +0000504 // if (*predicate != ~0l) {
505 // *predicate = ~0l;
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000506 // block();
507 // }
508 // }
Fangrui Song6907ce22018-07-30 19:24:48 +0000509
Ted Kremenek72418132012-09-21 17:54:35 +0000510 ASTMaker M(C);
Fangrui Song6907ce22018-07-30 19:24:48 +0000511
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000512 // (1) Create the call.
George Karpenkov657a5892017-09-30 00:03:22 +0000513 CallExpr *CE = new (C) CallExpr(
514 /*ASTContext=*/C,
515 /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
516 /*args=*/None,
517 /*QualType=*/C.VoidTy,
518 /*ExprValueType=*/VK_RValue,
519 /*SourceLocation=*/SourceLocation());
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000520
521 // (2) Create the assignment to the predicate.
Devin Coughlin046833e2017-11-06 22:12:19 +0000522 Expr *DoneValue =
523 new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
Aaron Ballmana5038552018-01-09 13:07:03 +0000524 VK_RValue, OK_Ordinary, SourceLocation(),
525 /*CanOverflow*/false);
George Karpenkov657a5892017-09-30 00:03:22 +0000526
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000527 BinaryOperator *B =
528 M.makeAssignment(
529 M.makeDereference(
530 M.makeLvalueToRvalue(
531 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
532 PredicateTy),
Devin Coughlin046833e2017-11-06 22:12:19 +0000533 M.makeIntegralCast(DoneValue, PredicateTy),
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000534 PredicateTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000535
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000536 // (3) Create the compound statement.
Craig Topper5fc8fc22014-08-27 06:28:36 +0000537 Stmt *Stmts[] = { B, CE };
538 CompoundStmt *CS = M.makeCompound(Stmts);
Fangrui Song6907ce22018-07-30 19:24:48 +0000539
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000540 // (4) Create the 'if' condition.
Ted Kremeneke7ad5352012-09-21 18:33:56 +0000541 ImplicitCastExpr *LValToRval =
542 M.makeLvalueToRvalue(
543 M.makeDereference(
544 M.makeLvalueToRvalue(
545 M.makeDeclRefExpr(Predicate),
546 PredicateQPtrTy),
547 PredicateTy),
548 PredicateTy);
Devin Coughlin046833e2017-11-06 22:12:19 +0000549
550 Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000551 // (5) Create the 'if' statement.
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000552 auto *If = IfStmt::Create(C, SourceLocation(),
553 /* IsConstexpr=*/false,
554 /* init=*/nullptr,
555 /* var=*/nullptr,
556 /* cond=*/GuardCondition,
557 /* then=*/CS);
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000558 return If;
559}
560
Ted Kremenek14f779c2012-09-21 00:09:11 +0000561/// Create a fake body for dispatch_sync.
562static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
563 // Check if we have at least two parameters.
564 if (D->param_size() != 2)
Craig Topper25542942014-05-20 04:30:07 +0000565 return nullptr;
566
Ted Kremenek14f779c2012-09-21 00:09:11 +0000567 // Check if the second parameter is a block.
568 const ParmVarDecl *PV = D->getParamDecl(1);
569 QualType Ty = PV->getType();
Ted Kremenekd81a4a12012-09-21 00:52:24 +0000570 if (!isDispatchBlock(Ty))
Craig Topper25542942014-05-20 04:30:07 +0000571 return nullptr;
572
Ted Kremenek14f779c2012-09-21 00:09:11 +0000573 // Everything checks out. Create a fake body that just calls the block.
574 // This is basically just an AST dump of:
575 //
576 // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
577 // block();
578 // }
Fangrui Song6907ce22018-07-30 19:24:48 +0000579 //
Ted Kremenek72418132012-09-21 17:54:35 +0000580 ASTMaker M(C);
581 DeclRefExpr *DR = M.makeDeclRefExpr(PV);
Ted Kremenekdff35532012-09-21 18:33:52 +0000582 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000583 CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
584 SourceLocation());
Ted Kremenek14f779c2012-09-21 00:09:11 +0000585 return CE;
586}
587
Ted Kremenek089ffd02012-10-11 20:58:18 +0000588static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
589{
590 // There are exactly 3 arguments.
591 if (D->param_size() != 3)
Craig Topper25542942014-05-20 04:30:07 +0000592 return nullptr;
593
Anna Zaks064185a2013-02-05 19:52:26 +0000594 // Signature:
595 // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
596 // void *__newValue,
597 // void * volatile *__theValue)
598 // Generate body:
Ted Kremenek089ffd02012-10-11 20:58:18 +0000599 // if (oldValue == *theValue) {
600 // *theValue = newValue;
601 // return YES;
602 // }
603 // else return NO;
Alp Toker314cc812014-01-25 16:55:45 +0000604
605 QualType ResultTy = D->getReturnType();
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000606 bool isBoolean = ResultTy->isBooleanType();
607 if (!isBoolean && !ResultTy->isIntegralType(C))
Craig Topper25542942014-05-20 04:30:07 +0000608 return nullptr;
609
Ted Kremenek089ffd02012-10-11 20:58:18 +0000610 const ParmVarDecl *OldValue = D->getParamDecl(0);
611 QualType OldValueTy = OldValue->getType();
612
613 const ParmVarDecl *NewValue = D->getParamDecl(1);
614 QualType NewValueTy = NewValue->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000615
Ted Kremenek089ffd02012-10-11 20:58:18 +0000616 assert(OldValueTy == NewValueTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000617
Ted Kremenek089ffd02012-10-11 20:58:18 +0000618 const ParmVarDecl *TheValue = D->getParamDecl(2);
619 QualType TheValueTy = TheValue->getType();
620 const PointerType *PT = TheValueTy->getAs<PointerType>();
621 if (!PT)
Craig Topper25542942014-05-20 04:30:07 +0000622 return nullptr;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000623 QualType PointeeTy = PT->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000624
Ted Kremenek089ffd02012-10-11 20:58:18 +0000625 ASTMaker M(C);
626 // Construct the comparison.
627 Expr *Comparison =
628 M.makeComparison(
629 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
630 M.makeLvalueToRvalue(
631 M.makeDereference(
632 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
633 PointeeTy),
634 PointeeTy),
635 BO_EQ);
636
637 // Construct the body of the IfStmt.
638 Stmt *Stmts[2];
639 Stmts[0] =
640 M.makeAssignment(
641 M.makeDereference(
642 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
643 PointeeTy),
644 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
645 NewValueTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000646
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000647 Expr *BoolVal = M.makeObjCBool(true);
648 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
649 : M.makeIntegralCast(BoolVal, ResultTy);
650 Stmts[1] = M.makeReturn(RetVal);
Craig Topper5fc8fc22014-08-27 06:28:36 +0000651 CompoundStmt *Body = M.makeCompound(Stmts);
Fangrui Song6907ce22018-07-30 19:24:48 +0000652
Ted Kremenek089ffd02012-10-11 20:58:18 +0000653 // Construct the else clause.
Ted Kremenek6fdefb52012-10-12 00:18:19 +0000654 BoolVal = M.makeObjCBool(false);
655 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
656 : M.makeIntegralCast(BoolVal, ResultTy);
657 Stmt *Else = M.makeReturn(RetVal);
Fangrui Song6907ce22018-07-30 19:24:48 +0000658
Ted Kremenek089ffd02012-10-11 20:58:18 +0000659 /// Construct the If.
Bruno Riccib1cc94b2018-10-27 21:12:20 +0000660 auto *If = IfStmt::Create(C, SourceLocation(),
661 /* IsConstexpr=*/false,
662 /* init=*/nullptr,
663 /* var=*/nullptr, Comparison, Body,
664 SourceLocation(), Else);
Craig Topper25542942014-05-20 04:30:07 +0000665
Fangrui Song6907ce22018-07-30 19:24:48 +0000666 return If;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000667}
668
Ted Kremenek14f779c2012-09-21 00:09:11 +0000669Stmt *BodyFarm::getBody(const FunctionDecl *D) {
670 D = D->getCanonicalDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000671
David Blaikie05785d12013-02-20 22:23:23 +0000672 Optional<Stmt *> &Val = Bodies[D];
Ted Kremenek14f779c2012-09-21 00:09:11 +0000673 if (Val.hasValue())
674 return Val.getValue();
Craig Topper25542942014-05-20 04:30:07 +0000675
676 Val = nullptr;
677
678 if (D->getIdentifier() == nullptr)
679 return nullptr;
Ted Kremenek14f779c2012-09-21 00:09:11 +0000680
681 StringRef Name = D->getName();
682 if (Name.empty())
Craig Topper25542942014-05-20 04:30:07 +0000683 return nullptr;
Ted Kremenek089ffd02012-10-11 20:58:18 +0000684
685 FunctionFarmer FF;
686
687 if (Name.startswith("OSAtomicCompareAndSwap") ||
688 Name.startswith("objc_atomicCompareAndSwap")) {
689 FF = create_OSAtomicCompareAndSwap;
George Karpenkov657a5892017-09-30 00:03:22 +0000690 } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
691 FF = create_call_once;
692 } else {
Ted Kremenek089ffd02012-10-11 20:58:18 +0000693 FF = llvm::StringSwitch<FunctionFarmer>(Name)
694 .Case("dispatch_sync", create_dispatch_sync)
695 .Case("dispatch_once", create_dispatch_once)
Craig Topper25542942014-05-20 04:30:07 +0000696 .Default(nullptr);
Ted Kremenek14f779c2012-09-21 00:09:11 +0000697 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000698
Ted Kremenek089ffd02012-10-11 20:58:18 +0000699 if (FF) { Val = FF(C, D); }
Ted Kremenekeeccb302014-08-27 15:14:15 +0000700 else if (Injector) { Val = Injector->getBody(D); }
Ted Kremenek14f779c2012-09-21 00:09:11 +0000701 return Val.getValue();
702}
703
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000704static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
705 const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
706
707 if (IVar)
708 return IVar;
709
710 // When a readonly property is shadowed in a class extensions with a
711 // a readwrite property, the instance variable belongs to the shadowing
712 // property rather than the shadowed property. If there is no instance
713 // variable on a readonly property, check to see whether the property is
714 // shadowed and if so try to get the instance variable from shadowing
715 // property.
716 if (!Prop->isReadOnly())
717 return nullptr;
718
719 auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
720 const ObjCInterfaceDecl *PrimaryInterface = nullptr;
721 if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
722 PrimaryInterface = InterfaceDecl;
723 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
724 PrimaryInterface = CategoryDecl->getClassInterface();
725 } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
726 PrimaryInterface = ImplDecl->getClassInterface();
727 } else {
728 return nullptr;
729 }
730
731 // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
732 // is guaranteed to find the shadowing property, if it exists, rather than
733 // the shadowed property.
734 auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
Manman Ren5b786402016-01-28 18:49:28 +0000735 Prop->getIdentifier(), Prop->getQueryKind());
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000736 if (ShadowingProp && ShadowingProp != Prop) {
737 IVar = ShadowingProp->getPropertyIvarDecl();
738 }
739
740 return IVar;
741}
742
Jordan Rose1a866cd2014-01-10 20:06:06 +0000743static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
744 const ObjCPropertyDecl *Prop) {
Jordan Roseddf19662014-01-23 03:59:10 +0000745 // First, find the backing ivar.
Devin Coughlinb7e810b2016-01-26 23:58:48 +0000746 const ObjCIvarDecl *IVar = findBackingIvar(Prop);
Jordan Rose1a866cd2014-01-10 20:06:06 +0000747 if (!IVar)
Craig Topper25542942014-05-20 04:30:07 +0000748 return nullptr;
Jordan Roseddf19662014-01-23 03:59:10 +0000749
750 // Ignore weak variables, which have special behavior.
Jordan Rose1a866cd2014-01-10 20:06:06 +0000751 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
Craig Topper25542942014-05-20 04:30:07 +0000752 return nullptr;
Jordan Rosea3f27812014-01-14 17:29:06 +0000753
Jordan Roseddf19662014-01-23 03:59:10 +0000754 // Look to see if Sema has synthesized a body for us. This happens in
755 // Objective-C++ because the return value may be a C++ class type with a
756 // non-trivial copy constructor. We can only do this if we can find the
757 // @synthesize for this property, though (or if we know it's been auto-
758 // synthesized).
Jordan Rosea3f27812014-01-14 17:29:06 +0000759 const ObjCImplementationDecl *ImplDecl =
760 IVar->getContainingInterface()->getImplementation();
761 if (ImplDecl) {
Aaron Ballmand85eff42014-03-14 15:02:45 +0000762 for (const auto *I : ImplDecl->property_impls()) {
Jordan Rosea3f27812014-01-14 17:29:06 +0000763 if (I->getPropertyDecl() != Prop)
764 continue;
765
766 if (I->getGetterCXXConstructor()) {
767 ASTMaker M(Ctx);
768 return M.makeReturn(I->getGetterCXXConstructor());
769 }
770 }
771 }
772
Jordan Roseddf19662014-01-23 03:59:10 +0000773 // Sanity check that the property is the same type as the ivar, or a
774 // reference to it, and that it is either an object pointer or trivially
775 // copyable.
776 if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
777 Prop->getType().getNonReferenceType()))
Craig Topper25542942014-05-20 04:30:07 +0000778 return nullptr;
Jordan Roseddf19662014-01-23 03:59:10 +0000779 if (!IVar->getType()->isObjCLifetimeType() &&
780 !IVar->getType().isTriviallyCopyableType(Ctx))
Craig Topper25542942014-05-20 04:30:07 +0000781 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000782
Jordan Roseddf19662014-01-23 03:59:10 +0000783 // Generate our body:
784 // return self->_ivar;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000785 ASTMaker M(Ctx);
786
787 const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
Devin Coughlinaac894f2017-01-11 01:02:34 +0000788 if (!selfVar)
789 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000790
791 Expr *loadedIVar =
792 M.makeObjCIvarRef(
793 M.makeLvalueToRvalue(
794 M.makeDeclRefExpr(selfVar),
795 selfVar->getType()),
796 IVar);
797
798 if (!Prop->getType()->isReferenceType())
799 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
800
801 return M.makeReturn(loadedIVar);
802}
803
Jordan Roseddf19662014-01-23 03:59:10 +0000804Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
805 // We currently only know how to synthesize property accessors.
Jordan Rose1a866cd2014-01-10 20:06:06 +0000806 if (!D->isPropertyAccessor())
Craig Topper25542942014-05-20 04:30:07 +0000807 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000808
809 D = D->getCanonicalDecl();
810
811 Optional<Stmt *> &Val = Bodies[D];
812 if (Val.hasValue())
813 return Val.getValue();
Craig Topper25542942014-05-20 04:30:07 +0000814 Val = nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000815
Jordan Roseddf19662014-01-23 03:59:10 +0000816 const ObjCPropertyDecl *Prop = D->findPropertyDecl();
Jordan Rose1a866cd2014-01-10 20:06:06 +0000817 if (!Prop)
Craig Topper25542942014-05-20 04:30:07 +0000818 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000819
Jordan Roseddf19662014-01-23 03:59:10 +0000820 // For now, we only synthesize getters.
Devin Coughlinef3697e2016-02-18 19:37:39 +0000821 // Synthesizing setters would cause false negatives in the
822 // RetainCountChecker because the method body would bind the parameter
823 // to an instance variable, causing it to escape. This would prevent
824 // warning in the following common scenario:
825 //
826 // id foo = [[NSObject alloc] init];
827 // self.foo = foo; // We should warn that foo leaks here.
828 //
Jordan Rose1a866cd2014-01-10 20:06:06 +0000829 if (D->param_size() != 0)
Craig Topper25542942014-05-20 04:30:07 +0000830 return nullptr;
Jordan Rose1a866cd2014-01-10 20:06:06 +0000831
832 Val = createObjCPropertyGetter(C, Prop);
833
834 return Val.getValue();
835}