Coverage Report

Created: 2024-01-17 10:31

/src/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
0
static bool isDispatchBlock(QualType Ty) {
38
  // Is it a block pointer?
39
0
  const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
40
0
  if (!BPT)
41
0
    return false;
42
43
  // Check if the block pointer type takes no arguments and
44
  // returns void.
45
0
  const FunctionProtoType *FT =
46
0
  BPT->getPointeeType()->getAs<FunctionProtoType>();
47
0
  return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
48
0
}
49
50
namespace {
51
class ASTMaker {
52
public:
53
0
  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
0
                                         QualType Ty) {
122
0
  return BinaryOperator::Create(
123
0
      C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), BO_Assign, Ty,
124
0
      VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride());
125
0
}
126
127
BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
128
0
                                         BinaryOperator::Opcode Op) {
129
0
  assert(BinaryOperator::isLogicalOp(Op) ||
130
0
         BinaryOperator::isComparisonOp(Op));
131
0
  return BinaryOperator::Create(
132
0
      C, const_cast<Expr *>(LHS), const_cast<Expr *>(RHS), Op,
133
0
      C.getLogicalOperationType(), VK_PRValue, OK_Ordinary, SourceLocation(),
134
0
      FPOptionsOverride());
135
0
}
136
137
0
CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
138
0
  return CompoundStmt::Create(C, Stmts, FPOptionsOverride(), SourceLocation(),
139
0
                              SourceLocation());
140
0
}
141
142
DeclRefExpr *ASTMaker::makeDeclRefExpr(
143
    const VarDecl *D,
144
0
    bool RefersToEnclosingVariableOrCapture) {
145
0
  QualType Type = D->getType().getNonReferenceType();
146
147
0
  DeclRefExpr *DR = DeclRefExpr::Create(
148
0
      C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
149
0
      RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
150
0
  return DR;
151
0
}
152
153
0
UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
154
0
  return UnaryOperator::Create(C, const_cast<Expr *>(Arg), UO_Deref, Ty,
155
0
                               VK_LValue, OK_Ordinary, SourceLocation(),
156
0
                               /*CanOverflow*/ false, FPOptionsOverride());
157
0
}
158
159
0
ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
160
0
  return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
161
0
}
162
163
ImplicitCastExpr *
164
ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
165
0
                             bool RefersToEnclosingVariableOrCapture) {
166
0
  QualType Type = Arg->getType().getNonReferenceType();
167
0
  return makeLvalueToRvalue(makeDeclRefExpr(Arg,
168
0
                                            RefersToEnclosingVariableOrCapture),
169
0
                            Type);
170
0
}
171
172
ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
173
0
                                             CastKind CK) {
174
0
  return ImplicitCastExpr::Create(C, Ty,
175
0
                                  /* CastKind=*/CK,
176
0
                                  /* Expr=*/const_cast<Expr *>(Arg),
177
0
                                  /* CXXCastPath=*/nullptr,
178
0
                                  /* ExprValueKind=*/VK_PRValue,
179
0
                                  /* FPFeatures */ FPOptionsOverride());
180
0
}
181
182
0
CastExpr *ASTMaker::makeReferenceCast(const Expr *Arg, QualType Ty) {
183
0
  assert(Ty->isReferenceType());
184
0
  return CXXStaticCastExpr::Create(
185
0
      C, Ty.getNonReferenceType(),
186
0
      Ty->isLValueReferenceType() ? VK_LValue : VK_XValue, CK_NoOp,
187
0
      const_cast<Expr *>(Arg), /*CXXCastPath=*/nullptr,
188
0
      /*Written=*/C.getTrivialTypeSourceInfo(Ty), FPOptionsOverride(),
189
0
      SourceLocation(), SourceLocation(), SourceRange());
190
0
}
191
192
0
Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
193
0
  if (Arg->getType() == Ty)
194
0
    return const_cast<Expr*>(Arg);
195
0
  return makeImplicitCast(Arg, Ty, CK_IntegralCast);
196
0
}
197
198
0
ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
199
0
  return makeImplicitCast(Arg, C.BoolTy, CK_IntegralToBoolean);
200
0
}
201
202
0
ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
203
0
  QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
204
0
  return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
205
0
}
206
207
ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
208
0
                                           const ObjCIvarDecl *IVar) {
209
0
  return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
210
0
                                 IVar->getType(), SourceLocation(),
211
0
                                 SourceLocation(), const_cast<Expr*>(Base),
212
0
                                 /*arrow=*/true, /*free=*/false);
213
0
}
214
215
0
ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
216
0
  return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
217
0
                            /* NRVOCandidate=*/nullptr);
218
0
}
219
220
0
IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
221
0
  llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
222
0
  return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
223
0
}
224
225
MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
226
                                           bool IsArrow,
227
0
                                           ExprValueKind ValueKind) {
228
229
0
  DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
230
0
  return MemberExpr::Create(
231
0
      C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
232
0
      SourceLocation(), MemberDecl, FoundDecl,
233
0
      DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
234
0
      /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
235
0
      OK_Ordinary, NOUR_None);
236
0
}
237
238
0
ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
239
240
0
  CXXBasePaths Paths(
241
0
      /* FindAmbiguities=*/false,
242
0
      /* RecordPaths=*/false,
243
0
      /* DetectVirtual=*/ false);
244
0
  const IdentifierInfo &II = C.Idents.get(Name);
245
0
  DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
246
247
0
  DeclContextLookupResult Decls = RD->lookup(DeclName);
248
0
  for (NamedDecl *FoundDecl : Decls)
249
0
    if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
250
0
      return cast<ValueDecl>(FoundDecl);
251
252
0
  return nullptr;
253
0
}
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
0
                                               ArrayRef<Expr *> CallArgs) {
264
265
0
  QualType Ty = Callback->getType();
266
0
  DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
267
0
  Expr *SubExpr;
268
0
  if (Ty->isRValueReferenceType()) {
269
0
    SubExpr = M.makeImplicitCast(
270
0
        Call, Ty.getNonReferenceType(), CK_LValueToRValue);
271
0
  } else if (Ty->isLValueReferenceType() &&
272
0
             Call->getType()->isFunctionType()) {
273
0
    Ty = C.getPointerType(Ty.getNonReferenceType());
274
0
    SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
275
0
  } else if (Ty->isLValueReferenceType()
276
0
             && Call->getType()->isPointerType()
277
0
             && Call->getType()->getPointeeType()->isFunctionType()){
278
0
    SubExpr = Call;
279
0
  } else {
280
0
    llvm_unreachable("Unexpected state");
281
0
  }
282
283
0
  return CallExpr::Create(C, SubExpr, CallArgs, C.VoidTy, VK_PRValue,
284
0
                          SourceLocation(), FPOptionsOverride());
285
0
}
286
287
static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
288
                                              const ParmVarDecl *Callback,
289
                                              CXXRecordDecl *CallbackDecl,
290
0
                                              ArrayRef<Expr *> CallArgs) {
291
0
  assert(CallbackDecl != nullptr);
292
0
  assert(CallbackDecl->isLambda());
293
0
  FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
294
0
  assert(callOperatorDecl != nullptr);
295
296
0
  DeclRefExpr *callOperatorDeclRef =
297
0
      DeclRefExpr::Create(/* Ctx =*/ C,
298
0
                          /* QualifierLoc =*/ NestedNameSpecifierLoc(),
299
0
                          /* TemplateKWLoc =*/ SourceLocation(),
300
0
                          const_cast<FunctionDecl *>(callOperatorDecl),
301
0
                          /* RefersToEnclosingVariableOrCapture=*/ false,
302
0
                          /* NameLoc =*/ SourceLocation(),
303
0
                          /* T =*/ callOperatorDecl->getType(),
304
0
                          /* VK =*/ VK_LValue);
305
306
0
  return CXXOperatorCallExpr::Create(
307
0
      /*AstContext=*/C, OO_Call, callOperatorDeclRef,
308
0
      /*Args=*/CallArgs,
309
0
      /*QualType=*/C.VoidTy,
310
0
      /*ExprValueType=*/VK_PRValue,
311
0
      /*SourceLocation=*/SourceLocation(),
312
0
      /*FPFeatures=*/FPOptionsOverride());
313
0
}
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
0
static Stmt *create_std_move_forward(ASTContext &C, const FunctionDecl *D) {
321
0
  LLVM_DEBUG(llvm::dbgs() << "Generating body for std::move / std::forward\n");
322
323
0
  ASTMaker M(C);
324
325
0
  QualType ReturnType = D->getType()->castAs<FunctionType>()->getReturnType();
326
0
  Expr *Param = M.makeDeclRefExpr(D->getParamDecl(0));
327
0
  Expr *Cast = M.makeReferenceCast(Param, ReturnType);
328
0
  return M.makeReturn(Cast);
329
0
}
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
0
static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
347
0
  LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
348
349
  // We need at least two parameters.
350
0
  if (D->param_size() < 2)
351
0
    return nullptr;
352
353
0
  ASTMaker M(C);
354
355
0
  const ParmVarDecl *Flag = D->getParamDecl(0);
356
0
  const ParmVarDecl *Callback = D->getParamDecl(1);
357
358
0
  if (!Callback->getType()->isReferenceType()) {
359
0
    llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
360
0
    return nullptr;
361
0
  }
362
0
  if (!Flag->getType()->isReferenceType()) {
363
0
    llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
364
0
    return nullptr;
365
0
  }
366
367
0
  QualType CallbackType = Callback->getType().getNonReferenceType();
368
369
  // Nullable pointer, non-null iff function is a CXXRecordDecl.
370
0
  CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
371
0
  QualType FlagType = Flag->getType().getNonReferenceType();
372
0
  auto *FlagRecordDecl = FlagType->getAsRecordDecl();
373
374
0
  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
0
  ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
384
385
  // Otherwise, try libstdc++ implementation, with a field
386
  // `_M_once`
387
0
  if (!FlagFieldDecl) {
388
0
    FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
389
0
  }
390
391
0
  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
0
  bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
399
0
  if (CallbackRecordDecl && !isLambdaCall) {
400
0
    LLVM_DEBUG(llvm::dbgs()
401
0
               << "Not supported: synthesizing body for functors when "
402
0
               << "body farming std::call_once, ignoring the call.");
403
0
    return nullptr;
404
0
  }
405
406
0
  SmallVector<Expr *, 5> CallArgs;
407
0
  const FunctionProtoType *CallbackFunctionType;
408
0
  if (isLambdaCall) {
409
410
    // Lambda requires callback itself inserted as a first parameter.
411
0
    CallArgs.push_back(
412
0
        M.makeDeclRefExpr(Callback,
413
0
                          /* RefersToEnclosingVariableOrCapture=*/ true));
414
0
    CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
415
0
                               ->getType()
416
0
                               ->getAs<FunctionProtoType>();
417
0
  } else if (!CallbackType->getPointeeType().isNull()) {
418
0
    CallbackFunctionType =
419
0
        CallbackType->getPointeeType()->getAs<FunctionProtoType>();
420
0
  } else {
421
0
    CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
422
0
  }
423
424
0
  if (!CallbackFunctionType)
425
0
    return nullptr;
426
427
  // First two arguments are used for the flag and for the callback.
428
0
  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
0
  for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
439
0
    const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
440
0
    assert(PDecl);
441
0
    if (CallbackFunctionType->getParamType(ParamIdx - 2)
442
0
                .getNonReferenceType()
443
0
                .getCanonicalType() !=
444
0
            PDecl->getType().getNonReferenceType().getCanonicalType()) {
445
0
      LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
446
0
                              << "params passed to std::call_once, "
447
0
                              << "ignoring the call\n");
448
0
      return nullptr;
449
0
    }
450
0
    Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
451
0
    if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
452
0
      QualType PTy = PDecl->getType().getNonReferenceType();
453
0
      ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
454
0
    }
455
0
    CallArgs.push_back(ParamExpr);
456
0
  }
457
458
0
  CallExpr *CallbackCall;
459
0
  if (isLambdaCall) {
460
461
0
    CallbackCall = create_call_once_lambda_call(C, M, Callback,
462
0
                                                CallbackRecordDecl, CallArgs);
463
0
  } else {
464
465
    // Function pointer case.
466
0
    CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
467
0
  }
468
469
0
  DeclRefExpr *FlagDecl =
470
0
      M.makeDeclRefExpr(Flag,
471
0
                        /* RefersToEnclosingVariableOrCapture=*/true);
472
473
474
0
  MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
475
0
  assert(Deref->isLValue());
476
0
  QualType DerefType = Deref->getType();
477
478
  // Negation predicate.
479
0
  UnaryOperator *FlagCheck = UnaryOperator::Create(
480
0
      C,
481
      /* input=*/
482
0
      M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
483
0
                         CK_IntegralToBoolean),
484
0
      /* opc=*/UO_LNot,
485
0
      /* QualType=*/C.IntTy,
486
0
      /* ExprValueKind=*/VK_PRValue,
487
0
      /* ExprObjectKind=*/OK_Ordinary, SourceLocation(),
488
0
      /* CanOverflow*/ false, FPOptionsOverride());
489
490
  // Create assignment.
491
0
  BinaryOperator *FlagAssignment = M.makeAssignment(
492
0
      Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
493
0
      DerefType);
494
495
0
  auto *Out =
496
0
      IfStmt::Create(C, SourceLocation(), IfStatementKind::Ordinary,
497
0
                     /* Init=*/nullptr,
498
0
                     /* Var=*/nullptr,
499
0
                     /* Cond=*/FlagCheck,
500
0
                     /* LPL=*/SourceLocation(),
501
0
                     /* RPL=*/SourceLocation(),
502
0
                     /* Then=*/M.makeCompound({CallbackCall, FlagAssignment}));
503
504
0
  return Out;
505
0
}
506
507
/// Create a fake body for dispatch_once.
508
0
static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
509
  // Check if we have at least two parameters.
510
0
  if (D->param_size() != 2)
511
0
    return nullptr;
512
513
  // Check if the first parameter is a pointer to integer type.
514
0
  const ParmVarDecl *Predicate = D->getParamDecl(0);
515
0
  QualType PredicateQPtrTy = Predicate->getType();
516
0
  const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
517
0
  if (!PredicatePtrTy)
518
0
    return nullptr;
519
0
  QualType PredicateTy = PredicatePtrTy->getPointeeType();
520
0
  if (!PredicateTy->isIntegerType())
521
0
    return nullptr;
522
523
  // Check if the second parameter is the proper block type.
524
0
  const ParmVarDecl *Block = D->getParamDecl(1);
525
0
  QualType Ty = Block->getType();
526
0
  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
0
  ASTMaker M(C);
540
541
  // (1) Create the call.
542
0
  CallExpr *CE = CallExpr::Create(
543
0
      /*ASTContext=*/C,
544
0
      /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
545
0
      /*Args=*/std::nullopt,
546
0
      /*QualType=*/C.VoidTy,
547
0
      /*ExprValueType=*/VK_PRValue,
548
0
      /*SourceLocation=*/SourceLocation(), FPOptionsOverride());
549
550
  // (2) Create the assignment to the predicate.
551
0
  Expr *DoneValue =
552
0
      UnaryOperator::Create(C, M.makeIntegerLiteral(0, C.LongTy), UO_Not,
553
0
                            C.LongTy, VK_PRValue, OK_Ordinary, SourceLocation(),
554
0
                            /*CanOverflow*/ false, FPOptionsOverride());
555
556
0
  BinaryOperator *B =
557
0
    M.makeAssignment(
558
0
       M.makeDereference(
559
0
          M.makeLvalueToRvalue(
560
0
            M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
561
0
            PredicateTy),
562
0
       M.makeIntegralCast(DoneValue, PredicateTy),
563
0
       PredicateTy);
564
565
  // (3) Create the compound statement.
566
0
  Stmt *Stmts[] = { B, CE };
567
0
  CompoundStmt *CS = M.makeCompound(Stmts);
568
569
  // (4) Create the 'if' condition.
570
0
  ImplicitCastExpr *LValToRval =
571
0
    M.makeLvalueToRvalue(
572
0
      M.makeDereference(
573
0
        M.makeLvalueToRvalue(
574
0
          M.makeDeclRefExpr(Predicate),
575
0
          PredicateQPtrTy),
576
0
        PredicateTy),
577
0
    PredicateTy);
578
579
0
  Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
580
  // (5) Create the 'if' statement.
581
0
  auto *If = IfStmt::Create(C, SourceLocation(), IfStatementKind::Ordinary,
582
0
                            /* Init=*/nullptr,
583
0
                            /* Var=*/nullptr,
584
0
                            /* Cond=*/GuardCondition,
585
0
                            /* LPL=*/SourceLocation(),
586
0
                            /* RPL=*/SourceLocation(),
587
0
                            /* Then=*/CS);
588
0
  return If;
589
0
}
590
591
/// Create a fake body for dispatch_sync.
592
0
static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
593
  // Check if we have at least two parameters.
594
0
  if (D->param_size() != 2)
595
0
    return nullptr;
596
597
  // Check if the second parameter is a block.
598
0
  const ParmVarDecl *PV = D->getParamDecl(1);
599
0
  QualType Ty = PV->getType();
600
0
  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
0
  ASTMaker M(C);
611
0
  DeclRefExpr *DR = M.makeDeclRefExpr(PV);
612
0
  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
613
0
  CallExpr *CE = CallExpr::Create(C, ICE, std::nullopt, C.VoidTy, VK_PRValue,
614
0
                                  SourceLocation(), FPOptionsOverride());
615
0
  return CE;
616
0
}
617
618
static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
619
0
{
620
  // There are exactly 3 arguments.
621
0
  if (D->param_size() != 3)
622
0
    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
0
  QualType ResultTy = D->getReturnType();
636
0
  bool isBoolean = ResultTy->isBooleanType();
637
0
  if (!isBoolean && !ResultTy->isIntegralType(C))
638
0
    return nullptr;
639
640
0
  const ParmVarDecl *OldValue = D->getParamDecl(0);
641
0
  QualType OldValueTy = OldValue->getType();
642
643
0
  const ParmVarDecl *NewValue = D->getParamDecl(1);
644
0
  QualType NewValueTy = NewValue->getType();
645
646
0
  assert(OldValueTy == NewValueTy);
647
648
0
  const ParmVarDecl *TheValue = D->getParamDecl(2);
649
0
  QualType TheValueTy = TheValue->getType();
650
0
  const PointerType *PT = TheValueTy->getAs<PointerType>();
651
0
  if (!PT)
652
0
    return nullptr;
653
0
  QualType PointeeTy = PT->getPointeeType();
654
655
0
  ASTMaker M(C);
656
  // Construct the comparison.
657
0
  Expr *Comparison =
658
0
    M.makeComparison(
659
0
      M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
660
0
      M.makeLvalueToRvalue(
661
0
        M.makeDereference(
662
0
          M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
663
0
          PointeeTy),
664
0
        PointeeTy),
665
0
      BO_EQ);
666
667
  // Construct the body of the IfStmt.
668
0
  Stmt *Stmts[2];
669
0
  Stmts[0] =
670
0
    M.makeAssignment(
671
0
      M.makeDereference(
672
0
        M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
673
0
        PointeeTy),
674
0
      M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
675
0
      NewValueTy);
676
677
0
  Expr *BoolVal = M.makeObjCBool(true);
678
0
  Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
679
0
                           : M.makeIntegralCast(BoolVal, ResultTy);
680
0
  Stmts[1] = M.makeReturn(RetVal);
681
0
  CompoundStmt *Body = M.makeCompound(Stmts);
682
683
  // Construct the else clause.
684
0
  BoolVal = M.makeObjCBool(false);
685
0
  RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
686
0
                     : M.makeIntegralCast(BoolVal, ResultTy);
687
0
  Stmt *Else = M.makeReturn(RetVal);
688
689
  /// Construct the If.
690
0
  auto *If =
691
0
      IfStmt::Create(C, SourceLocation(), IfStatementKind::Ordinary,
692
0
                     /* Init=*/nullptr,
693
0
                     /* Var=*/nullptr, Comparison,
694
0
                     /* LPL=*/SourceLocation(),
695
0
                     /* RPL=*/SourceLocation(), Body, SourceLocation(), Else);
696
697
0
  return If;
698
0
}
699
700
0
Stmt *BodyFarm::getBody(const FunctionDecl *D) {
701
0
  std::optional<Stmt *> &Val = Bodies[D];
702
0
  if (Val)
703
0
    return *Val;
704
705
0
  Val = nullptr;
706
707
0
  if (D->getIdentifier() == nullptr)
708
0
    return nullptr;
709
710
0
  StringRef Name = D->getName();
711
0
  if (Name.empty())
712
0
    return nullptr;
713
714
0
  FunctionFarmer FF;
715
716
0
  if (unsigned BuiltinID = D->getBuiltinID()) {
717
0
    switch (BuiltinID) {
718
0
    case Builtin::BIas_const:
719
0
    case Builtin::BIforward:
720
0
    case Builtin::BIforward_like:
721
0
    case Builtin::BImove:
722
0
    case Builtin::BImove_if_noexcept:
723
0
      FF = create_std_move_forward;
724
0
      break;
725
0
    default:
726
0
      FF = nullptr;
727
0
      break;
728
0
    }
729
0
  } else if (Name.starts_with("OSAtomicCompareAndSwap") ||
730
0
             Name.starts_with("objc_atomicCompareAndSwap")) {
731
0
    FF = create_OSAtomicCompareAndSwap;
732
0
  } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
733
0
    FF = create_call_once;
734
0
  } else {
735
0
    FF = llvm::StringSwitch<FunctionFarmer>(Name)
736
0
          .Case("dispatch_sync", create_dispatch_sync)
737
0
          .Case("dispatch_once", create_dispatch_once)
738
0
          .Default(nullptr);
739
0
  }
740
741
0
  if (FF) { Val = FF(C, D); }
742
0
  else if (Injector) { Val = Injector->getBody(D); }
743
0
  return *Val;
744
0
}
745
746
0
static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
747
0
  const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
748
749
0
  if (IVar)
750
0
    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
0
  if (!Prop->isReadOnly())
759
0
    return nullptr;
760
761
0
  auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
762
0
  const ObjCInterfaceDecl *PrimaryInterface = nullptr;
763
0
  if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
764
0
    PrimaryInterface = InterfaceDecl;
765
0
  } else if (auto *CategoryDecl = 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
0
  auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
777
0
      Prop->getIdentifier(), Prop->getQueryKind());
778
0
  if (ShadowingProp && ShadowingProp != Prop) {
779
0
    IVar = ShadowingProp->getPropertyIvarDecl();
780
0
  }
781
782
0
  return IVar;
783
0
}
784
785
static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
786
0
                                      const ObjCMethodDecl *MD) {
787
  // First, find the backing ivar.
788
0
  const ObjCIvarDecl *IVar = nullptr;
789
0
  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
0
  if (MD->isSynthesizedAccessorStub()) {
795
0
    const ObjCInterfaceDecl *IntD = MD->getClassInterface();
796
0
    const ObjCImplementationDecl *ImpD = IntD->getImplementation();
797
0
    for (const auto *PI : ImpD->property_impls()) {
798
0
      if (const ObjCPropertyDecl *Candidate = PI->getPropertyDecl()) {
799
0
        if (Candidate->getGetterName() == MD->getSelector()) {
800
0
          Prop = Candidate;
801
0
          IVar = Prop->getPropertyIvarDecl();
802
0
        }
803
0
      }
804
0
    }
805
0
  }
806
807
0
  if (!IVar) {
808
0
    Prop = MD->findPropertyDecl();
809
0
    IVar = Prop ? findBackingIvar(Prop) : nullptr;
810
0
  }
811
812
0
  if (!IVar || !Prop)
813
0
    return nullptr;
814
815
  // Ignore weak variables, which have special behavior.
816
0
  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
0
  const ObjCImplementationDecl *ImplDecl =
825
0
      IVar->getContainingInterface()->getImplementation();
826
0
  if (ImplDecl) {
827
0
    for (const auto *I : ImplDecl->property_impls()) {
828
0
      if (I->getPropertyDecl() != Prop)
829
0
        continue;
830
831
0
      if (I->getGetterCXXConstructor()) {
832
0
        ASTMaker M(Ctx);
833
0
        return M.makeReturn(I->getGetterCXXConstructor());
834
0
      }
835
0
    }
836
0
  }
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
0
  if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
841
0
                                  Prop->getType().getNonReferenceType()))
842
0
    return nullptr;
843
0
  if (!IVar->getType()->isObjCLifetimeType() &&
844
0
      !IVar->getType().isTriviallyCopyableType(Ctx))
845
0
    return nullptr;
846
847
  // Generate our body:
848
  //   return self->_ivar;
849
0
  ASTMaker M(Ctx);
850
851
0
  const VarDecl *selfVar = MD->getSelfDecl();
852
0
  if (!selfVar)
853
0
    return nullptr;
854
855
0
  Expr *loadedIVar = M.makeObjCIvarRef(
856
0
      M.makeLvalueToRvalue(M.makeDeclRefExpr(selfVar), selfVar->getType()),
857
0
      IVar);
858
859
0
  if (!MD->getReturnType()->isReferenceType())
860
0
    loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
861
862
0
  return M.makeReturn(loadedIVar);
863
0
}
864
865
0
Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
866
  // We currently only know how to synthesize property accessors.
867
0
  if (!D->isPropertyAccessor())
868
0
    return nullptr;
869
870
0
  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
0
  if (!D->isImplicit())
875
0
    return nullptr;
876
877
0
  std::optional<Stmt *> &Val = Bodies[D];
878
0
  if (Val)
879
0
    return *Val;
880
0
  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
0
  if (D->param_size() != 0)
892
0
    return nullptr;
893
894
  // If the property was defined in an extension, search the extensions for
895
  // overrides.
896
0
  const ObjCInterfaceDecl *OID = D->getClassInterface();
897
0
  if (dyn_cast<ObjCInterfaceDecl>(D->getParent()) != OID)
898
0
    for (auto *Ext : OID->known_extensions()) {
899
0
      auto *OMD = Ext->getInstanceMethod(D->getSelector());
900
0
      if (OMD && !OMD->isImplicit())
901
0
        return nullptr;
902
0
    }
903
904
0
  Val = createObjCPropertyGetter(C, D);
905
906
0
  return *Val;
907
0
}