1 //===- ThreadSafetyCommon.cpp ----------------------------------*- 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 // Implementation of the interfaces declared in ThreadSafetyCommon.h
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
21 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
22 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
23 #include "clang/Analysis/AnalysisContext.h"
24 #include "clang/Analysis/CFG.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include <algorithm>
32 #include <climits>
33 #include <vector>
34 using namespace clang;
35 using namespace threadSafety;
36 
37 // From ThreadSafetyUtil.h
38 std::string threadSafety::getSourceLiteralString(const clang::Expr *CE) {
39   switch (CE->getStmtClass()) {
40     case Stmt::IntegerLiteralClass:
41       return cast<IntegerLiteral>(CE)->getValue().toString(10, true);
42     case Stmt::StringLiteralClass: {
43       std::string ret("\"");
44       ret += cast<StringLiteral>(CE)->getString();
45       ret += "\"";
46       return ret;
47     }
48     case Stmt::CharacterLiteralClass:
49     case Stmt::CXXNullPtrLiteralExprClass:
50     case Stmt::GNUNullExprClass:
51     case Stmt::CXXBoolLiteralExprClass:
52     case Stmt::FloatingLiteralClass:
53     case Stmt::ImaginaryLiteralClass:
54     case Stmt::ObjCStringLiteralClass:
55     default:
56       return "#lit";
57   }
58 }
59 
60 // Return true if E is a variable that points to an incomplete Phi node.
61 static bool isIncompletePhi(const til::SExpr *E) {
62   if (const auto *Ph = dyn_cast<til::Phi>(E))
63     return Ph->status() == til::Phi::PH_Incomplete;
64   return false;
65 }
66 
67 typedef SExprBuilder::CallingContext CallingContext;
68 
69 
70 til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
71   auto It = SMap.find(S);
72   if (It != SMap.end())
73     return It->second;
74   return nullptr;
75 }
76 
77 
78 til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
79   Walker.walk(*this);
80   return Scfg;
81 }
82 
83 static bool isCalleeArrow(const Expr *E) {
84   const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
85   return ME ? ME->isArrow() : false;
86 }
87 
88 
89 /// \brief Translate a clang expression in an attribute to a til::SExpr.
90 /// Constructs the context from D, DeclExp, and SelfDecl.
91 ///
92 /// \param AttrExp The expression to translate.
93 /// \param D       The declaration to which the attribute is attached.
94 /// \param DeclExp An expression involving the Decl to which the attribute
95 ///                is attached.  E.g. the call to a function.
96 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
97                                                const NamedDecl *D,
98                                                const Expr *DeclExp,
99                                                VarDecl *SelfDecl) {
100   // If we are processing a raw attribute expression, with no substitutions.
101   if (!DeclExp)
102     return translateAttrExpr(AttrExp, nullptr);
103 
104   CallingContext Ctx(nullptr, D);
105 
106   // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
107   // for formal parameters when we call buildMutexID later.
108   if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
109     Ctx.SelfArg   = ME->getBase();
110     Ctx.SelfArrow = ME->isArrow();
111   } else if (const CXXMemberCallExpr *CE =
112              dyn_cast<CXXMemberCallExpr>(DeclExp)) {
113     Ctx.SelfArg   = CE->getImplicitObjectArgument();
114     Ctx.SelfArrow = isCalleeArrow(CE->getCallee());
115     Ctx.NumArgs   = CE->getNumArgs();
116     Ctx.FunArgs   = CE->getArgs();
117   } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
118     Ctx.NumArgs = CE->getNumArgs();
119     Ctx.FunArgs = CE->getArgs();
120   } else if (const CXXConstructExpr *CE =
121              dyn_cast<CXXConstructExpr>(DeclExp)) {
122     Ctx.SelfArg = nullptr;  // Will be set below
123     Ctx.NumArgs = CE->getNumArgs();
124     Ctx.FunArgs = CE->getArgs();
125   } else if (D && isa<CXXDestructorDecl>(D)) {
126     // There's no such thing as a "destructor call" in the AST.
127     Ctx.SelfArg = DeclExp;
128   }
129 
130   // Hack to handle constructors, where self cannot be recovered from
131   // the expression.
132   if (SelfDecl && !Ctx.SelfArg) {
133     DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
134                         SelfDecl->getLocation());
135     Ctx.SelfArg = &SelfDRE;
136 
137     // If the attribute has no arguments, then assume the argument is "this".
138     if (!AttrExp)
139       return translateAttrExpr(Ctx.SelfArg, nullptr);
140     else  // For most attributes.
141       return translateAttrExpr(AttrExp, &Ctx);
142   }
143 
144   // If the attribute has no arguments, then assume the argument is "this".
145   if (!AttrExp)
146     return translateAttrExpr(Ctx.SelfArg, nullptr);
147   else  // For most attributes.
148     return translateAttrExpr(AttrExp, &Ctx);
149 }
150 
151 
152 /// \brief Translate a clang expression in an attribute to a til::SExpr.
153 // This assumes a CallingContext has already been created.
154 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
155                                                CallingContext *Ctx) {
156   if (!AttrExp)
157     return CapabilityExpr(nullptr, false);
158 
159   if (auto* SLit = dyn_cast<StringLiteral>(AttrExp)) {
160     if (SLit->getString() == StringRef("*"))
161       // The "*" expr is a universal lock, which essentially turns off
162       // checks until it is removed from the lockset.
163       return CapabilityExpr(new (Arena) til::Wildcard(), false);
164     else
165       // Ignore other string literals for now.
166       return CapabilityExpr(nullptr, false);
167   }
168 
169   bool Neg = false;
170   if (auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) {
171     if (OE->getOperator() == OO_Exclaim) {
172       Neg = true;
173       AttrExp = OE->getArg(0);
174     }
175   }
176   else if (auto *UO = dyn_cast<UnaryOperator>(AttrExp)) {
177     if (UO->getOpcode() == UO_LNot) {
178       Neg = true;
179       AttrExp = UO->getSubExpr();
180     }
181   }
182 
183   til::SExpr *E = translate(AttrExp, Ctx);
184 
185   // Trap mutex expressions like nullptr, or 0.
186   // Any literal value is nonsense.
187   if (!E || isa<til::Literal>(E))
188     return CapabilityExpr(nullptr, false);
189 
190   // Hack to deal with smart pointers -- strip off top-level pointer casts.
191   if (auto *CE = dyn_cast_or_null<til::Cast>(E)) {
192     if (CE->castOpcode() == til::CAST_objToPtr)
193       return CapabilityExpr(CE->expr(), Neg);
194   }
195   return CapabilityExpr(E, Neg);
196 }
197 
198 
199 
200 // Translate a clang statement or expression to a TIL expression.
201 // Also performs substitution of variables; Ctx provides the context.
202 // Dispatches on the type of S.
203 til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
204   if (!S)
205     return nullptr;
206 
207   // Check if S has already been translated and cached.
208   // This handles the lookup of SSA names for DeclRefExprs here.
209   if (til::SExpr *E = lookupStmt(S))
210     return E;
211 
212   switch (S->getStmtClass()) {
213   case Stmt::DeclRefExprClass:
214     return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
215   case Stmt::CXXThisExprClass:
216     return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
217   case Stmt::MemberExprClass:
218     return translateMemberExpr(cast<MemberExpr>(S), Ctx);
219   case Stmt::CallExprClass:
220     return translateCallExpr(cast<CallExpr>(S), Ctx);
221   case Stmt::CXXMemberCallExprClass:
222     return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
223   case Stmt::CXXOperatorCallExprClass:
224     return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
225   case Stmt::UnaryOperatorClass:
226     return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
227   case Stmt::BinaryOperatorClass:
228   case Stmt::CompoundAssignOperatorClass:
229     return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
230 
231   case Stmt::ArraySubscriptExprClass:
232     return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
233   case Stmt::ConditionalOperatorClass:
234     return translateAbstractConditionalOperator(
235              cast<ConditionalOperator>(S), Ctx);
236   case Stmt::BinaryConditionalOperatorClass:
237     return translateAbstractConditionalOperator(
238              cast<BinaryConditionalOperator>(S), Ctx);
239 
240   // We treat these as no-ops
241   case Stmt::ParenExprClass:
242     return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
243   case Stmt::ExprWithCleanupsClass:
244     return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
245   case Stmt::CXXBindTemporaryExprClass:
246     return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
247 
248   // Collect all literals
249   case Stmt::CharacterLiteralClass:
250   case Stmt::CXXNullPtrLiteralExprClass:
251   case Stmt::GNUNullExprClass:
252   case Stmt::CXXBoolLiteralExprClass:
253   case Stmt::FloatingLiteralClass:
254   case Stmt::ImaginaryLiteralClass:
255   case Stmt::IntegerLiteralClass:
256   case Stmt::StringLiteralClass:
257   case Stmt::ObjCStringLiteralClass:
258     return new (Arena) til::Literal(cast<Expr>(S));
259 
260   case Stmt::DeclStmtClass:
261     return translateDeclStmt(cast<DeclStmt>(S), Ctx);
262   default:
263     break;
264   }
265   if (const CastExpr *CE = dyn_cast<CastExpr>(S))
266     return translateCastExpr(CE, Ctx);
267 
268   return new (Arena) til::Undefined(S);
269 }
270 
271 
272 
273 til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
274                                                CallingContext *Ctx) {
275   const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
276 
277   // Function parameters require substitution and/or renaming.
278   if (const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(VD)) {
279     const FunctionDecl *FD =
280         cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
281     unsigned I = PV->getFunctionScopeIndex();
282 
283     if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) {
284       // Substitute call arguments for references to function parameters
285       assert(I < Ctx->NumArgs);
286       return translate(Ctx->FunArgs[I], Ctx->Prev);
287     }
288     // Map the param back to the param of the original function declaration
289     // for consistent comparisons.
290     VD = FD->getParamDecl(I);
291   }
292 
293   // For non-local variables, treat it as a reference to a named object.
294   return new (Arena) til::LiteralPtr(VD);
295 }
296 
297 
298 til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
299                                                CallingContext *Ctx) {
300   // Substitute for 'this'
301   if (Ctx && Ctx->SelfArg)
302     return translate(Ctx->SelfArg, Ctx->Prev);
303   assert(SelfVar && "We have no variable for 'this'!");
304   return SelfVar;
305 }
306 
307 static const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {
308   if (auto *V = dyn_cast<til::Variable>(E))
309     return V->clangDecl();
310   if (auto *Ph = dyn_cast<til::Phi>(E))
311     return Ph->clangDecl();
312   if (auto *P = dyn_cast<til::Project>(E))
313     return P->clangDecl();
314   if (auto *L = dyn_cast<til::LiteralPtr>(E))
315     return L->clangDecl();
316   return 0;
317 }
318 
319 static bool hasCppPointerType(const til::SExpr *E) {
320   auto *VD = getValueDeclFromSExpr(E);
321   if (VD && VD->getType()->isPointerType())
322     return true;
323   if (auto *C = dyn_cast<til::Cast>(E))
324     return C->castOpcode() == til::CAST_objToPtr;
325 
326   return false;
327 }
328 
329 // Grab the very first declaration of virtual method D
330 static const CXXMethodDecl *getFirstVirtualDecl(const CXXMethodDecl *D) {
331   while (true) {
332     D = D->getCanonicalDecl();
333     CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
334                                    E = D->end_overridden_methods();
335     if (I == E)
336       return D;  // Method does not override anything
337     D = *I;      // FIXME: this does not work with multiple inheritance.
338   }
339   return nullptr;
340 }
341 
342 til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
343                                               CallingContext *Ctx) {
344   til::SExpr *BE = translate(ME->getBase(), Ctx);
345   til::SExpr *E  = new (Arena) til::SApply(BE);
346 
347   const ValueDecl *D =
348       cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
349   if (auto *VD = dyn_cast<CXXMethodDecl>(D))
350     D = getFirstVirtualDecl(VD);
351 
352   til::Project *P = new (Arena) til::Project(E, D);
353   if (hasCppPointerType(BE))
354     P->setArrow(true);
355   return P;
356 }
357 
358 
359 til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
360                                             CallingContext *Ctx,
361                                             const Expr *SelfE) {
362   if (CapabilityExprMode) {
363     // Handle LOCK_RETURNED
364     const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
365     if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
366       CallingContext LRCallCtx(Ctx);
367       LRCallCtx.AttrDecl = CE->getDirectCallee();
368       LRCallCtx.SelfArg  = SelfE;
369       LRCallCtx.NumArgs  = CE->getNumArgs();
370       LRCallCtx.FunArgs  = CE->getArgs();
371       return const_cast<til::SExpr*>(
372           translateAttrExpr(At->getArg(), &LRCallCtx).sexpr());
373     }
374   }
375 
376   til::SExpr *E = translate(CE->getCallee(), Ctx);
377   for (const auto *Arg : CE->arguments()) {
378     til::SExpr *A = translate(Arg, Ctx);
379     E = new (Arena) til::Apply(E, A);
380   }
381   return new (Arena) til::Call(E, CE);
382 }
383 
384 
385 til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
386     const CXXMemberCallExpr *ME, CallingContext *Ctx) {
387   if (CapabilityExprMode) {
388     // Ignore calls to get() on smart pointers.
389     if (ME->getMethodDecl()->getNameAsString() == "get" &&
390         ME->getNumArgs() == 0) {
391       auto *E = translate(ME->getImplicitObjectArgument(), Ctx);
392       return new (Arena) til::Cast(til::CAST_objToPtr, E);
393       // return E;
394     }
395   }
396   return translateCallExpr(cast<CallExpr>(ME), Ctx,
397                            ME->getImplicitObjectArgument());
398 }
399 
400 
401 til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
402     const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
403   if (CapabilityExprMode) {
404     // Ignore operator * and operator -> on smart pointers.
405     OverloadedOperatorKind k = OCE->getOperator();
406     if (k == OO_Star || k == OO_Arrow) {
407       auto *E = translate(OCE->getArg(0), Ctx);
408       return new (Arena) til::Cast(til::CAST_objToPtr, E);
409       // return E;
410     }
411   }
412   return translateCallExpr(cast<CallExpr>(OCE), Ctx);
413 }
414 
415 
416 til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
417                                                  CallingContext *Ctx) {
418   switch (UO->getOpcode()) {
419   case UO_PostInc:
420   case UO_PostDec:
421   case UO_PreInc:
422   case UO_PreDec:
423     return new (Arena) til::Undefined(UO);
424 
425   case UO_AddrOf: {
426     if (CapabilityExprMode) {
427       // interpret &Graph::mu_ as an existential.
428       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) {
429         if (DRE->getDecl()->isCXXInstanceMember()) {
430           // This is a pointer-to-member expression, e.g. &MyClass::mu_.
431           // We interpret this syntax specially, as a wildcard.
432           auto *W = new (Arena) til::Wildcard();
433           return new (Arena) til::Project(W, DRE->getDecl());
434         }
435       }
436     }
437     // otherwise, & is a no-op
438     return translate(UO->getSubExpr(), Ctx);
439   }
440 
441   // We treat these as no-ops
442   case UO_Deref:
443   case UO_Plus:
444     return translate(UO->getSubExpr(), Ctx);
445 
446   case UO_Minus:
447     return new (Arena)
448       til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx));
449   case UO_Not:
450     return new (Arena)
451       til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx));
452   case UO_LNot:
453     return new (Arena)
454       til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx));
455 
456   // Currently unsupported
457   case UO_Real:
458   case UO_Imag:
459   case UO_Extension:
460     return new (Arena) til::Undefined(UO);
461   }
462   return new (Arena) til::Undefined(UO);
463 }
464 
465 
466 til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op,
467                                          const BinaryOperator *BO,
468                                          CallingContext *Ctx, bool Reverse) {
469    til::SExpr *E0 = translate(BO->getLHS(), Ctx);
470    til::SExpr *E1 = translate(BO->getRHS(), Ctx);
471    if (Reverse)
472      return new (Arena) til::BinaryOp(Op, E1, E0);
473    else
474      return new (Arena) til::BinaryOp(Op, E0, E1);
475 }
476 
477 
478 til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
479                                              const BinaryOperator *BO,
480                                              CallingContext *Ctx,
481                                              bool Assign) {
482   const Expr *LHS = BO->getLHS();
483   const Expr *RHS = BO->getRHS();
484   til::SExpr *E0 = translate(LHS, Ctx);
485   til::SExpr *E1 = translate(RHS, Ctx);
486 
487   const ValueDecl *VD = nullptr;
488   til::SExpr *CV = nullptr;
489   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHS)) {
490     VD = DRE->getDecl();
491     CV = lookupVarDecl(VD);
492   }
493 
494   if (!Assign) {
495     til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
496     E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
497     E1 = addStatement(E1, nullptr, VD);
498   }
499   if (VD && CV)
500     return updateVarDecl(VD, E1);
501   return new (Arena) til::Store(E0, E1);
502 }
503 
504 
505 til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
506                                                   CallingContext *Ctx) {
507   switch (BO->getOpcode()) {
508   case BO_PtrMemD:
509   case BO_PtrMemI:
510     return new (Arena) til::Undefined(BO);
511 
512   case BO_Mul:  return translateBinOp(til::BOP_Mul, BO, Ctx);
513   case BO_Div:  return translateBinOp(til::BOP_Div, BO, Ctx);
514   case BO_Rem:  return translateBinOp(til::BOP_Rem, BO, Ctx);
515   case BO_Add:  return translateBinOp(til::BOP_Add, BO, Ctx);
516   case BO_Sub:  return translateBinOp(til::BOP_Sub, BO, Ctx);
517   case BO_Shl:  return translateBinOp(til::BOP_Shl, BO, Ctx);
518   case BO_Shr:  return translateBinOp(til::BOP_Shr, BO, Ctx);
519   case BO_LT:   return translateBinOp(til::BOP_Lt,  BO, Ctx);
520   case BO_GT:   return translateBinOp(til::BOP_Lt,  BO, Ctx, true);
521   case BO_LE:   return translateBinOp(til::BOP_Leq, BO, Ctx);
522   case BO_GE:   return translateBinOp(til::BOP_Leq, BO, Ctx, true);
523   case BO_EQ:   return translateBinOp(til::BOP_Eq,  BO, Ctx);
524   case BO_NE:   return translateBinOp(til::BOP_Neq, BO, Ctx);
525   case BO_And:  return translateBinOp(til::BOP_BitAnd,   BO, Ctx);
526   case BO_Xor:  return translateBinOp(til::BOP_BitXor,   BO, Ctx);
527   case BO_Or:   return translateBinOp(til::BOP_BitOr,    BO, Ctx);
528   case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx);
529   case BO_LOr:  return translateBinOp(til::BOP_LogicOr,  BO, Ctx);
530 
531   case BO_Assign:    return translateBinAssign(til::BOP_Eq,  BO, Ctx, true);
532   case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx);
533   case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx);
534   case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx);
535   case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx);
536   case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx);
537   case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx);
538   case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx);
539   case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx);
540   case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx);
541   case BO_OrAssign:  return translateBinAssign(til::BOP_BitOr,  BO, Ctx);
542 
543   case BO_Comma:
544     // The clang CFG should have already processed both sides.
545     return translate(BO->getRHS(), Ctx);
546   }
547   return new (Arena) til::Undefined(BO);
548 }
549 
550 
551 til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
552                                             CallingContext *Ctx) {
553   clang::CastKind K = CE->getCastKind();
554   switch (K) {
555   case CK_LValueToRValue: {
556     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
557       til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
558       if (E0)
559         return E0;
560     }
561     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
562     return E0;
563     // FIXME!! -- get Load working properly
564     // return new (Arena) til::Load(E0);
565   }
566   case CK_NoOp:
567   case CK_DerivedToBase:
568   case CK_UncheckedDerivedToBase:
569   case CK_ArrayToPointerDecay:
570   case CK_FunctionToPointerDecay: {
571     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
572     return E0;
573   }
574   default: {
575     // FIXME: handle different kinds of casts.
576     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
577     if (CapabilityExprMode)
578       return E0;
579     return new (Arena) til::Cast(til::CAST_none, E0);
580   }
581   }
582 }
583 
584 
585 til::SExpr *
586 SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
587                                           CallingContext *Ctx) {
588   til::SExpr *E0 = translate(E->getBase(), Ctx);
589   til::SExpr *E1 = translate(E->getIdx(), Ctx);
590   return new (Arena) til::ArrayIndex(E0, E1);
591 }
592 
593 
594 til::SExpr *
595 SExprBuilder::translateAbstractConditionalOperator(
596     const AbstractConditionalOperator *CO, CallingContext *Ctx) {
597   auto *C = translate(CO->getCond(), Ctx);
598   auto *T = translate(CO->getTrueExpr(), Ctx);
599   auto *E = translate(CO->getFalseExpr(), Ctx);
600   return new (Arena) til::IfThenElse(C, T, E);
601 }
602 
603 
604 til::SExpr *
605 SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
606   DeclGroupRef DGrp = S->getDeclGroup();
607   for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
608     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
609       Expr *E = VD->getInit();
610       til::SExpr* SE = translate(E, Ctx);
611 
612       // Add local variables with trivial type to the variable map
613       QualType T = VD->getType();
614       if (T.isTrivialType(VD->getASTContext())) {
615         return addVarDecl(VD, SE);
616       }
617       else {
618         // TODO: add alloca
619       }
620     }
621   }
622   return nullptr;
623 }
624 
625 
626 
627 // If (E) is non-trivial, then add it to the current basic block, and
628 // update the statement map so that S refers to E.  Returns a new variable
629 // that refers to E.
630 // If E is trivial returns E.
631 til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
632                                        const ValueDecl *VD) {
633   if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))
634     return E;
635   if (VD)
636     E = new (Arena) til::Variable(E, VD);
637   CurrentInstructions.push_back(E);
638   if (S)
639     insertStmt(S, E);
640   return E;
641 }
642 
643 
644 // Returns the current value of VD, if known, and nullptr otherwise.
645 til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
646   auto It = LVarIdxMap.find(VD);
647   if (It != LVarIdxMap.end()) {
648     assert(CurrentLVarMap[It->second].first == VD);
649     return CurrentLVarMap[It->second].second;
650   }
651   return nullptr;
652 }
653 
654 
655 // if E is a til::Variable, update its clangDecl.
656 static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
657   if (!E)
658     return;
659   if (til::Variable *V = dyn_cast<til::Variable>(E)) {
660     if (!V->clangDecl())
661       V->setClangDecl(VD);
662   }
663 }
664 
665 // Adds a new variable declaration.
666 til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
667   maybeUpdateVD(E, VD);
668   LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
669   CurrentLVarMap.makeWritable();
670   CurrentLVarMap.push_back(std::make_pair(VD, E));
671   return E;
672 }
673 
674 
675 // Updates a current variable declaration.  (E.g. by assignment)
676 til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
677   maybeUpdateVD(E, VD);
678   auto It = LVarIdxMap.find(VD);
679   if (It == LVarIdxMap.end()) {
680     til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
681     til::SExpr *St  = new (Arena) til::Store(Ptr, E);
682     return St;
683   }
684   CurrentLVarMap.makeWritable();
685   CurrentLVarMap.elem(It->second).second = E;
686   return E;
687 }
688 
689 
690 // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
691 // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
692 // If E == null, this is a backedge and will be set later.
693 void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
694   unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
695   assert(ArgIndex > 0 && ArgIndex < NPreds);
696 
697   til::SExpr *CurrE = CurrentLVarMap[i].second;
698   if (CurrE->block() == CurrentBB) {
699     // We already have a Phi node in the current block,
700     // so just add the new variable to the Phi node.
701     til::Phi *Ph = dyn_cast<til::Phi>(CurrE);
702     assert(Ph && "Expecting Phi node.");
703     if (E)
704       Ph->values()[ArgIndex] = E;
705     return;
706   }
707 
708   // Make a new phi node: phi(..., E)
709   // All phi args up to the current index are set to the current value.
710   til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
711   Ph->values().setValues(NPreds, nullptr);
712   for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
713     Ph->values()[PIdx] = CurrE;
714   if (E)
715     Ph->values()[ArgIndex] = E;
716   Ph->setClangDecl(CurrentLVarMap[i].first);
717   // If E is from a back-edge, or either E or CurrE are incomplete, then
718   // mark this node as incomplete; we may need to remove it later.
719   if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE)) {
720     Ph->setStatus(til::Phi::PH_Incomplete);
721   }
722 
723   // Add Phi node to current block, and update CurrentLVarMap[i]
724   CurrentArguments.push_back(Ph);
725   if (Ph->status() == til::Phi::PH_Incomplete)
726     IncompleteArgs.push_back(Ph);
727 
728   CurrentLVarMap.makeWritable();
729   CurrentLVarMap.elem(i).second = Ph;
730 }
731 
732 
733 // Merge values from Map into the current variable map.
734 // This will construct Phi nodes in the current basic block as necessary.
735 void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
736   assert(CurrentBlockInfo && "Not processing a block!");
737 
738   if (!CurrentLVarMap.valid()) {
739     // Steal Map, using copy-on-write.
740     CurrentLVarMap = std::move(Map);
741     return;
742   }
743   if (CurrentLVarMap.sameAs(Map))
744     return;  // Easy merge: maps from different predecessors are unchanged.
745 
746   unsigned NPreds = CurrentBB->numPredecessors();
747   unsigned ESz = CurrentLVarMap.size();
748   unsigned MSz = Map.size();
749   unsigned Sz  = std::min(ESz, MSz);
750 
751   for (unsigned i=0; i<Sz; ++i) {
752     if (CurrentLVarMap[i].first != Map[i].first) {
753       // We've reached the end of variables in common.
754       CurrentLVarMap.makeWritable();
755       CurrentLVarMap.downsize(i);
756       break;
757     }
758     if (CurrentLVarMap[i].second != Map[i].second)
759       makePhiNodeVar(i, NPreds, Map[i].second);
760   }
761   if (ESz > MSz) {
762     CurrentLVarMap.makeWritable();
763     CurrentLVarMap.downsize(Map.size());
764   }
765 }
766 
767 
768 // Merge a back edge into the current variable map.
769 // This will create phi nodes for all variables in the variable map.
770 void SExprBuilder::mergeEntryMapBackEdge() {
771   // We don't have definitions for variables on the backedge, because we
772   // haven't gotten that far in the CFG.  Thus, when encountering a back edge,
773   // we conservatively create Phi nodes for all variables.  Unnecessary Phi
774   // nodes will be marked as incomplete, and stripped out at the end.
775   //
776   // An Phi node is unnecessary if it only refers to itself and one other
777   // variable, e.g. x = Phi(y, y, x)  can be reduced to x = y.
778 
779   assert(CurrentBlockInfo && "Not processing a block!");
780 
781   if (CurrentBlockInfo->HasBackEdges)
782     return;
783   CurrentBlockInfo->HasBackEdges = true;
784 
785   CurrentLVarMap.makeWritable();
786   unsigned Sz = CurrentLVarMap.size();
787   unsigned NPreds = CurrentBB->numPredecessors();
788 
789   for (unsigned i=0; i < Sz; ++i) {
790     makePhiNodeVar(i, NPreds, nullptr);
791   }
792 }
793 
794 
795 // Update the phi nodes that were initially created for a back edge
796 // once the variable definitions have been computed.
797 // I.e., merge the current variable map into the phi nodes for Blk.
798 void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
799   til::BasicBlock *BB = lookupBlock(Blk);
800   unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
801   assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
802 
803   for (til::SExpr *PE : BB->arguments()) {
804     til::Phi *Ph = dyn_cast_or_null<til::Phi>(PE);
805     assert(Ph && "Expecting Phi Node.");
806     assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
807 
808     til::SExpr *E = lookupVarDecl(Ph->clangDecl());
809     assert(E && "Couldn't find local variable for Phi node.");
810     Ph->values()[ArgIndex] = E;
811   }
812 }
813 
814 void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D,
815                             const CFGBlock *First) {
816   // Perform initial setup operations.
817   unsigned NBlocks = Cfg->getNumBlockIDs();
818   Scfg = new (Arena) til::SCFG(Arena, NBlocks);
819 
820   // allocate all basic blocks immediately, to handle forward references.
821   BBInfo.resize(NBlocks);
822   BlockMap.resize(NBlocks, nullptr);
823   // create map from clang blockID to til::BasicBlocks
824   for (auto *B : *Cfg) {
825     auto *BB = new (Arena) til::BasicBlock(Arena);
826     BB->reserveInstructions(B->size());
827     BlockMap[B->getBlockID()] = BB;
828   }
829 
830   CurrentBB = lookupBlock(&Cfg->getEntry());
831   auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters()
832                                       : cast<FunctionDecl>(D)->parameters();
833   for (auto *Pm : Parms) {
834     QualType T = Pm->getType();
835     if (!T.isTrivialType(Pm->getASTContext()))
836       continue;
837 
838     // Add parameters to local variable map.
839     // FIXME: right now we emulate params with loads; that should be fixed.
840     til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
841     til::SExpr *Ld = new (Arena) til::Load(Lp);
842     til::SExpr *V  = addStatement(Ld, nullptr, Pm);
843     addVarDecl(Pm, V);
844   }
845 }
846 
847 
848 void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
849   // Intialize TIL basic block and add it to the CFG.
850   CurrentBB = lookupBlock(B);
851   CurrentBB->reservePredecessors(B->pred_size());
852   Scfg->add(CurrentBB);
853 
854   CurrentBlockInfo = &BBInfo[B->getBlockID()];
855 
856   // CurrentLVarMap is moved to ExitMap on block exit.
857   // FIXME: the entry block will hold function parameters.
858   // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
859 }
860 
861 
862 void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
863   // Compute CurrentLVarMap on entry from ExitMaps of predecessors
864 
865   CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]);
866   BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
867   assert(PredInfo->UnprocessedSuccessors > 0);
868 
869   if (--PredInfo->UnprocessedSuccessors == 0)
870     mergeEntryMap(std::move(PredInfo->ExitMap));
871   else
872     mergeEntryMap(PredInfo->ExitMap.clone());
873 
874   ++CurrentBlockInfo->ProcessedPredecessors;
875 }
876 
877 
878 void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
879   mergeEntryMapBackEdge();
880 }
881 
882 
883 void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
884   // The merge*() methods have created arguments.
885   // Push those arguments onto the basic block.
886   CurrentBB->arguments().reserve(
887     static_cast<unsigned>(CurrentArguments.size()), Arena);
888   for (auto *A : CurrentArguments)
889     CurrentBB->addArgument(A);
890 }
891 
892 
893 void SExprBuilder::handleStatement(const Stmt *S) {
894   til::SExpr *E = translate(S, nullptr);
895   addStatement(E, S);
896 }
897 
898 
899 void SExprBuilder::handleDestructorCall(const VarDecl *VD,
900                                         const CXXDestructorDecl *DD) {
901   til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
902   til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
903   til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
904   til::SExpr *E = new (Arena) til::Call(Ap);
905   addStatement(E, nullptr);
906 }
907 
908 
909 
910 void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
911   CurrentBB->instructions().reserve(
912     static_cast<unsigned>(CurrentInstructions.size()), Arena);
913   for (auto *V : CurrentInstructions)
914     CurrentBB->addInstruction(V);
915 
916   // Create an appropriate terminator
917   unsigned N = B->succ_size();
918   auto It = B->succ_begin();
919   if (N == 1) {
920     til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
921     // TODO: set index
922     unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0;
923     auto *Tm = new (Arena) til::Goto(BB, Idx);
924     CurrentBB->setTerminator(Tm);
925   }
926   else if (N == 2) {
927     til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr);
928     til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
929     ++It;
930     til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
931     // FIXME: make sure these arent' critical edges.
932     auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
933     CurrentBB->setTerminator(Tm);
934   }
935 }
936 
937 
938 void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
939   ++CurrentBlockInfo->UnprocessedSuccessors;
940 }
941 
942 
943 void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
944   mergePhiNodesBackEdge(Succ);
945   ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
946 }
947 
948 
949 void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
950   CurrentArguments.clear();
951   CurrentInstructions.clear();
952   CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
953   CurrentBB = nullptr;
954   CurrentBlockInfo = nullptr;
955 }
956 
957 
958 void SExprBuilder::exitCFG(const CFGBlock *Last) {
959   for (auto *Ph : IncompleteArgs) {
960     if (Ph->status() == til::Phi::PH_Incomplete)
961       simplifyIncompleteArg(Ph);
962   }
963 
964   CurrentArguments.clear();
965   CurrentInstructions.clear();
966   IncompleteArgs.clear();
967 }
968 
969 
970 /*
971 void printSCFG(CFGWalker &Walker) {
972   llvm::BumpPtrAllocator Bpa;
973   til::MemRegionRef Arena(&Bpa);
974   SExprBuilder SxBuilder(Arena);
975   til::SCFG *Scfg = SxBuilder.buildCFG(Walker);
976   TILPrinter::print(Scfg, llvm::errs());
977 }
978 */
979