Coverage Report

Created: 2023-11-11 10:31

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