BodyFarm.cpp revision 48fa1361505c51cdc5e78deffdbdd7c334cca5d0
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
15#include "llvm/ADT/StringSwitch.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/ExprObjC.h"
20#include "BodyFarm.h"
21
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Helper creation functions for constructing faux ASTs.
26//===----------------------------------------------------------------------===//
27
28static bool isDispatchBlock(QualType Ty) {
29  // Is it a block pointer?
30  const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
31  if (!BPT)
32    return false;
33
34  // Check if the block pointer type takes no arguments and
35  // returns void.
36  const FunctionProtoType *FT =
37  BPT->getPointeeType()->getAs<FunctionProtoType>();
38  if (!FT || !FT->getResultType()->isVoidType()  ||
39      FT->getNumArgs() != 0)
40    return false;
41
42  return true;
43}
44
45namespace {
46class ASTMaker {
47public:
48  ASTMaker(ASTContext &C) : C(C) {}
49
50  /// Create a new BinaryOperator representing a simple assignment.
51  BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
52
53  /// Create a new BinaryOperator representing a comparison.
54  BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
55                                 BinaryOperator::Opcode Op);
56
57  /// Create a new compound stmt using the provided statements.
58  CompoundStmt *makeCompound(ArrayRef<Stmt*>);
59
60  /// Create a new DeclRefExpr for the referenced variable.
61  DeclRefExpr *makeDeclRefExpr(const VarDecl *D);
62
63  /// Create a new UnaryOperator representing a dereference.
64  UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
65
66  /// Create an implicit cast for an integer conversion.
67  ImplicitCastExpr *makeIntegralCast(const Expr *Arg, QualType Ty);
68
69  /// Create an implicit cast to a builtin boolean type.
70  ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
71
72  // Create an implicit cast for lvalue-to-rvaluate conversions.
73  ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
74
75  /// Create an Objective-C bool literal.
76  ObjCBoolLiteralExpr *makeObjCBool(bool Val);
77
78  /// Create a Return statement.
79  ReturnStmt *makeReturn(const Expr *RetVal);
80
81private:
82  ASTContext &C;
83};
84}
85
86BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
87                                         QualType Ty) {
88 return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
89                               BO_Assign, Ty, VK_RValue,
90                               OK_Ordinary, SourceLocation(), false);
91}
92
93BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
94                                         BinaryOperator::Opcode Op) {
95  assert(BinaryOperator::isLogicalOp(Op) ||
96         BinaryOperator::isComparisonOp(Op));
97  return new (C) BinaryOperator(const_cast<Expr*>(LHS),
98                                const_cast<Expr*>(RHS),
99                                Op,
100                                C.getLogicalOperationType(),
101                                VK_RValue,
102                                OK_Ordinary, SourceLocation(), false);
103}
104
105CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
106  return new (C) CompoundStmt(C, const_cast<Stmt**>(Stmts.data()),
107                              Stmts.size(),
108                              SourceLocation(), SourceLocation());
109}
110
111DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D) {
112  DeclRefExpr *DR =
113    DeclRefExpr::Create(/* Ctx = */ C,
114                        /* QualifierLoc = */ NestedNameSpecifierLoc(),
115                        /* TemplateKWLoc = */ SourceLocation(),
116                        /* D = */ const_cast<VarDecl*>(D),
117                        /* isEnclosingLocal = */ false,
118                        /* NameLoc = */ SourceLocation(),
119                        /* T = */ D->getType(),
120                        /* VK = */ VK_LValue);
121  return DR;
122}
123
124UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
125  return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
126                               VK_LValue, OK_Ordinary, SourceLocation());
127}
128
129ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
130  return ImplicitCastExpr::Create(C, Ty, CK_LValueToRValue,
131                                  const_cast<Expr*>(Arg), 0, VK_RValue);
132}
133
134ImplicitCastExpr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
135  return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
136                                  const_cast<Expr*>(Arg), 0, VK_RValue);
137}
138
139ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
140  return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
141                                  const_cast<Expr*>(Arg), 0, VK_RValue);
142}
143
144ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
145  QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
146  return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
147}
148
149ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
150  return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal), 0);
151}
152
153//===----------------------------------------------------------------------===//
154// Creation functions for faux ASTs.
155//===----------------------------------------------------------------------===//
156
157typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
158
159/// Create a fake body for dispatch_once.
160static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
161  // Check if we have at least two parameters.
162  if (D->param_size() != 2)
163    return 0;
164
165  // Check if the first parameter is a pointer to integer type.
166  const ParmVarDecl *Predicate = D->getParamDecl(0);
167  QualType PredicateQPtrTy = Predicate->getType();
168  const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
169  if (!PredicatePtrTy)
170    return 0;
171  QualType PredicateTy = PredicatePtrTy->getPointeeType();
172  if (!PredicateTy->isIntegerType())
173    return 0;
174
175  // Check if the second parameter is the proper block type.
176  const ParmVarDecl *Block = D->getParamDecl(1);
177  QualType Ty = Block->getType();
178  if (!isDispatchBlock(Ty))
179    return 0;
180
181  // Everything checks out.  Create a fakse body that checks the predicate,
182  // sets it, and calls the block.  Basically, an AST dump of:
183  //
184  // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
185  //  if (!*predicate) {
186  //    *predicate = 1;
187  //    block();
188  //  }
189  // }
190
191  ASTMaker M(C);
192
193  // (1) Create the call.
194  DeclRefExpr *DR = M.makeDeclRefExpr(Block);
195  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
196  CallExpr *CE = new (C) CallExpr(C, ICE, ArrayRef<Expr*>(), C.VoidTy,
197                                  VK_RValue, SourceLocation());
198
199  // (2) Create the assignment to the predicate.
200  IntegerLiteral *IL =
201    IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), (uint64_t) 1),
202                           C.IntTy, SourceLocation());
203  BinaryOperator *B =
204    M.makeAssignment(
205       M.makeDereference(
206          M.makeLvalueToRvalue(
207            M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
208            PredicateTy),
209       M.makeIntegralCast(IL, PredicateTy),
210       PredicateTy);
211
212  // (3) Create the compound statement.
213  Stmt *Stmts[2];
214  Stmts[0] = B;
215  Stmts[1] = CE;
216  CompoundStmt *CS = M.makeCompound(ArrayRef<Stmt*>(Stmts, 2));
217
218  // (4) Create the 'if' condition.
219  ImplicitCastExpr *LValToRval =
220    M.makeLvalueToRvalue(
221      M.makeDereference(
222        M.makeLvalueToRvalue(
223          M.makeDeclRefExpr(Predicate),
224          PredicateQPtrTy),
225        PredicateTy),
226    PredicateTy);
227
228  UnaryOperator *UO = new (C) UnaryOperator(LValToRval, UO_LNot, C.IntTy,
229                                           VK_RValue, OK_Ordinary,
230                                           SourceLocation());
231
232  // (5) Create the 'if' statement.
233  IfStmt *If = new (C) IfStmt(C, SourceLocation(), 0, UO, CS);
234  return If;
235}
236
237/// Create a fake body for dispatch_sync.
238static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
239  // Check if we have at least two parameters.
240  if (D->param_size() != 2)
241    return 0;
242
243  // Check if the second parameter is a block.
244  const ParmVarDecl *PV = D->getParamDecl(1);
245  QualType Ty = PV->getType();
246  if (!isDispatchBlock(Ty))
247    return 0;
248
249  // Everything checks out.  Create a fake body that just calls the block.
250  // This is basically just an AST dump of:
251  //
252  // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
253  //   block();
254  // }
255  //
256  ASTMaker M(C);
257  DeclRefExpr *DR = M.makeDeclRefExpr(PV);
258  ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
259  CallExpr *CE = new (C) CallExpr(C, ICE, ArrayRef<Expr*>(), C.VoidTy,
260                                  VK_RValue, SourceLocation());
261  return CE;
262}
263
264static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
265{
266  // There are exactly 3 arguments.
267  if (D->param_size() != 3)
268    return 0;
269
270  // Body for:
271  //   if (oldValue == *theValue) {
272  //    *theValue = newValue;
273  //    return YES;
274  //   }
275  //   else return NO;
276
277  const ParmVarDecl *OldValue = D->getParamDecl(0);
278  QualType OldValueTy = OldValue->getType();
279
280  const ParmVarDecl *NewValue = D->getParamDecl(1);
281  QualType NewValueTy = NewValue->getType();
282
283  assert(OldValueTy == NewValueTy);
284
285  const ParmVarDecl *TheValue = D->getParamDecl(2);
286  QualType TheValueTy = TheValue->getType();
287  const PointerType *PT = TheValueTy->getAs<PointerType>();
288  if (!PT)
289    return 0;
290  QualType PointeeTy = PT->getPointeeType();
291
292  ASTMaker M(C);
293  // Construct the comparison.
294  Expr *Comparison =
295    M.makeComparison(
296      M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
297      M.makeLvalueToRvalue(
298        M.makeDereference(
299          M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
300          PointeeTy),
301        PointeeTy),
302      BO_EQ);
303
304  // Construct the body of the IfStmt.
305  Stmt *Stmts[2];
306  Stmts[0] =
307    M.makeAssignment(
308      M.makeDereference(
309        M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
310        PointeeTy),
311      M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
312      NewValueTy);
313  Stmts[1] =
314    M.makeReturn(M.makeIntegralCastToBoolean(M.makeObjCBool(true)));
315  CompoundStmt *Body = M.makeCompound(ArrayRef<Stmt*>(Stmts, 2));
316
317  // Construct the else clause.
318  Stmt *Else =
319    M.makeReturn(M.makeIntegralCastToBoolean(M.makeObjCBool(false)));
320
321  /// Construct the If.
322  Stmt *If =
323    new (C) IfStmt(C, SourceLocation(), 0, Comparison, Body,
324                   SourceLocation(), Else);
325
326  return If;
327}
328
329Stmt *BodyFarm::getBody(const FunctionDecl *D) {
330  D = D->getCanonicalDecl();
331
332  llvm::Optional<Stmt *> &Val = Bodies[D];
333  if (Val.hasValue())
334    return Val.getValue();
335
336  Val = 0;
337
338  if (D->getIdentifier() == 0)
339    return 0;
340
341  StringRef Name = D->getName();
342  if (Name.empty())
343    return 0;
344
345  FunctionFarmer FF;
346
347  if (Name.startswith("OSAtomicCompareAndSwap") ||
348      Name.startswith("objc_atomicCompareAndSwap")) {
349    FF = create_OSAtomicCompareAndSwap;
350  }
351  else {
352    FF = llvm::StringSwitch<FunctionFarmer>(Name)
353          .Case("dispatch_sync", create_dispatch_sync)
354          .Case("dispatch_once", create_dispatch_once)
355        .Default(NULL);
356  }
357
358  if (FF) { Val = FF(C, D); }
359  return Val.getValue();
360}
361
362