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