xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Analysis/ThreadSafetyCommon.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- ThreadSafetyCommon.cpp ---------------------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // Implementation of the interfaces declared in ThreadSafetyCommon.h
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
147330f729Sjoerg #include "clang/AST/Attr.h"
157330f729Sjoerg #include "clang/AST/Decl.h"
167330f729Sjoerg #include "clang/AST/DeclCXX.h"
177330f729Sjoerg #include "clang/AST/DeclGroup.h"
187330f729Sjoerg #include "clang/AST/DeclObjC.h"
197330f729Sjoerg #include "clang/AST/Expr.h"
207330f729Sjoerg #include "clang/AST/ExprCXX.h"
217330f729Sjoerg #include "clang/AST/OperationKinds.h"
227330f729Sjoerg #include "clang/AST/Stmt.h"
237330f729Sjoerg #include "clang/AST/Type.h"
247330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
257330f729Sjoerg #include "clang/Analysis/CFG.h"
267330f729Sjoerg #include "clang/Basic/LLVM.h"
277330f729Sjoerg #include "clang/Basic/OperatorKinds.h"
287330f729Sjoerg #include "clang/Basic/Specifiers.h"
297330f729Sjoerg #include "llvm/ADT/StringRef.h"
307330f729Sjoerg #include "llvm/Support/Casting.h"
317330f729Sjoerg #include <algorithm>
327330f729Sjoerg #include <cassert>
337330f729Sjoerg #include <string>
347330f729Sjoerg #include <utility>
357330f729Sjoerg 
367330f729Sjoerg using namespace clang;
377330f729Sjoerg using namespace threadSafety;
387330f729Sjoerg 
397330f729Sjoerg // From ThreadSafetyUtil.h
getSourceLiteralString(const Expr * CE)407330f729Sjoerg std::string threadSafety::getSourceLiteralString(const Expr *CE) {
417330f729Sjoerg   switch (CE->getStmtClass()) {
427330f729Sjoerg     case Stmt::IntegerLiteralClass:
437330f729Sjoerg       return cast<IntegerLiteral>(CE)->getValue().toString(10, true);
447330f729Sjoerg     case Stmt::StringLiteralClass: {
457330f729Sjoerg       std::string ret("\"");
467330f729Sjoerg       ret += cast<StringLiteral>(CE)->getString();
477330f729Sjoerg       ret += "\"";
487330f729Sjoerg       return ret;
497330f729Sjoerg     }
507330f729Sjoerg     case Stmt::CharacterLiteralClass:
517330f729Sjoerg     case Stmt::CXXNullPtrLiteralExprClass:
527330f729Sjoerg     case Stmt::GNUNullExprClass:
537330f729Sjoerg     case Stmt::CXXBoolLiteralExprClass:
547330f729Sjoerg     case Stmt::FloatingLiteralClass:
557330f729Sjoerg     case Stmt::ImaginaryLiteralClass:
567330f729Sjoerg     case Stmt::ObjCStringLiteralClass:
577330f729Sjoerg     default:
587330f729Sjoerg       return "#lit";
597330f729Sjoerg   }
607330f729Sjoerg }
617330f729Sjoerg 
627330f729Sjoerg // Return true if E is a variable that points to an incomplete Phi node.
isIncompletePhi(const til::SExpr * E)637330f729Sjoerg static bool isIncompletePhi(const til::SExpr *E) {
647330f729Sjoerg   if (const auto *Ph = dyn_cast<til::Phi>(E))
657330f729Sjoerg     return Ph->status() == til::Phi::PH_Incomplete;
667330f729Sjoerg   return false;
677330f729Sjoerg }
687330f729Sjoerg 
697330f729Sjoerg using CallingContext = SExprBuilder::CallingContext;
707330f729Sjoerg 
lookupStmt(const Stmt * S)717330f729Sjoerg til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
727330f729Sjoerg   auto It = SMap.find(S);
737330f729Sjoerg   if (It != SMap.end())
747330f729Sjoerg     return It->second;
757330f729Sjoerg   return nullptr;
767330f729Sjoerg }
777330f729Sjoerg 
buildCFG(CFGWalker & Walker)787330f729Sjoerg til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
797330f729Sjoerg   Walker.walk(*this);
807330f729Sjoerg   return Scfg;
817330f729Sjoerg }
827330f729Sjoerg 
isCalleeArrow(const Expr * E)837330f729Sjoerg static bool isCalleeArrow(const Expr *E) {
847330f729Sjoerg   const auto *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
857330f729Sjoerg   return ME ? ME->isArrow() : false;
867330f729Sjoerg }
877330f729Sjoerg 
887330f729Sjoerg /// Translate a clang expression in an attribute to a til::SExpr.
897330f729Sjoerg /// Constructs the context from D, DeclExp, and SelfDecl.
907330f729Sjoerg ///
917330f729Sjoerg /// \param AttrExp The expression to translate.
927330f729Sjoerg /// \param D       The declaration to which the attribute is attached.
937330f729Sjoerg /// \param DeclExp An expression involving the Decl to which the attribute
947330f729Sjoerg ///                is attached.  E.g. the call to a function.
translateAttrExpr(const Expr * AttrExp,const NamedDecl * D,const Expr * DeclExp,VarDecl * SelfDecl)957330f729Sjoerg CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
967330f729Sjoerg                                                const NamedDecl *D,
977330f729Sjoerg                                                const Expr *DeclExp,
987330f729Sjoerg                                                VarDecl *SelfDecl) {
997330f729Sjoerg   // If we are processing a raw attribute expression, with no substitutions.
1007330f729Sjoerg   if (!DeclExp)
1017330f729Sjoerg     return translateAttrExpr(AttrExp, nullptr);
1027330f729Sjoerg 
1037330f729Sjoerg   CallingContext Ctx(nullptr, D);
1047330f729Sjoerg 
1057330f729Sjoerg   // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
1067330f729Sjoerg   // for formal parameters when we call buildMutexID later.
1077330f729Sjoerg   if (const auto *ME = dyn_cast<MemberExpr>(DeclExp)) {
1087330f729Sjoerg     Ctx.SelfArg   = ME->getBase();
1097330f729Sjoerg     Ctx.SelfArrow = ME->isArrow();
1107330f729Sjoerg   } else if (const auto *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
1117330f729Sjoerg     Ctx.SelfArg   = CE->getImplicitObjectArgument();
1127330f729Sjoerg     Ctx.SelfArrow = isCalleeArrow(CE->getCallee());
1137330f729Sjoerg     Ctx.NumArgs   = CE->getNumArgs();
1147330f729Sjoerg     Ctx.FunArgs   = CE->getArgs();
1157330f729Sjoerg   } else if (const auto *CE = dyn_cast<CallExpr>(DeclExp)) {
1167330f729Sjoerg     Ctx.NumArgs = CE->getNumArgs();
1177330f729Sjoerg     Ctx.FunArgs = CE->getArgs();
1187330f729Sjoerg   } else if (const auto *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
1197330f729Sjoerg     Ctx.SelfArg = nullptr;  // Will be set below
1207330f729Sjoerg     Ctx.NumArgs = CE->getNumArgs();
1217330f729Sjoerg     Ctx.FunArgs = CE->getArgs();
1227330f729Sjoerg   } else if (D && isa<CXXDestructorDecl>(D)) {
1237330f729Sjoerg     // There's no such thing as a "destructor call" in the AST.
1247330f729Sjoerg     Ctx.SelfArg = DeclExp;
1257330f729Sjoerg   }
1267330f729Sjoerg 
1277330f729Sjoerg   // Hack to handle constructors, where self cannot be recovered from
1287330f729Sjoerg   // the expression.
1297330f729Sjoerg   if (SelfDecl && !Ctx.SelfArg) {
1307330f729Sjoerg     DeclRefExpr SelfDRE(SelfDecl->getASTContext(), SelfDecl, false,
1317330f729Sjoerg                         SelfDecl->getType(), VK_LValue,
1327330f729Sjoerg                         SelfDecl->getLocation());
1337330f729Sjoerg     Ctx.SelfArg = &SelfDRE;
1347330f729Sjoerg 
1357330f729Sjoerg     // If the attribute has no arguments, then assume the argument is "this".
1367330f729Sjoerg     if (!AttrExp)
1377330f729Sjoerg       return translateAttrExpr(Ctx.SelfArg, nullptr);
1387330f729Sjoerg     else  // For most attributes.
1397330f729Sjoerg       return translateAttrExpr(AttrExp, &Ctx);
1407330f729Sjoerg   }
1417330f729Sjoerg 
1427330f729Sjoerg   // If the attribute has no arguments, then assume the argument is "this".
1437330f729Sjoerg   if (!AttrExp)
1447330f729Sjoerg     return translateAttrExpr(Ctx.SelfArg, nullptr);
1457330f729Sjoerg   else  // For most attributes.
1467330f729Sjoerg     return translateAttrExpr(AttrExp, &Ctx);
1477330f729Sjoerg }
1487330f729Sjoerg 
1497330f729Sjoerg /// Translate a clang expression in an attribute to a til::SExpr.
1507330f729Sjoerg // This assumes a CallingContext has already been created.
translateAttrExpr(const Expr * AttrExp,CallingContext * Ctx)1517330f729Sjoerg CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
1527330f729Sjoerg                                                CallingContext *Ctx) {
1537330f729Sjoerg   if (!AttrExp)
1547330f729Sjoerg     return CapabilityExpr(nullptr, false);
1557330f729Sjoerg 
1567330f729Sjoerg   if (const auto* SLit = dyn_cast<StringLiteral>(AttrExp)) {
1577330f729Sjoerg     if (SLit->getString() == StringRef("*"))
1587330f729Sjoerg       // The "*" expr is a universal lock, which essentially turns off
1597330f729Sjoerg       // checks until it is removed from the lockset.
1607330f729Sjoerg       return CapabilityExpr(new (Arena) til::Wildcard(), false);
1617330f729Sjoerg     else
1627330f729Sjoerg       // Ignore other string literals for now.
1637330f729Sjoerg       return CapabilityExpr(nullptr, false);
1647330f729Sjoerg   }
1657330f729Sjoerg 
1667330f729Sjoerg   bool Neg = false;
1677330f729Sjoerg   if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) {
1687330f729Sjoerg     if (OE->getOperator() == OO_Exclaim) {
1697330f729Sjoerg       Neg = true;
1707330f729Sjoerg       AttrExp = OE->getArg(0);
1717330f729Sjoerg     }
1727330f729Sjoerg   }
1737330f729Sjoerg   else if (const auto *UO = dyn_cast<UnaryOperator>(AttrExp)) {
1747330f729Sjoerg     if (UO->getOpcode() == UO_LNot) {
1757330f729Sjoerg       Neg = true;
1767330f729Sjoerg       AttrExp = UO->getSubExpr();
1777330f729Sjoerg     }
1787330f729Sjoerg   }
1797330f729Sjoerg 
1807330f729Sjoerg   til::SExpr *E = translate(AttrExp, Ctx);
1817330f729Sjoerg 
1827330f729Sjoerg   // Trap mutex expressions like nullptr, or 0.
1837330f729Sjoerg   // Any literal value is nonsense.
1847330f729Sjoerg   if (!E || isa<til::Literal>(E))
1857330f729Sjoerg     return CapabilityExpr(nullptr, false);
1867330f729Sjoerg 
1877330f729Sjoerg   // Hack to deal with smart pointers -- strip off top-level pointer casts.
188*e038c9c4Sjoerg   if (const auto *CE = dyn_cast<til::Cast>(E)) {
1897330f729Sjoerg     if (CE->castOpcode() == til::CAST_objToPtr)
1907330f729Sjoerg       return CapabilityExpr(CE->expr(), Neg);
1917330f729Sjoerg   }
1927330f729Sjoerg   return CapabilityExpr(E, Neg);
1937330f729Sjoerg }
1947330f729Sjoerg 
1957330f729Sjoerg // Translate a clang statement or expression to a TIL expression.
1967330f729Sjoerg // Also performs substitution of variables; Ctx provides the context.
1977330f729Sjoerg // Dispatches on the type of S.
translate(const Stmt * S,CallingContext * Ctx)1987330f729Sjoerg til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
1997330f729Sjoerg   if (!S)
2007330f729Sjoerg     return nullptr;
2017330f729Sjoerg 
2027330f729Sjoerg   // Check if S has already been translated and cached.
2037330f729Sjoerg   // This handles the lookup of SSA names for DeclRefExprs here.
2047330f729Sjoerg   if (til::SExpr *E = lookupStmt(S))
2057330f729Sjoerg     return E;
2067330f729Sjoerg 
2077330f729Sjoerg   switch (S->getStmtClass()) {
2087330f729Sjoerg   case Stmt::DeclRefExprClass:
2097330f729Sjoerg     return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
2107330f729Sjoerg   case Stmt::CXXThisExprClass:
2117330f729Sjoerg     return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
2127330f729Sjoerg   case Stmt::MemberExprClass:
2137330f729Sjoerg     return translateMemberExpr(cast<MemberExpr>(S), Ctx);
2147330f729Sjoerg   case Stmt::ObjCIvarRefExprClass:
2157330f729Sjoerg     return translateObjCIVarRefExpr(cast<ObjCIvarRefExpr>(S), Ctx);
2167330f729Sjoerg   case Stmt::CallExprClass:
2177330f729Sjoerg     return translateCallExpr(cast<CallExpr>(S), Ctx);
2187330f729Sjoerg   case Stmt::CXXMemberCallExprClass:
2197330f729Sjoerg     return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
2207330f729Sjoerg   case Stmt::CXXOperatorCallExprClass:
2217330f729Sjoerg     return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
2227330f729Sjoerg   case Stmt::UnaryOperatorClass:
2237330f729Sjoerg     return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
2247330f729Sjoerg   case Stmt::BinaryOperatorClass:
2257330f729Sjoerg   case Stmt::CompoundAssignOperatorClass:
2267330f729Sjoerg     return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
2277330f729Sjoerg 
2287330f729Sjoerg   case Stmt::ArraySubscriptExprClass:
2297330f729Sjoerg     return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
2307330f729Sjoerg   case Stmt::ConditionalOperatorClass:
2317330f729Sjoerg     return translateAbstractConditionalOperator(
2327330f729Sjoerg              cast<ConditionalOperator>(S), Ctx);
2337330f729Sjoerg   case Stmt::BinaryConditionalOperatorClass:
2347330f729Sjoerg     return translateAbstractConditionalOperator(
2357330f729Sjoerg              cast<BinaryConditionalOperator>(S), Ctx);
2367330f729Sjoerg 
2377330f729Sjoerg   // We treat these as no-ops
2387330f729Sjoerg   case Stmt::ConstantExprClass:
2397330f729Sjoerg     return translate(cast<ConstantExpr>(S)->getSubExpr(), Ctx);
2407330f729Sjoerg   case Stmt::ParenExprClass:
2417330f729Sjoerg     return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
2427330f729Sjoerg   case Stmt::ExprWithCleanupsClass:
2437330f729Sjoerg     return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
2447330f729Sjoerg   case Stmt::CXXBindTemporaryExprClass:
2457330f729Sjoerg     return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
2467330f729Sjoerg   case Stmt::MaterializeTemporaryExprClass:
247*e038c9c4Sjoerg     return translate(cast<MaterializeTemporaryExpr>(S)->getSubExpr(), Ctx);
2487330f729Sjoerg 
2497330f729Sjoerg   // Collect all literals
2507330f729Sjoerg   case Stmt::CharacterLiteralClass:
2517330f729Sjoerg   case Stmt::CXXNullPtrLiteralExprClass:
2527330f729Sjoerg   case Stmt::GNUNullExprClass:
2537330f729Sjoerg   case Stmt::CXXBoolLiteralExprClass:
2547330f729Sjoerg   case Stmt::FloatingLiteralClass:
2557330f729Sjoerg   case Stmt::ImaginaryLiteralClass:
2567330f729Sjoerg   case Stmt::IntegerLiteralClass:
2577330f729Sjoerg   case Stmt::StringLiteralClass:
2587330f729Sjoerg   case Stmt::ObjCStringLiteralClass:
2597330f729Sjoerg     return new (Arena) til::Literal(cast<Expr>(S));
2607330f729Sjoerg 
2617330f729Sjoerg   case Stmt::DeclStmtClass:
2627330f729Sjoerg     return translateDeclStmt(cast<DeclStmt>(S), Ctx);
2637330f729Sjoerg   default:
2647330f729Sjoerg     break;
2657330f729Sjoerg   }
2667330f729Sjoerg   if (const auto *CE = dyn_cast<CastExpr>(S))
2677330f729Sjoerg     return translateCastExpr(CE, Ctx);
2687330f729Sjoerg 
2697330f729Sjoerg   return new (Arena) til::Undefined(S);
2707330f729Sjoerg }
2717330f729Sjoerg 
translateDeclRefExpr(const DeclRefExpr * DRE,CallingContext * Ctx)2727330f729Sjoerg til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
2737330f729Sjoerg                                                CallingContext *Ctx) {
2747330f729Sjoerg   const auto *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
2757330f729Sjoerg 
2767330f729Sjoerg   // Function parameters require substitution and/or renaming.
277*e038c9c4Sjoerg   if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
2787330f729Sjoerg     unsigned I = PV->getFunctionScopeIndex();
2797330f729Sjoerg     const DeclContext *D = PV->getDeclContext();
2807330f729Sjoerg     if (Ctx && Ctx->FunArgs) {
2817330f729Sjoerg       const Decl *Canonical = Ctx->AttrDecl->getCanonicalDecl();
2827330f729Sjoerg       if (isa<FunctionDecl>(D)
2837330f729Sjoerg               ? (cast<FunctionDecl>(D)->getCanonicalDecl() == Canonical)
2847330f729Sjoerg               : (cast<ObjCMethodDecl>(D)->getCanonicalDecl() == Canonical)) {
2857330f729Sjoerg         // Substitute call arguments for references to function parameters
2867330f729Sjoerg         assert(I < Ctx->NumArgs);
2877330f729Sjoerg         return translate(Ctx->FunArgs[I], Ctx->Prev);
2887330f729Sjoerg       }
2897330f729Sjoerg     }
2907330f729Sjoerg     // Map the param back to the param of the original function declaration
2917330f729Sjoerg     // for consistent comparisons.
2927330f729Sjoerg     VD = isa<FunctionDecl>(D)
2937330f729Sjoerg              ? cast<FunctionDecl>(D)->getCanonicalDecl()->getParamDecl(I)
2947330f729Sjoerg              : cast<ObjCMethodDecl>(D)->getCanonicalDecl()->getParamDecl(I);
2957330f729Sjoerg   }
2967330f729Sjoerg 
2977330f729Sjoerg   // For non-local variables, treat it as a reference to a named object.
2987330f729Sjoerg   return new (Arena) til::LiteralPtr(VD);
2997330f729Sjoerg }
3007330f729Sjoerg 
translateCXXThisExpr(const CXXThisExpr * TE,CallingContext * Ctx)3017330f729Sjoerg til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
3027330f729Sjoerg                                                CallingContext *Ctx) {
3037330f729Sjoerg   // Substitute for 'this'
3047330f729Sjoerg   if (Ctx && Ctx->SelfArg)
3057330f729Sjoerg     return translate(Ctx->SelfArg, Ctx->Prev);
3067330f729Sjoerg   assert(SelfVar && "We have no variable for 'this'!");
3077330f729Sjoerg   return SelfVar;
3087330f729Sjoerg }
3097330f729Sjoerg 
getValueDeclFromSExpr(const til::SExpr * E)3107330f729Sjoerg static const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {
3117330f729Sjoerg   if (const auto *V = dyn_cast<til::Variable>(E))
3127330f729Sjoerg     return V->clangDecl();
3137330f729Sjoerg   if (const auto *Ph = dyn_cast<til::Phi>(E))
3147330f729Sjoerg     return Ph->clangDecl();
3157330f729Sjoerg   if (const auto *P = dyn_cast<til::Project>(E))
3167330f729Sjoerg     return P->clangDecl();
3177330f729Sjoerg   if (const auto *L = dyn_cast<til::LiteralPtr>(E))
3187330f729Sjoerg     return L->clangDecl();
3197330f729Sjoerg   return nullptr;
3207330f729Sjoerg }
3217330f729Sjoerg 
hasAnyPointerType(const til::SExpr * E)3227330f729Sjoerg static bool hasAnyPointerType(const til::SExpr *E) {
3237330f729Sjoerg   auto *VD = getValueDeclFromSExpr(E);
3247330f729Sjoerg   if (VD && VD->getType()->isAnyPointerType())
3257330f729Sjoerg     return true;
3267330f729Sjoerg   if (const auto *C = dyn_cast<til::Cast>(E))
3277330f729Sjoerg     return C->castOpcode() == til::CAST_objToPtr;
3287330f729Sjoerg 
3297330f729Sjoerg   return false;
3307330f729Sjoerg }
3317330f729Sjoerg 
3327330f729Sjoerg // Grab the very first declaration of virtual method D
getFirstVirtualDecl(const CXXMethodDecl * D)3337330f729Sjoerg static const CXXMethodDecl *getFirstVirtualDecl(const CXXMethodDecl *D) {
3347330f729Sjoerg   while (true) {
3357330f729Sjoerg     D = D->getCanonicalDecl();
3367330f729Sjoerg     auto OverriddenMethods = D->overridden_methods();
3377330f729Sjoerg     if (OverriddenMethods.begin() == OverriddenMethods.end())
3387330f729Sjoerg       return D;  // Method does not override anything
3397330f729Sjoerg     // FIXME: this does not work with multiple inheritance.
3407330f729Sjoerg     D = *OverriddenMethods.begin();
3417330f729Sjoerg   }
3427330f729Sjoerg   return nullptr;
3437330f729Sjoerg }
3447330f729Sjoerg 
translateMemberExpr(const MemberExpr * ME,CallingContext * Ctx)3457330f729Sjoerg til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
3467330f729Sjoerg                                               CallingContext *Ctx) {
3477330f729Sjoerg   til::SExpr *BE = translate(ME->getBase(), Ctx);
3487330f729Sjoerg   til::SExpr *E  = new (Arena) til::SApply(BE);
3497330f729Sjoerg 
3507330f729Sjoerg   const auto *D = cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
3517330f729Sjoerg   if (const auto *VD = dyn_cast<CXXMethodDecl>(D))
3527330f729Sjoerg     D = getFirstVirtualDecl(VD);
3537330f729Sjoerg 
3547330f729Sjoerg   til::Project *P = new (Arena) til::Project(E, D);
3557330f729Sjoerg   if (hasAnyPointerType(BE))
3567330f729Sjoerg     P->setArrow(true);
3577330f729Sjoerg   return P;
3587330f729Sjoerg }
3597330f729Sjoerg 
translateObjCIVarRefExpr(const ObjCIvarRefExpr * IVRE,CallingContext * Ctx)3607330f729Sjoerg til::SExpr *SExprBuilder::translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE,
3617330f729Sjoerg                                                    CallingContext *Ctx) {
3627330f729Sjoerg   til::SExpr *BE = translate(IVRE->getBase(), Ctx);
3637330f729Sjoerg   til::SExpr *E = new (Arena) til::SApply(BE);
3647330f729Sjoerg 
3657330f729Sjoerg   const auto *D = cast<ObjCIvarDecl>(IVRE->getDecl()->getCanonicalDecl());
3667330f729Sjoerg 
3677330f729Sjoerg   til::Project *P = new (Arena) til::Project(E, D);
3687330f729Sjoerg   if (hasAnyPointerType(BE))
3697330f729Sjoerg     P->setArrow(true);
3707330f729Sjoerg   return P;
3717330f729Sjoerg }
3727330f729Sjoerg 
translateCallExpr(const CallExpr * CE,CallingContext * Ctx,const Expr * SelfE)3737330f729Sjoerg til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
3747330f729Sjoerg                                             CallingContext *Ctx,
3757330f729Sjoerg                                             const Expr *SelfE) {
3767330f729Sjoerg   if (CapabilityExprMode) {
3777330f729Sjoerg     // Handle LOCK_RETURNED
3787330f729Sjoerg     if (const FunctionDecl *FD = CE->getDirectCallee()) {
3797330f729Sjoerg       FD = FD->getMostRecentDecl();
3807330f729Sjoerg       if (LockReturnedAttr *At = FD->getAttr<LockReturnedAttr>()) {
3817330f729Sjoerg         CallingContext LRCallCtx(Ctx);
3827330f729Sjoerg         LRCallCtx.AttrDecl = CE->getDirectCallee();
3837330f729Sjoerg         LRCallCtx.SelfArg = SelfE;
3847330f729Sjoerg         LRCallCtx.NumArgs = CE->getNumArgs();
3857330f729Sjoerg         LRCallCtx.FunArgs = CE->getArgs();
3867330f729Sjoerg         return const_cast<til::SExpr *>(
3877330f729Sjoerg             translateAttrExpr(At->getArg(), &LRCallCtx).sexpr());
3887330f729Sjoerg       }
3897330f729Sjoerg     }
3907330f729Sjoerg   }
3917330f729Sjoerg 
3927330f729Sjoerg   til::SExpr *E = translate(CE->getCallee(), Ctx);
3937330f729Sjoerg   for (const auto *Arg : CE->arguments()) {
3947330f729Sjoerg     til::SExpr *A = translate(Arg, Ctx);
3957330f729Sjoerg     E = new (Arena) til::Apply(E, A);
3967330f729Sjoerg   }
3977330f729Sjoerg   return new (Arena) til::Call(E, CE);
3987330f729Sjoerg }
3997330f729Sjoerg 
translateCXXMemberCallExpr(const CXXMemberCallExpr * ME,CallingContext * Ctx)4007330f729Sjoerg til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
4017330f729Sjoerg     const CXXMemberCallExpr *ME, CallingContext *Ctx) {
4027330f729Sjoerg   if (CapabilityExprMode) {
4037330f729Sjoerg     // Ignore calls to get() on smart pointers.
4047330f729Sjoerg     if (ME->getMethodDecl()->getNameAsString() == "get" &&
4057330f729Sjoerg         ME->getNumArgs() == 0) {
4067330f729Sjoerg       auto *E = translate(ME->getImplicitObjectArgument(), Ctx);
4077330f729Sjoerg       return new (Arena) til::Cast(til::CAST_objToPtr, E);
4087330f729Sjoerg       // return E;
4097330f729Sjoerg     }
4107330f729Sjoerg   }
4117330f729Sjoerg   return translateCallExpr(cast<CallExpr>(ME), Ctx,
4127330f729Sjoerg                            ME->getImplicitObjectArgument());
4137330f729Sjoerg }
4147330f729Sjoerg 
translateCXXOperatorCallExpr(const CXXOperatorCallExpr * OCE,CallingContext * Ctx)4157330f729Sjoerg til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
4167330f729Sjoerg     const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
4177330f729Sjoerg   if (CapabilityExprMode) {
4187330f729Sjoerg     // Ignore operator * and operator -> on smart pointers.
4197330f729Sjoerg     OverloadedOperatorKind k = OCE->getOperator();
4207330f729Sjoerg     if (k == OO_Star || k == OO_Arrow) {
4217330f729Sjoerg       auto *E = translate(OCE->getArg(0), Ctx);
4227330f729Sjoerg       return new (Arena) til::Cast(til::CAST_objToPtr, E);
4237330f729Sjoerg       // return E;
4247330f729Sjoerg     }
4257330f729Sjoerg   }
4267330f729Sjoerg   return translateCallExpr(cast<CallExpr>(OCE), Ctx);
4277330f729Sjoerg }
4287330f729Sjoerg 
translateUnaryOperator(const UnaryOperator * UO,CallingContext * Ctx)4297330f729Sjoerg til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
4307330f729Sjoerg                                                  CallingContext *Ctx) {
4317330f729Sjoerg   switch (UO->getOpcode()) {
4327330f729Sjoerg   case UO_PostInc:
4337330f729Sjoerg   case UO_PostDec:
4347330f729Sjoerg   case UO_PreInc:
4357330f729Sjoerg   case UO_PreDec:
4367330f729Sjoerg     return new (Arena) til::Undefined(UO);
4377330f729Sjoerg 
4387330f729Sjoerg   case UO_AddrOf:
4397330f729Sjoerg     if (CapabilityExprMode) {
4407330f729Sjoerg       // interpret &Graph::mu_ as an existential.
4417330f729Sjoerg       if (const auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) {
4427330f729Sjoerg         if (DRE->getDecl()->isCXXInstanceMember()) {
4437330f729Sjoerg           // This is a pointer-to-member expression, e.g. &MyClass::mu_.
4447330f729Sjoerg           // We interpret this syntax specially, as a wildcard.
4457330f729Sjoerg           auto *W = new (Arena) til::Wildcard();
4467330f729Sjoerg           return new (Arena) til::Project(W, DRE->getDecl());
4477330f729Sjoerg         }
4487330f729Sjoerg       }
4497330f729Sjoerg     }
4507330f729Sjoerg     // otherwise, & is a no-op
4517330f729Sjoerg     return translate(UO->getSubExpr(), Ctx);
4527330f729Sjoerg 
4537330f729Sjoerg   // We treat these as no-ops
4547330f729Sjoerg   case UO_Deref:
4557330f729Sjoerg   case UO_Plus:
4567330f729Sjoerg     return translate(UO->getSubExpr(), Ctx);
4577330f729Sjoerg 
4587330f729Sjoerg   case UO_Minus:
4597330f729Sjoerg     return new (Arena)
4607330f729Sjoerg       til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx));
4617330f729Sjoerg   case UO_Not:
4627330f729Sjoerg     return new (Arena)
4637330f729Sjoerg       til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx));
4647330f729Sjoerg   case UO_LNot:
4657330f729Sjoerg     return new (Arena)
4667330f729Sjoerg       til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx));
4677330f729Sjoerg 
4687330f729Sjoerg   // Currently unsupported
4697330f729Sjoerg   case UO_Real:
4707330f729Sjoerg   case UO_Imag:
4717330f729Sjoerg   case UO_Extension:
4727330f729Sjoerg   case UO_Coawait:
4737330f729Sjoerg     return new (Arena) til::Undefined(UO);
4747330f729Sjoerg   }
4757330f729Sjoerg   return new (Arena) til::Undefined(UO);
4767330f729Sjoerg }
4777330f729Sjoerg 
translateBinOp(til::TIL_BinaryOpcode Op,const BinaryOperator * BO,CallingContext * Ctx,bool Reverse)4787330f729Sjoerg til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op,
4797330f729Sjoerg                                          const BinaryOperator *BO,
4807330f729Sjoerg                                          CallingContext *Ctx, bool Reverse) {
4817330f729Sjoerg    til::SExpr *E0 = translate(BO->getLHS(), Ctx);
4827330f729Sjoerg    til::SExpr *E1 = translate(BO->getRHS(), Ctx);
4837330f729Sjoerg    if (Reverse)
4847330f729Sjoerg      return new (Arena) til::BinaryOp(Op, E1, E0);
4857330f729Sjoerg    else
4867330f729Sjoerg      return new (Arena) til::BinaryOp(Op, E0, E1);
4877330f729Sjoerg }
4887330f729Sjoerg 
translateBinAssign(til::TIL_BinaryOpcode Op,const BinaryOperator * BO,CallingContext * Ctx,bool Assign)4897330f729Sjoerg til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
4907330f729Sjoerg                                              const BinaryOperator *BO,
4917330f729Sjoerg                                              CallingContext *Ctx,
4927330f729Sjoerg                                              bool Assign) {
4937330f729Sjoerg   const Expr *LHS = BO->getLHS();
4947330f729Sjoerg   const Expr *RHS = BO->getRHS();
4957330f729Sjoerg   til::SExpr *E0 = translate(LHS, Ctx);
4967330f729Sjoerg   til::SExpr *E1 = translate(RHS, Ctx);
4977330f729Sjoerg 
4987330f729Sjoerg   const ValueDecl *VD = nullptr;
4997330f729Sjoerg   til::SExpr *CV = nullptr;
5007330f729Sjoerg   if (const auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5017330f729Sjoerg     VD = DRE->getDecl();
5027330f729Sjoerg     CV = lookupVarDecl(VD);
5037330f729Sjoerg   }
5047330f729Sjoerg 
5057330f729Sjoerg   if (!Assign) {
5067330f729Sjoerg     til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
5077330f729Sjoerg     E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
5087330f729Sjoerg     E1 = addStatement(E1, nullptr, VD);
5097330f729Sjoerg   }
5107330f729Sjoerg   if (VD && CV)
5117330f729Sjoerg     return updateVarDecl(VD, E1);
5127330f729Sjoerg   return new (Arena) til::Store(E0, E1);
5137330f729Sjoerg }
5147330f729Sjoerg 
translateBinaryOperator(const BinaryOperator * BO,CallingContext * Ctx)5157330f729Sjoerg til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
5167330f729Sjoerg                                                   CallingContext *Ctx) {
5177330f729Sjoerg   switch (BO->getOpcode()) {
5187330f729Sjoerg   case BO_PtrMemD:
5197330f729Sjoerg   case BO_PtrMemI:
5207330f729Sjoerg     return new (Arena) til::Undefined(BO);
5217330f729Sjoerg 
5227330f729Sjoerg   case BO_Mul:  return translateBinOp(til::BOP_Mul, BO, Ctx);
5237330f729Sjoerg   case BO_Div:  return translateBinOp(til::BOP_Div, BO, Ctx);
5247330f729Sjoerg   case BO_Rem:  return translateBinOp(til::BOP_Rem, BO, Ctx);
5257330f729Sjoerg   case BO_Add:  return translateBinOp(til::BOP_Add, BO, Ctx);
5267330f729Sjoerg   case BO_Sub:  return translateBinOp(til::BOP_Sub, BO, Ctx);
5277330f729Sjoerg   case BO_Shl:  return translateBinOp(til::BOP_Shl, BO, Ctx);
5287330f729Sjoerg   case BO_Shr:  return translateBinOp(til::BOP_Shr, BO, Ctx);
5297330f729Sjoerg   case BO_LT:   return translateBinOp(til::BOP_Lt,  BO, Ctx);
5307330f729Sjoerg   case BO_GT:   return translateBinOp(til::BOP_Lt,  BO, Ctx, true);
5317330f729Sjoerg   case BO_LE:   return translateBinOp(til::BOP_Leq, BO, Ctx);
5327330f729Sjoerg   case BO_GE:   return translateBinOp(til::BOP_Leq, BO, Ctx, true);
5337330f729Sjoerg   case BO_EQ:   return translateBinOp(til::BOP_Eq,  BO, Ctx);
5347330f729Sjoerg   case BO_NE:   return translateBinOp(til::BOP_Neq, BO, Ctx);
5357330f729Sjoerg   case BO_Cmp:  return translateBinOp(til::BOP_Cmp, BO, Ctx);
5367330f729Sjoerg   case BO_And:  return translateBinOp(til::BOP_BitAnd,   BO, Ctx);
5377330f729Sjoerg   case BO_Xor:  return translateBinOp(til::BOP_BitXor,   BO, Ctx);
5387330f729Sjoerg   case BO_Or:   return translateBinOp(til::BOP_BitOr,    BO, Ctx);
5397330f729Sjoerg   case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx);
5407330f729Sjoerg   case BO_LOr:  return translateBinOp(til::BOP_LogicOr,  BO, Ctx);
5417330f729Sjoerg 
5427330f729Sjoerg   case BO_Assign:    return translateBinAssign(til::BOP_Eq,  BO, Ctx, true);
5437330f729Sjoerg   case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx);
5447330f729Sjoerg   case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx);
5457330f729Sjoerg   case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx);
5467330f729Sjoerg   case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx);
5477330f729Sjoerg   case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx);
5487330f729Sjoerg   case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx);
5497330f729Sjoerg   case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx);
5507330f729Sjoerg   case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx);
5517330f729Sjoerg   case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx);
5527330f729Sjoerg   case BO_OrAssign:  return translateBinAssign(til::BOP_BitOr,  BO, Ctx);
5537330f729Sjoerg 
5547330f729Sjoerg   case BO_Comma:
5557330f729Sjoerg     // The clang CFG should have already processed both sides.
5567330f729Sjoerg     return translate(BO->getRHS(), Ctx);
5577330f729Sjoerg   }
5587330f729Sjoerg   return new (Arena) til::Undefined(BO);
5597330f729Sjoerg }
5607330f729Sjoerg 
translateCastExpr(const CastExpr * CE,CallingContext * Ctx)5617330f729Sjoerg til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
5627330f729Sjoerg                                             CallingContext *Ctx) {
5637330f729Sjoerg   CastKind K = CE->getCastKind();
5647330f729Sjoerg   switch (K) {
5657330f729Sjoerg   case CK_LValueToRValue: {
5667330f729Sjoerg     if (const auto *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
5677330f729Sjoerg       til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
5687330f729Sjoerg       if (E0)
5697330f729Sjoerg         return E0;
5707330f729Sjoerg     }
5717330f729Sjoerg     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
5727330f729Sjoerg     return E0;
5737330f729Sjoerg     // FIXME!! -- get Load working properly
5747330f729Sjoerg     // return new (Arena) til::Load(E0);
5757330f729Sjoerg   }
5767330f729Sjoerg   case CK_NoOp:
5777330f729Sjoerg   case CK_DerivedToBase:
5787330f729Sjoerg   case CK_UncheckedDerivedToBase:
5797330f729Sjoerg   case CK_ArrayToPointerDecay:
5807330f729Sjoerg   case CK_FunctionToPointerDecay: {
5817330f729Sjoerg     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
5827330f729Sjoerg     return E0;
5837330f729Sjoerg   }
5847330f729Sjoerg   default: {
5857330f729Sjoerg     // FIXME: handle different kinds of casts.
5867330f729Sjoerg     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
5877330f729Sjoerg     if (CapabilityExprMode)
5887330f729Sjoerg       return E0;
5897330f729Sjoerg     return new (Arena) til::Cast(til::CAST_none, E0);
5907330f729Sjoerg   }
5917330f729Sjoerg   }
5927330f729Sjoerg }
5937330f729Sjoerg 
5947330f729Sjoerg til::SExpr *
translateArraySubscriptExpr(const ArraySubscriptExpr * E,CallingContext * Ctx)5957330f729Sjoerg SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
5967330f729Sjoerg                                           CallingContext *Ctx) {
5977330f729Sjoerg   til::SExpr *E0 = translate(E->getBase(), Ctx);
5987330f729Sjoerg   til::SExpr *E1 = translate(E->getIdx(), Ctx);
5997330f729Sjoerg   return new (Arena) til::ArrayIndex(E0, E1);
6007330f729Sjoerg }
6017330f729Sjoerg 
6027330f729Sjoerg til::SExpr *
translateAbstractConditionalOperator(const AbstractConditionalOperator * CO,CallingContext * Ctx)6037330f729Sjoerg SExprBuilder::translateAbstractConditionalOperator(
6047330f729Sjoerg     const AbstractConditionalOperator *CO, CallingContext *Ctx) {
6057330f729Sjoerg   auto *C = translate(CO->getCond(), Ctx);
6067330f729Sjoerg   auto *T = translate(CO->getTrueExpr(), Ctx);
6077330f729Sjoerg   auto *E = translate(CO->getFalseExpr(), Ctx);
6087330f729Sjoerg   return new (Arena) til::IfThenElse(C, T, E);
6097330f729Sjoerg }
6107330f729Sjoerg 
6117330f729Sjoerg til::SExpr *
translateDeclStmt(const DeclStmt * S,CallingContext * Ctx)6127330f729Sjoerg SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
6137330f729Sjoerg   DeclGroupRef DGrp = S->getDeclGroup();
6147330f729Sjoerg   for (auto I : DGrp) {
6157330f729Sjoerg     if (auto *VD = dyn_cast_or_null<VarDecl>(I)) {
6167330f729Sjoerg       Expr *E = VD->getInit();
6177330f729Sjoerg       til::SExpr* SE = translate(E, Ctx);
6187330f729Sjoerg 
6197330f729Sjoerg       // Add local variables with trivial type to the variable map
6207330f729Sjoerg       QualType T = VD->getType();
6217330f729Sjoerg       if (T.isTrivialType(VD->getASTContext()))
6227330f729Sjoerg         return addVarDecl(VD, SE);
6237330f729Sjoerg       else {
6247330f729Sjoerg         // TODO: add alloca
6257330f729Sjoerg       }
6267330f729Sjoerg     }
6277330f729Sjoerg   }
6287330f729Sjoerg   return nullptr;
6297330f729Sjoerg }
6307330f729Sjoerg 
6317330f729Sjoerg // If (E) is non-trivial, then add it to the current basic block, and
6327330f729Sjoerg // update the statement map so that S refers to E.  Returns a new variable
6337330f729Sjoerg // that refers to E.
6347330f729Sjoerg // If E is trivial returns E.
addStatement(til::SExpr * E,const Stmt * S,const ValueDecl * VD)6357330f729Sjoerg til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
6367330f729Sjoerg                                        const ValueDecl *VD) {
6377330f729Sjoerg   if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))
6387330f729Sjoerg     return E;
6397330f729Sjoerg   if (VD)
6407330f729Sjoerg     E = new (Arena) til::Variable(E, VD);
6417330f729Sjoerg   CurrentInstructions.push_back(E);
6427330f729Sjoerg   if (S)
6437330f729Sjoerg     insertStmt(S, E);
6447330f729Sjoerg   return E;
6457330f729Sjoerg }
6467330f729Sjoerg 
6477330f729Sjoerg // Returns the current value of VD, if known, and nullptr otherwise.
lookupVarDecl(const ValueDecl * VD)6487330f729Sjoerg til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
6497330f729Sjoerg   auto It = LVarIdxMap.find(VD);
6507330f729Sjoerg   if (It != LVarIdxMap.end()) {
6517330f729Sjoerg     assert(CurrentLVarMap[It->second].first == VD);
6527330f729Sjoerg     return CurrentLVarMap[It->second].second;
6537330f729Sjoerg   }
6547330f729Sjoerg   return nullptr;
6557330f729Sjoerg }
6567330f729Sjoerg 
6577330f729Sjoerg // if E is a til::Variable, update its clangDecl.
maybeUpdateVD(til::SExpr * E,const ValueDecl * VD)6587330f729Sjoerg static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
6597330f729Sjoerg   if (!E)
6607330f729Sjoerg     return;
6617330f729Sjoerg   if (auto *V = dyn_cast<til::Variable>(E)) {
6627330f729Sjoerg     if (!V->clangDecl())
6637330f729Sjoerg       V->setClangDecl(VD);
6647330f729Sjoerg   }
6657330f729Sjoerg }
6667330f729Sjoerg 
6677330f729Sjoerg // Adds a new variable declaration.
addVarDecl(const ValueDecl * VD,til::SExpr * E)6687330f729Sjoerg til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
6697330f729Sjoerg   maybeUpdateVD(E, VD);
6707330f729Sjoerg   LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
6717330f729Sjoerg   CurrentLVarMap.makeWritable();
6727330f729Sjoerg   CurrentLVarMap.push_back(std::make_pair(VD, E));
6737330f729Sjoerg   return E;
6747330f729Sjoerg }
6757330f729Sjoerg 
6767330f729Sjoerg // Updates a current variable declaration.  (E.g. by assignment)
updateVarDecl(const ValueDecl * VD,til::SExpr * E)6777330f729Sjoerg til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
6787330f729Sjoerg   maybeUpdateVD(E, VD);
6797330f729Sjoerg   auto It = LVarIdxMap.find(VD);
6807330f729Sjoerg   if (It == LVarIdxMap.end()) {
6817330f729Sjoerg     til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
6827330f729Sjoerg     til::SExpr *St  = new (Arena) til::Store(Ptr, E);
6837330f729Sjoerg     return St;
6847330f729Sjoerg   }
6857330f729Sjoerg   CurrentLVarMap.makeWritable();
6867330f729Sjoerg   CurrentLVarMap.elem(It->second).second = E;
6877330f729Sjoerg   return E;
6887330f729Sjoerg }
6897330f729Sjoerg 
6907330f729Sjoerg // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
6917330f729Sjoerg // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
6927330f729Sjoerg // If E == null, this is a backedge and will be set later.
makePhiNodeVar(unsigned i,unsigned NPreds,til::SExpr * E)6937330f729Sjoerg void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
6947330f729Sjoerg   unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
6957330f729Sjoerg   assert(ArgIndex > 0 && ArgIndex < NPreds);
6967330f729Sjoerg 
6977330f729Sjoerg   til::SExpr *CurrE = CurrentLVarMap[i].second;
6987330f729Sjoerg   if (CurrE->block() == CurrentBB) {
6997330f729Sjoerg     // We already have a Phi node in the current block,
7007330f729Sjoerg     // so just add the new variable to the Phi node.
7017330f729Sjoerg     auto *Ph = dyn_cast<til::Phi>(CurrE);
7027330f729Sjoerg     assert(Ph && "Expecting Phi node.");
7037330f729Sjoerg     if (E)
7047330f729Sjoerg       Ph->values()[ArgIndex] = E;
7057330f729Sjoerg     return;
7067330f729Sjoerg   }
7077330f729Sjoerg 
7087330f729Sjoerg   // Make a new phi node: phi(..., E)
7097330f729Sjoerg   // All phi args up to the current index are set to the current value.
7107330f729Sjoerg   til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
7117330f729Sjoerg   Ph->values().setValues(NPreds, nullptr);
7127330f729Sjoerg   for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
7137330f729Sjoerg     Ph->values()[PIdx] = CurrE;
7147330f729Sjoerg   if (E)
7157330f729Sjoerg     Ph->values()[ArgIndex] = E;
7167330f729Sjoerg   Ph->setClangDecl(CurrentLVarMap[i].first);
7177330f729Sjoerg   // If E is from a back-edge, or either E or CurrE are incomplete, then
7187330f729Sjoerg   // mark this node as incomplete; we may need to remove it later.
7197330f729Sjoerg   if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE))
7207330f729Sjoerg     Ph->setStatus(til::Phi::PH_Incomplete);
7217330f729Sjoerg 
7227330f729Sjoerg   // Add Phi node to current block, and update CurrentLVarMap[i]
7237330f729Sjoerg   CurrentArguments.push_back(Ph);
7247330f729Sjoerg   if (Ph->status() == til::Phi::PH_Incomplete)
7257330f729Sjoerg     IncompleteArgs.push_back(Ph);
7267330f729Sjoerg 
7277330f729Sjoerg   CurrentLVarMap.makeWritable();
7287330f729Sjoerg   CurrentLVarMap.elem(i).second = Ph;
7297330f729Sjoerg }
7307330f729Sjoerg 
7317330f729Sjoerg // Merge values from Map into the current variable map.
7327330f729Sjoerg // This will construct Phi nodes in the current basic block as necessary.
mergeEntryMap(LVarDefinitionMap Map)7337330f729Sjoerg void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
7347330f729Sjoerg   assert(CurrentBlockInfo && "Not processing a block!");
7357330f729Sjoerg 
7367330f729Sjoerg   if (!CurrentLVarMap.valid()) {
7377330f729Sjoerg     // Steal Map, using copy-on-write.
7387330f729Sjoerg     CurrentLVarMap = std::move(Map);
7397330f729Sjoerg     return;
7407330f729Sjoerg   }
7417330f729Sjoerg   if (CurrentLVarMap.sameAs(Map))
7427330f729Sjoerg     return;  // Easy merge: maps from different predecessors are unchanged.
7437330f729Sjoerg 
7447330f729Sjoerg   unsigned NPreds = CurrentBB->numPredecessors();
7457330f729Sjoerg   unsigned ESz = CurrentLVarMap.size();
7467330f729Sjoerg   unsigned MSz = Map.size();
7477330f729Sjoerg   unsigned Sz  = std::min(ESz, MSz);
7487330f729Sjoerg 
7497330f729Sjoerg   for (unsigned i = 0; i < Sz; ++i) {
7507330f729Sjoerg     if (CurrentLVarMap[i].first != Map[i].first) {
7517330f729Sjoerg       // We've reached the end of variables in common.
7527330f729Sjoerg       CurrentLVarMap.makeWritable();
7537330f729Sjoerg       CurrentLVarMap.downsize(i);
7547330f729Sjoerg       break;
7557330f729Sjoerg     }
7567330f729Sjoerg     if (CurrentLVarMap[i].second != Map[i].second)
7577330f729Sjoerg       makePhiNodeVar(i, NPreds, Map[i].second);
7587330f729Sjoerg   }
7597330f729Sjoerg   if (ESz > MSz) {
7607330f729Sjoerg     CurrentLVarMap.makeWritable();
7617330f729Sjoerg     CurrentLVarMap.downsize(Map.size());
7627330f729Sjoerg   }
7637330f729Sjoerg }
7647330f729Sjoerg 
7657330f729Sjoerg // Merge a back edge into the current variable map.
7667330f729Sjoerg // This will create phi nodes for all variables in the variable map.
mergeEntryMapBackEdge()7677330f729Sjoerg void SExprBuilder::mergeEntryMapBackEdge() {
7687330f729Sjoerg   // We don't have definitions for variables on the backedge, because we
7697330f729Sjoerg   // haven't gotten that far in the CFG.  Thus, when encountering a back edge,
7707330f729Sjoerg   // we conservatively create Phi nodes for all variables.  Unnecessary Phi
7717330f729Sjoerg   // nodes will be marked as incomplete, and stripped out at the end.
7727330f729Sjoerg   //
7737330f729Sjoerg   // An Phi node is unnecessary if it only refers to itself and one other
7747330f729Sjoerg   // variable, e.g. x = Phi(y, y, x)  can be reduced to x = y.
7757330f729Sjoerg 
7767330f729Sjoerg   assert(CurrentBlockInfo && "Not processing a block!");
7777330f729Sjoerg 
7787330f729Sjoerg   if (CurrentBlockInfo->HasBackEdges)
7797330f729Sjoerg     return;
7807330f729Sjoerg   CurrentBlockInfo->HasBackEdges = true;
7817330f729Sjoerg 
7827330f729Sjoerg   CurrentLVarMap.makeWritable();
7837330f729Sjoerg   unsigned Sz = CurrentLVarMap.size();
7847330f729Sjoerg   unsigned NPreds = CurrentBB->numPredecessors();
7857330f729Sjoerg 
7867330f729Sjoerg   for (unsigned i = 0; i < Sz; ++i)
7877330f729Sjoerg     makePhiNodeVar(i, NPreds, nullptr);
7887330f729Sjoerg }
7897330f729Sjoerg 
7907330f729Sjoerg // Update the phi nodes that were initially created for a back edge
7917330f729Sjoerg // once the variable definitions have been computed.
7927330f729Sjoerg // I.e., merge the current variable map into the phi nodes for Blk.
mergePhiNodesBackEdge(const CFGBlock * Blk)7937330f729Sjoerg void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
7947330f729Sjoerg   til::BasicBlock *BB = lookupBlock(Blk);
7957330f729Sjoerg   unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
7967330f729Sjoerg   assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
7977330f729Sjoerg 
7987330f729Sjoerg   for (til::SExpr *PE : BB->arguments()) {
7997330f729Sjoerg     auto *Ph = dyn_cast_or_null<til::Phi>(PE);
8007330f729Sjoerg     assert(Ph && "Expecting Phi Node.");
8017330f729Sjoerg     assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
8027330f729Sjoerg 
8037330f729Sjoerg     til::SExpr *E = lookupVarDecl(Ph->clangDecl());
8047330f729Sjoerg     assert(E && "Couldn't find local variable for Phi node.");
8057330f729Sjoerg     Ph->values()[ArgIndex] = E;
8067330f729Sjoerg   }
8077330f729Sjoerg }
8087330f729Sjoerg 
enterCFG(CFG * Cfg,const NamedDecl * D,const CFGBlock * First)8097330f729Sjoerg void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D,
8107330f729Sjoerg                             const CFGBlock *First) {
8117330f729Sjoerg   // Perform initial setup operations.
8127330f729Sjoerg   unsigned NBlocks = Cfg->getNumBlockIDs();
8137330f729Sjoerg   Scfg = new (Arena) til::SCFG(Arena, NBlocks);
8147330f729Sjoerg 
8157330f729Sjoerg   // allocate all basic blocks immediately, to handle forward references.
8167330f729Sjoerg   BBInfo.resize(NBlocks);
8177330f729Sjoerg   BlockMap.resize(NBlocks, nullptr);
8187330f729Sjoerg   // create map from clang blockID to til::BasicBlocks
8197330f729Sjoerg   for (auto *B : *Cfg) {
8207330f729Sjoerg     auto *BB = new (Arena) til::BasicBlock(Arena);
8217330f729Sjoerg     BB->reserveInstructions(B->size());
8227330f729Sjoerg     BlockMap[B->getBlockID()] = BB;
8237330f729Sjoerg   }
8247330f729Sjoerg 
8257330f729Sjoerg   CurrentBB = lookupBlock(&Cfg->getEntry());
8267330f729Sjoerg   auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters()
8277330f729Sjoerg                                       : cast<FunctionDecl>(D)->parameters();
8287330f729Sjoerg   for (auto *Pm : Parms) {
8297330f729Sjoerg     QualType T = Pm->getType();
8307330f729Sjoerg     if (!T.isTrivialType(Pm->getASTContext()))
8317330f729Sjoerg       continue;
8327330f729Sjoerg 
8337330f729Sjoerg     // Add parameters to local variable map.
8347330f729Sjoerg     // FIXME: right now we emulate params with loads; that should be fixed.
8357330f729Sjoerg     til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
8367330f729Sjoerg     til::SExpr *Ld = new (Arena) til::Load(Lp);
8377330f729Sjoerg     til::SExpr *V  = addStatement(Ld, nullptr, Pm);
8387330f729Sjoerg     addVarDecl(Pm, V);
8397330f729Sjoerg   }
8407330f729Sjoerg }
8417330f729Sjoerg 
enterCFGBlock(const CFGBlock * B)8427330f729Sjoerg void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
8437330f729Sjoerg   // Initialize TIL basic block and add it to the CFG.
8447330f729Sjoerg   CurrentBB = lookupBlock(B);
8457330f729Sjoerg   CurrentBB->reservePredecessors(B->pred_size());
8467330f729Sjoerg   Scfg->add(CurrentBB);
8477330f729Sjoerg 
8487330f729Sjoerg   CurrentBlockInfo = &BBInfo[B->getBlockID()];
8497330f729Sjoerg 
8507330f729Sjoerg   // CurrentLVarMap is moved to ExitMap on block exit.
8517330f729Sjoerg   // FIXME: the entry block will hold function parameters.
8527330f729Sjoerg   // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
8537330f729Sjoerg }
8547330f729Sjoerg 
handlePredecessor(const CFGBlock * Pred)8557330f729Sjoerg void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
8567330f729Sjoerg   // Compute CurrentLVarMap on entry from ExitMaps of predecessors
8577330f729Sjoerg 
8587330f729Sjoerg   CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]);
8597330f729Sjoerg   BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
8607330f729Sjoerg   assert(PredInfo->UnprocessedSuccessors > 0);
8617330f729Sjoerg 
8627330f729Sjoerg   if (--PredInfo->UnprocessedSuccessors == 0)
8637330f729Sjoerg     mergeEntryMap(std::move(PredInfo->ExitMap));
8647330f729Sjoerg   else
8657330f729Sjoerg     mergeEntryMap(PredInfo->ExitMap.clone());
8667330f729Sjoerg 
8677330f729Sjoerg   ++CurrentBlockInfo->ProcessedPredecessors;
8687330f729Sjoerg }
8697330f729Sjoerg 
handlePredecessorBackEdge(const CFGBlock * Pred)8707330f729Sjoerg void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
8717330f729Sjoerg   mergeEntryMapBackEdge();
8727330f729Sjoerg }
8737330f729Sjoerg 
enterCFGBlockBody(const CFGBlock * B)8747330f729Sjoerg void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
8757330f729Sjoerg   // The merge*() methods have created arguments.
8767330f729Sjoerg   // Push those arguments onto the basic block.
8777330f729Sjoerg   CurrentBB->arguments().reserve(
8787330f729Sjoerg     static_cast<unsigned>(CurrentArguments.size()), Arena);
8797330f729Sjoerg   for (auto *A : CurrentArguments)
8807330f729Sjoerg     CurrentBB->addArgument(A);
8817330f729Sjoerg }
8827330f729Sjoerg 
handleStatement(const Stmt * S)8837330f729Sjoerg void SExprBuilder::handleStatement(const Stmt *S) {
8847330f729Sjoerg   til::SExpr *E = translate(S, nullptr);
8857330f729Sjoerg   addStatement(E, S);
8867330f729Sjoerg }
8877330f729Sjoerg 
handleDestructorCall(const VarDecl * VD,const CXXDestructorDecl * DD)8887330f729Sjoerg void SExprBuilder::handleDestructorCall(const VarDecl *VD,
8897330f729Sjoerg                                         const CXXDestructorDecl *DD) {
8907330f729Sjoerg   til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
8917330f729Sjoerg   til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
8927330f729Sjoerg   til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
8937330f729Sjoerg   til::SExpr *E = new (Arena) til::Call(Ap);
8947330f729Sjoerg   addStatement(E, nullptr);
8957330f729Sjoerg }
8967330f729Sjoerg 
exitCFGBlockBody(const CFGBlock * B)8977330f729Sjoerg void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
8987330f729Sjoerg   CurrentBB->instructions().reserve(
8997330f729Sjoerg     static_cast<unsigned>(CurrentInstructions.size()), Arena);
9007330f729Sjoerg   for (auto *V : CurrentInstructions)
9017330f729Sjoerg     CurrentBB->addInstruction(V);
9027330f729Sjoerg 
9037330f729Sjoerg   // Create an appropriate terminator
9047330f729Sjoerg   unsigned N = B->succ_size();
9057330f729Sjoerg   auto It = B->succ_begin();
9067330f729Sjoerg   if (N == 1) {
9077330f729Sjoerg     til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
9087330f729Sjoerg     // TODO: set index
9097330f729Sjoerg     unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0;
9107330f729Sjoerg     auto *Tm = new (Arena) til::Goto(BB, Idx);
9117330f729Sjoerg     CurrentBB->setTerminator(Tm);
9127330f729Sjoerg   }
9137330f729Sjoerg   else if (N == 2) {
9147330f729Sjoerg     til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr);
9157330f729Sjoerg     til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
9167330f729Sjoerg     ++It;
9177330f729Sjoerg     til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
9187330f729Sjoerg     // FIXME: make sure these aren't critical edges.
9197330f729Sjoerg     auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
9207330f729Sjoerg     CurrentBB->setTerminator(Tm);
9217330f729Sjoerg   }
9227330f729Sjoerg }
9237330f729Sjoerg 
handleSuccessor(const CFGBlock * Succ)9247330f729Sjoerg void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
9257330f729Sjoerg   ++CurrentBlockInfo->UnprocessedSuccessors;
9267330f729Sjoerg }
9277330f729Sjoerg 
handleSuccessorBackEdge(const CFGBlock * Succ)9287330f729Sjoerg void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
9297330f729Sjoerg   mergePhiNodesBackEdge(Succ);
9307330f729Sjoerg   ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
9317330f729Sjoerg }
9327330f729Sjoerg 
exitCFGBlock(const CFGBlock * B)9337330f729Sjoerg void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
9347330f729Sjoerg   CurrentArguments.clear();
9357330f729Sjoerg   CurrentInstructions.clear();
9367330f729Sjoerg   CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
9377330f729Sjoerg   CurrentBB = nullptr;
9387330f729Sjoerg   CurrentBlockInfo = nullptr;
9397330f729Sjoerg }
9407330f729Sjoerg 
exitCFG(const CFGBlock * Last)9417330f729Sjoerg void SExprBuilder::exitCFG(const CFGBlock *Last) {
9427330f729Sjoerg   for (auto *Ph : IncompleteArgs) {
9437330f729Sjoerg     if (Ph->status() == til::Phi::PH_Incomplete)
9447330f729Sjoerg       simplifyIncompleteArg(Ph);
9457330f729Sjoerg   }
9467330f729Sjoerg 
9477330f729Sjoerg   CurrentArguments.clear();
9487330f729Sjoerg   CurrentInstructions.clear();
9497330f729Sjoerg   IncompleteArgs.clear();
9507330f729Sjoerg }
9517330f729Sjoerg 
9527330f729Sjoerg /*
9537330f729Sjoerg namespace {
9547330f729Sjoerg 
9557330f729Sjoerg class TILPrinter :
9567330f729Sjoerg     public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
9577330f729Sjoerg 
9587330f729Sjoerg } // namespace
9597330f729Sjoerg 
9607330f729Sjoerg namespace clang {
9617330f729Sjoerg namespace threadSafety {
9627330f729Sjoerg 
9637330f729Sjoerg void printSCFG(CFGWalker &Walker) {
9647330f729Sjoerg   llvm::BumpPtrAllocator Bpa;
9657330f729Sjoerg   til::MemRegionRef Arena(&Bpa);
9667330f729Sjoerg   SExprBuilder SxBuilder(Arena);
9677330f729Sjoerg   til::SCFG *Scfg = SxBuilder.buildCFG(Walker);
9687330f729Sjoerg   TILPrinter::print(Scfg, llvm::errs());
9697330f729Sjoerg }
9707330f729Sjoerg 
9717330f729Sjoerg } // namespace threadSafety
9727330f729Sjoerg } // namespace clang
9737330f729Sjoerg */
974