Coverage Report

Created: 2022-01-25 06:29

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