clang  8.0.0svn
BodyFarm.cpp
Go to the documentation of this file.
1 //== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- C++ -*-//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // BodyFarm is a factory for creating faux implementations for functions/methods
11 // for analysis purposes.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/Debug.h"
27 
28 #define DEBUG_TYPE "body-farm"
29 
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Helper creation functions for constructing faux ASTs.
34 //===----------------------------------------------------------------------===//
35 
36 static bool isDispatchBlock(QualType Ty) {
37  // Is it a block pointer?
38  const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
39  if (!BPT)
40  return false;
41 
42  // Check if the block pointer type takes no arguments and
43  // returns void.
44  const FunctionProtoType *FT =
46  return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
47 }
48 
49 namespace {
50 class ASTMaker {
51 public:
52  ASTMaker(ASTContext &C) : C(C) {}
53 
54  /// Create a new BinaryOperator representing a simple assignment.
55  BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
56 
57  /// Create a new BinaryOperator representing a comparison.
58  BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
60 
61  /// Create a new compound stmt using the provided statements.
62  CompoundStmt *makeCompound(ArrayRef<Stmt*>);
63 
64  /// Create a new DeclRefExpr for the referenced variable.
65  DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
66  bool RefersToEnclosingVariableOrCapture = false);
67 
68  /// Create a new UnaryOperator representing a dereference.
69  UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
70 
71  /// Create an implicit cast for an integer conversion.
72  Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
73 
74  /// Create an implicit cast to a builtin boolean type.
75  ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
76 
77  /// Create an implicit cast for lvalue-to-rvaluate conversions.
78  ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
79 
80  /// Make RValue out of variable declaration, creating a temporary
81  /// DeclRefExpr in the process.
83  makeLvalueToRvalue(const VarDecl *Decl,
84  bool RefersToEnclosingVariableOrCapture = false);
85 
86  /// Create an implicit cast of the given type.
87  ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
88  CastKind CK = CK_LValueToRValue);
89 
90  /// Create an Objective-C bool literal.
91  ObjCBoolLiteralExpr *makeObjCBool(bool Val);
92 
93  /// Create an Objective-C ivar reference.
94  ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
95 
96  /// Create a Return statement.
97  ReturnStmt *makeReturn(const Expr *RetVal);
98 
99  /// Create an integer literal expression of the given type.
100  IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
101 
102  /// Create a member expression.
103  MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
104  bool IsArrow = false,
105  ExprValueKind ValueKind = VK_LValue);
106 
107  /// Returns a *first* member field of a record declaration with a given name.
108  /// \return an nullptr if no member with such a name exists.
109  ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
110 
111 private:
112  ASTContext &C;
113 };
114 }
115 
116 BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
117  QualType Ty) {
118  return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
119  BO_Assign, Ty, VK_RValue,
121 }
122 
123 BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
125  assert(BinaryOperator::isLogicalOp(Op) ||
127  return new (C) BinaryOperator(const_cast<Expr*>(LHS),
128  const_cast<Expr*>(RHS),
129  Op,
130  C.getLogicalOperationType(),
131  VK_RValue,
133 }
134 
135 CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
137 }
138 
139 DeclRefExpr *ASTMaker::makeDeclRefExpr(
140  const VarDecl *D,
141  bool RefersToEnclosingVariableOrCapture) {
143 
145  C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
146  RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
147  return DR;
148 }
149 
150 UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
151  return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
153  /*CanOverflow*/ false);
154 }
155 
156 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
157  return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
158 }
159 
161 ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
162  bool RefersToEnclosingVariableOrCapture) {
164  return makeLvalueToRvalue(makeDeclRefExpr(Arg,
165  RefersToEnclosingVariableOrCapture),
166  Type);
167 }
168 
169 ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
170  CastKind CK) {
171  return ImplicitCastExpr::Create(C, Ty,
172  /* CastKind=*/ CK,
173  /* Expr=*/ const_cast<Expr *>(Arg),
174  /* CXXCastPath=*/ nullptr,
175  /* ExprValueKind=*/ VK_RValue);
176 }
177 
178 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
179  if (Arg->getType() == Ty)
180  return const_cast<Expr*>(Arg);
181 
182  return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
183  const_cast<Expr*>(Arg), nullptr, VK_RValue);
184 }
185 
186 ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
187  return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
188  const_cast<Expr*>(Arg), nullptr, VK_RValue);
189 }
190 
191 ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
192  QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
193  return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
194 }
195 
196 ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
197  const ObjCIvarDecl *IVar) {
198  return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
199  IVar->getType(), SourceLocation(),
200  SourceLocation(), const_cast<Expr*>(Base),
201  /*arrow=*/true, /*free=*/false);
202 }
203 
204 ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
205  return ReturnStmt::Create(C, SourceLocation(), const_cast<Expr *>(RetVal),
206  /* NRVOCandidate=*/nullptr);
207 }
208 
209 IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
210  llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
211  return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
212 }
213 
214 MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
215  bool IsArrow,
216  ExprValueKind ValueKind) {
217 
218  DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
219  return MemberExpr::Create(
220  C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
221  SourceLocation(), MemberDecl, FoundDecl,
223  /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
224  OK_Ordinary);
225 }
226 
227 ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
228 
229  CXXBasePaths Paths(
230  /* FindAmbiguities=*/false,
231  /* RecordPaths=*/false,
232  /* DetectVirtual=*/ false);
233  const IdentifierInfo &II = C.Idents.get(Name);
234  DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
235 
236  DeclContextLookupResult Decls = RD->lookup(DeclName);
237  for (NamedDecl *FoundDecl : Decls)
238  if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
239  return cast<ValueDecl>(FoundDecl);
240 
241  return nullptr;
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // Creation functions for faux ASTs.
246 //===----------------------------------------------------------------------===//
247 
248 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
249 
251  const ParmVarDecl *Callback,
252  ArrayRef<Expr *> CallArgs) {
253 
254  QualType Ty = Callback->getType();
255  DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
256  Expr *SubExpr;
257  if (Ty->isRValueReferenceType()) {
258  SubExpr = M.makeImplicitCast(
259  Call, Ty.getNonReferenceType(), CK_LValueToRValue);
260  } else if (Ty->isLValueReferenceType() &&
261  Call->getType()->isFunctionType()) {
262  Ty = C.getPointerType(Ty.getNonReferenceType());
263  SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
264  } else if (Ty->isLValueReferenceType()
265  && Call->getType()->isPointerType()
266  && Call->getType()->getPointeeType()->isFunctionType()){
267  SubExpr = Call;
268  } else {
269  llvm_unreachable("Unexpected state");
270  }
271 
272  return new (C)
273  CallExpr(C, SubExpr, CallArgs, C.VoidTy, VK_RValue, SourceLocation());
274 }
275 
277  const ParmVarDecl *Callback,
278  CXXRecordDecl *CallbackDecl,
279  ArrayRef<Expr *> CallArgs) {
280  assert(CallbackDecl != nullptr);
281  assert(CallbackDecl->isLambda());
282  FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
283  assert(callOperatorDecl != nullptr);
284 
285  DeclRefExpr *callOperatorDeclRef =
286  DeclRefExpr::Create(/* Ctx =*/ C,
287  /* QualifierLoc =*/ NestedNameSpecifierLoc(),
288  /* TemplateKWLoc =*/ SourceLocation(),
289  const_cast<FunctionDecl *>(callOperatorDecl),
290  /* RefersToEnclosingVariableOrCapture=*/ false,
291  /* NameLoc =*/ SourceLocation(),
292  /* T =*/ callOperatorDecl->getType(),
293  /* VK =*/ VK_LValue);
294 
295  return new (C)
296  CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
297  /*args=*/CallArgs,
298  /*QualType=*/C.VoidTy,
299  /*ExprValueType=*/VK_RValue,
300  /*SourceLocation=*/SourceLocation(), FPOptions());
301 }
302 
303 /// Create a fake body for std::call_once.
304 /// Emulates the following function body:
305 ///
306 /// \code
307 /// typedef struct once_flag_s {
308 /// unsigned long __state = 0;
309 /// } once_flag;
310 /// template<class Callable>
311 /// void call_once(once_flag& o, Callable func) {
312 /// if (!o.__state) {
313 /// func();
314 /// }
315 /// o.__state = 1;
316 /// }
317 /// \endcode
319  LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n");
320 
321  // We need at least two parameters.
322  if (D->param_size() < 2)
323  return nullptr;
324 
325  ASTMaker M(C);
326 
327  const ParmVarDecl *Flag = D->getParamDecl(0);
328  const ParmVarDecl *Callback = D->getParamDecl(1);
329 
330  if (!Callback->getType()->isReferenceType()) {
331  llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
332  return nullptr;
333  }
334  if (!Flag->getType()->isReferenceType()) {
335  llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
336  return nullptr;
337  }
338 
339  QualType CallbackType = Callback->getType().getNonReferenceType();
340 
341  // Nullable pointer, non-null iff function is a CXXRecordDecl.
342  CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
343  QualType FlagType = Flag->getType().getNonReferenceType();
344  auto *FlagRecordDecl = FlagType->getAsRecordDecl();
345 
346  if (!FlagRecordDecl) {
347  LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "
348  << "unknown std::call_once implementation, "
349  << "ignoring the call.\n");
350  return nullptr;
351  }
352 
353  // We initially assume libc++ implementation of call_once,
354  // where the once_flag struct has a field `__state_`.
355  ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
356 
357  // Otherwise, try libstdc++ implementation, with a field
358  // `_M_once`
359  if (!FlagFieldDecl) {
360  FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
361  }
362 
363  if (!FlagFieldDecl) {
364  LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "
365  << "std::once_flag struct: unknown std::call_once "
366  << "implementation, ignoring the call.");
367  return nullptr;
368  }
369 
370  bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
371  if (CallbackRecordDecl && !isLambdaCall) {
372  LLVM_DEBUG(llvm::dbgs()
373  << "Not supported: synthesizing body for functors when "
374  << "body farming std::call_once, ignoring the call.");
375  return nullptr;
376  }
377 
378  SmallVector<Expr *, 5> CallArgs;
379  const FunctionProtoType *CallbackFunctionType;
380  if (isLambdaCall) {
381 
382  // Lambda requires callback itself inserted as a first parameter.
383  CallArgs.push_back(
384  M.makeDeclRefExpr(Callback,
385  /* RefersToEnclosingVariableOrCapture=*/ true));
386  CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
387  ->getType()
389  } else if (!CallbackType->getPointeeType().isNull()) {
390  CallbackFunctionType =
391  CallbackType->getPointeeType()->getAs<FunctionProtoType>();
392  } else {
393  CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
394  }
395 
396  if (!CallbackFunctionType)
397  return nullptr;
398 
399  // First two arguments are used for the flag and for the callback.
400  if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
401  LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
402  << "params passed to std::call_once, "
403  << "ignoring the call\n");
404  return nullptr;
405  }
406 
407  // All arguments past first two ones are passed to the callback,
408  // and we turn lvalues into rvalues if the argument is not passed by
409  // reference.
410  for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
411  const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
412  if (PDecl &&
413  CallbackFunctionType->getParamType(ParamIdx - 2)
415  .getCanonicalType() !=
417  LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
418  << "params passed to std::call_once, "
419  << "ignoring the call\n");
420  return nullptr;
421  }
422  Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
423  if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
424  QualType PTy = PDecl->getType().getNonReferenceType();
425  ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
426  }
427  CallArgs.push_back(ParamExpr);
428  }
429 
430  CallExpr *CallbackCall;
431  if (isLambdaCall) {
432 
433  CallbackCall = create_call_once_lambda_call(C, M, Callback,
434  CallbackRecordDecl, CallArgs);
435  } else {
436 
437  // Function pointer case.
438  CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
439  }
440 
441  DeclRefExpr *FlagDecl =
442  M.makeDeclRefExpr(Flag,
443  /* RefersToEnclosingVariableOrCapture=*/true);
444 
445 
446  MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
447  assert(Deref->isLValue());
448  QualType DerefType = Deref->getType();
449 
450  // Negation predicate.
451  UnaryOperator *FlagCheck = new (C) UnaryOperator(
452  /* input=*/
453  M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
454  CK_IntegralToBoolean),
455  /* opc=*/ UO_LNot,
456  /* QualType=*/ C.IntTy,
457  /* ExprValueKind=*/ VK_RValue,
458  /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
459  /* CanOverflow*/ false);
460 
461  // Create assignment.
462  BinaryOperator *FlagAssignment = M.makeAssignment(
463  Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
464  DerefType);
465 
466  auto *Out =
468  /* IsConstexpr=*/false,
469  /* init=*/nullptr,
470  /* var=*/nullptr,
471  /* cond=*/FlagCheck,
472  /* then=*/M.makeCompound({CallbackCall, FlagAssignment}));
473 
474  return Out;
475 }
476 
477 /// Create a fake body for dispatch_once.
479  // Check if we have at least two parameters.
480  if (D->param_size() != 2)
481  return nullptr;
482 
483  // Check if the first parameter is a pointer to integer type.
484  const ParmVarDecl *Predicate = D->getParamDecl(0);
485  QualType PredicateQPtrTy = Predicate->getType();
486  const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
487  if (!PredicatePtrTy)
488  return nullptr;
489  QualType PredicateTy = PredicatePtrTy->getPointeeType();
490  if (!PredicateTy->isIntegerType())
491  return nullptr;
492 
493  // Check if the second parameter is the proper block type.
494  const ParmVarDecl *Block = D->getParamDecl(1);
495  QualType Ty = Block->getType();
496  if (!isDispatchBlock(Ty))
497  return nullptr;
498 
499  // Everything checks out. Create a fakse body that checks the predicate,
500  // sets it, and calls the block. Basically, an AST dump of:
501  //
502  // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
503  // if (*predicate != ~0l) {
504  // *predicate = ~0l;
505  // block();
506  // }
507  // }
508 
509  ASTMaker M(C);
510 
511  // (1) Create the call.
512  CallExpr *CE = new (C) CallExpr(
513  /*ASTContext=*/C,
514  /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
515  /*args=*/None,
516  /*QualType=*/C.VoidTy,
517  /*ExprValueType=*/VK_RValue,
518  /*SourceLocation=*/SourceLocation());
519 
520  // (2) Create the assignment to the predicate.
521  Expr *DoneValue =
522  new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
524  /*CanOverflow*/false);
525 
526  BinaryOperator *B =
527  M.makeAssignment(
528  M.makeDereference(
529  M.makeLvalueToRvalue(
530  M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
531  PredicateTy),
532  M.makeIntegralCast(DoneValue, PredicateTy),
533  PredicateTy);
534 
535  // (3) Create the compound statement.
536  Stmt *Stmts[] = { B, CE };
537  CompoundStmt *CS = M.makeCompound(Stmts);
538 
539  // (4) Create the 'if' condition.
540  ImplicitCastExpr *LValToRval =
541  M.makeLvalueToRvalue(
542  M.makeDereference(
543  M.makeLvalueToRvalue(
544  M.makeDeclRefExpr(Predicate),
545  PredicateQPtrTy),
546  PredicateTy),
547  PredicateTy);
548 
549  Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
550  // (5) Create the 'if' statement.
551  auto *If = IfStmt::Create(C, SourceLocation(),
552  /* IsConstexpr=*/false,
553  /* init=*/nullptr,
554  /* var=*/nullptr,
555  /* cond=*/GuardCondition,
556  /* then=*/CS);
557  return If;
558 }
559 
560 /// Create a fake body for dispatch_sync.
562  // Check if we have at least two parameters.
563  if (D->param_size() != 2)
564  return nullptr;
565 
566  // Check if the second parameter is a block.
567  const ParmVarDecl *PV = D->getParamDecl(1);
568  QualType Ty = PV->getType();
569  if (!isDispatchBlock(Ty))
570  return nullptr;
571 
572  // Everything checks out. Create a fake body that just calls the block.
573  // This is basically just an AST dump of:
574  //
575  // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
576  // block();
577  // }
578  //
579  ASTMaker M(C);
580  DeclRefExpr *DR = M.makeDeclRefExpr(PV);
581  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
582  CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
583  SourceLocation());
584  return CE;
585 }
586 
588 {
589  // There are exactly 3 arguments.
590  if (D->param_size() != 3)
591  return nullptr;
592 
593  // Signature:
594  // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
595  // void *__newValue,
596  // void * volatile *__theValue)
597  // Generate body:
598  // if (oldValue == *theValue) {
599  // *theValue = newValue;
600  // return YES;
601  // }
602  // else return NO;
603 
604  QualType ResultTy = D->getReturnType();
605  bool isBoolean = ResultTy->isBooleanType();
606  if (!isBoolean && !ResultTy->isIntegralType(C))
607  return nullptr;
608 
609  const ParmVarDecl *OldValue = D->getParamDecl(0);
610  QualType OldValueTy = OldValue->getType();
611 
612  const ParmVarDecl *NewValue = D->getParamDecl(1);
613  QualType NewValueTy = NewValue->getType();
614 
615  assert(OldValueTy == NewValueTy);
616 
617  const ParmVarDecl *TheValue = D->getParamDecl(2);
618  QualType TheValueTy = TheValue->getType();
619  const PointerType *PT = TheValueTy->getAs<PointerType>();
620  if (!PT)
621  return nullptr;
622  QualType PointeeTy = PT->getPointeeType();
623 
624  ASTMaker M(C);
625  // Construct the comparison.
626  Expr *Comparison =
627  M.makeComparison(
628  M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
629  M.makeLvalueToRvalue(
630  M.makeDereference(
631  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
632  PointeeTy),
633  PointeeTy),
634  BO_EQ);
635 
636  // Construct the body of the IfStmt.
637  Stmt *Stmts[2];
638  Stmts[0] =
639  M.makeAssignment(
640  M.makeDereference(
641  M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
642  PointeeTy),
643  M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
644  NewValueTy);
645 
646  Expr *BoolVal = M.makeObjCBool(true);
647  Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
648  : M.makeIntegralCast(BoolVal, ResultTy);
649  Stmts[1] = M.makeReturn(RetVal);
650  CompoundStmt *Body = M.makeCompound(Stmts);
651 
652  // Construct the else clause.
653  BoolVal = M.makeObjCBool(false);
654  RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
655  : M.makeIntegralCast(BoolVal, ResultTy);
656  Stmt *Else = M.makeReturn(RetVal);
657 
658  /// Construct the If.
659  auto *If = IfStmt::Create(C, SourceLocation(),
660  /* IsConstexpr=*/false,
661  /* init=*/nullptr,
662  /* var=*/nullptr, Comparison, Body,
663  SourceLocation(), Else);
664 
665  return If;
666 }
667 
669  D = D->getCanonicalDecl();
670 
671  Optional<Stmt *> &Val = Bodies[D];
672  if (Val.hasValue())
673  return Val.getValue();
674 
675  Val = nullptr;
676 
677  if (D->getIdentifier() == nullptr)
678  return nullptr;
679 
680  StringRef Name = D->getName();
681  if (Name.empty())
682  return nullptr;
683 
684  FunctionFarmer FF;
685 
686  if (Name.startswith("OSAtomicCompareAndSwap") ||
687  Name.startswith("objc_atomicCompareAndSwap")) {
689  } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
690  FF = create_call_once;
691  } else {
692  FF = llvm::StringSwitch<FunctionFarmer>(Name)
693  .Case("dispatch_sync", create_dispatch_sync)
694  .Case("dispatch_once", create_dispatch_once)
695  .Default(nullptr);
696  }
697 
698  if (FF) { Val = FF(C, D); }
699  else if (Injector) { Val = Injector->getBody(D); }
700  return Val.getValue();
701 }
702 
703 static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
704  const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
705 
706  if (IVar)
707  return IVar;
708 
709  // When a readonly property is shadowed in a class extensions with a
710  // a readwrite property, the instance variable belongs to the shadowing
711  // property rather than the shadowed property. If there is no instance
712  // variable on a readonly property, check to see whether the property is
713  // shadowed and if so try to get the instance variable from shadowing
714  // property.
715  if (!Prop->isReadOnly())
716  return nullptr;
717 
718  auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
719  const ObjCInterfaceDecl *PrimaryInterface = nullptr;
720  if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
721  PrimaryInterface = InterfaceDecl;
722  } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
723  PrimaryInterface = CategoryDecl->getClassInterface();
724  } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
725  PrimaryInterface = ImplDecl->getClassInterface();
726  } else {
727  return nullptr;
728  }
729 
730  // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
731  // is guaranteed to find the shadowing property, if it exists, rather than
732  // the shadowed property.
733  auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
734  Prop->getIdentifier(), Prop->getQueryKind());
735  if (ShadowingProp && ShadowingProp != Prop) {
736  IVar = ShadowingProp->getPropertyIvarDecl();
737  }
738 
739  return IVar;
740 }
741 
743  const ObjCPropertyDecl *Prop) {
744  // First, find the backing ivar.
745  const ObjCIvarDecl *IVar = findBackingIvar(Prop);
746  if (!IVar)
747  return nullptr;
748 
749  // Ignore weak variables, which have special behavior.
751  return nullptr;
752 
753  // Look to see if Sema has synthesized a body for us. This happens in
754  // Objective-C++ because the return value may be a C++ class type with a
755  // non-trivial copy constructor. We can only do this if we can find the
756  // @synthesize for this property, though (or if we know it's been auto-
757  // synthesized).
758  const ObjCImplementationDecl *ImplDecl =
760  if (ImplDecl) {
761  for (const auto *I : ImplDecl->property_impls()) {
762  if (I->getPropertyDecl() != Prop)
763  continue;
764 
765  if (I->getGetterCXXConstructor()) {
766  ASTMaker M(Ctx);
767  return M.makeReturn(I->getGetterCXXConstructor());
768  }
769  }
770  }
771 
772  // Sanity check that the property is the same type as the ivar, or a
773  // reference to it, and that it is either an object pointer or trivially
774  // copyable.
775  if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
776  Prop->getType().getNonReferenceType()))
777  return nullptr;
778  if (!IVar->getType()->isObjCLifetimeType() &&
779  !IVar->getType().isTriviallyCopyableType(Ctx))
780  return nullptr;
781 
782  // Generate our body:
783  // return self->_ivar;
784  ASTMaker M(Ctx);
785 
786  const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
787  if (!selfVar)
788  return nullptr;
789 
790  Expr *loadedIVar =
791  M.makeObjCIvarRef(
792  M.makeLvalueToRvalue(
793  M.makeDeclRefExpr(selfVar),
794  selfVar->getType()),
795  IVar);
796 
797  if (!Prop->getType()->isReferenceType())
798  loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
799 
800  return M.makeReturn(loadedIVar);
801 }
802 
804  // We currently only know how to synthesize property accessors.
805  if (!D->isPropertyAccessor())
806  return nullptr;
807 
808  D = D->getCanonicalDecl();
809 
810  Optional<Stmt *> &Val = Bodies[D];
811  if (Val.hasValue())
812  return Val.getValue();
813  Val = nullptr;
814 
815  const ObjCPropertyDecl *Prop = D->findPropertyDecl();
816  if (!Prop)
817  return nullptr;
818 
819  // For now, we only synthesize getters.
820  // Synthesizing setters would cause false negatives in the
821  // RetainCountChecker because the method body would bind the parameter
822  // to an instance variable, causing it to escape. This would prevent
823  // warning in the following common scenario:
824  //
825  // id foo = [[NSObject alloc] init];
826  // self.foo = foo; // We should warn that foo leaks here.
827  //
828  if (D->param_size() != 0)
829  return nullptr;
830 
831  Val = createObjCPropertyGetter(C, Prop);
832 
833  return Val.getValue();
834 }
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
Defines the clang::ASTContext interface.
ObjCPropertyQueryKind getQueryKind() const
Definition: DeclObjC.h:873
Represents a function declaration or definition.
Definition: Decl.h:1739
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2541
QualType getPointeeType() const
Definition: Type.h:2554
A (possibly-)qualified type.
Definition: Type.h:638
unsigned param_size() const
Definition: DeclObjC.h:341
Stmt - This represents one statement.
Definition: Stmt.h:66
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
bool isLogicalOp() const
Definition: Expr.h:3369
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
static Stmt * create_call_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for std::call_once.
Definition: BodyFarm.cpp:318
static CallExpr * create_call_once_funcptr_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, ArrayRef< Expr *> CallArgs)
Definition: BodyFarm.cpp:250
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6249
The base class of the type hierarchy.
Definition: Type.h:1411
CanQualType LongTy
Definition: ASTContext.h:1024
Floating point control options.
Definition: LangOptions.h:307
size_t param_size() const
Definition: Decl.h:2279
static bool isDispatchBlock(QualType Ty)
Definition: BodyFarm.cpp:36
Represents a variable declaration or definition.
Definition: Decl.h:812
QualType getReturnType() const
Definition: Decl.h:2303
unsigned getNumParams() const
Definition: Type.h:3892
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6734
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
Represents a parameter to a function.
Definition: Decl.h:1551
Defines the clang::Expr interface and subclasses for C++ expressions.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Represents a struct/union/class.
Definition: Decl.h:3602
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
One of these records is kept for each identifier that is lexed.
QualType getPointeeType() const
Definition: Type.h:2658
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
A C++ nested-name-specifier augmented with source location information.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1187
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3941
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
bool isReferenceType() const
Definition: Type.h:6312
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:391
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
BinaryOperatorKind
static IfStmt * Create(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL=SourceLocation(), Stmt *Else=nullptr)
Create an IfStmt.
Definition: Stmt.cpp:841
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2205
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:832
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3248
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:332
bool isRValueReferenceType() const
Definition: Type.h:6320
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:855
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1196
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:777
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
Represents an ObjC class declaration.
Definition: DeclObjC.h:1164
Stmt *(* FunctionFarmer)(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:248
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:954
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1589
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1617
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1024
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3691
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1797
static const ObjCIvarDecl * findBackingIvar(const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:703
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:213
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:106
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
Defines an enumeration for C++ overloaded operators.
DeclContext * getDeclContext()
Definition: DeclBase.h:427
ObjCPropertyDecl * FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId, ObjCPropertyQueryKind QueryKind) const
FindPropertyVisibleInPrimaryClass - Finds declaration of the property with name &#39;PropertyId&#39; in the p...
Definition: DeclObjC.cpp:369
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1800
propimpl_range property_impls() const
Definition: DeclObjC.h:2459
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2226
static Stmt * create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
Definition: BodyFarm.cpp:587
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1907
static Stmt * createObjCPropertyGetter(ASTContext &Ctx, const ObjCPropertyDecl *Prop)
Definition: BodyFarm.cpp:742
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:406
QualType getType() const
Definition: DeclObjC.h:821
bool isComparisonOp() const
Definition: Expr.h:3339
QualType getCanonicalType() const
Definition: Type.h:6115
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3617
static Stmt * create_dispatch_sync(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_sync.
Definition: BodyFarm.cpp:561
static CallExpr * create_call_once_lambda_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, CXXRecordDecl *CallbackDecl, ArrayRef< Expr *> CallArgs)
Definition: BodyFarm.cpp:276
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1759
bool isStdNamespace() const
Definition: DeclBase.cpp:1062
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2286
CanQualType VoidTy
Definition: ASTContext.h:1015
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:721
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3066
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:249
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1549
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2292
static MemberExpr * Create(const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *memberdecl, DeclAccessPair founddecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *targs, QualType ty, ExprValueKind VK, ExprObjectKind OK)
Definition: Expr.cpp:1477
A POD class for pairing a NamedDecl* with an access specifier.
static Stmt * create_dispatch_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_once.
Definition: BodyFarm.cpp:478
Dataflow Directional Tag Classes.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1362
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1064
The name of a declaration.
bool isBooleanType() const
Definition: Type.h:6661
Stmt * getBody(const FunctionDecl *D)
Factory method for creating bodies for ordinary functions.
Definition: BodyFarm.cpp:668
const ObjCInterfaceDecl * getContainingInterface() const
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1790
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Pointer to a block type.
Definition: Type.h:2643
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2544
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6582
bool isFunctionType() const
Definition: Type.h:6296
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
bool isLValueReferenceType() const
Definition: Type.h:6316
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method&#39;s selector.
Definition: DeclObjC.cpp:1302
QualType getParamType(unsigned i) const
Definition: Type.h:3894
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2616
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isVoidType() const
Definition: Type.h:6548
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1937
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:937
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2407
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
CanQualType IntTy
Definition: ASTContext.h:1024
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:82
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1042
bool isPointerType() const
Definition: Type.h:6300
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
QualType getType() const
Definition: Decl.h:647
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2983
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:914
This represents a decl that may have a name.
Definition: Decl.h:248
bool isPropertyAccessor() const
Definition: DeclObjC.h:424
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
Comparison