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