123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805 |
- //===- ThreadSafetyCommon.cpp ----------------------------------*- C++ --*-===//
- //
- // The LLVM Compiler Infrastructure
- //
- // This file is distributed under the University of Illinois Open Source
- // License. See LICENSE.TXT for details.
- //
- //===----------------------------------------------------------------------===//
- //
- // Implementation of the interfaces declared in ThreadSafetyCommon.h
- //
- //===----------------------------------------------------------------------===//
- #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
- #include "clang/AST/Attr.h"
- #include "clang/AST/DeclCXX.h"
- #include "clang/AST/ExprCXX.h"
- #include "clang/AST/StmtCXX.h"
- #include "clang/Analysis/Analyses/PostOrderCFGView.h"
- #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
- #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
- #include "clang/Analysis/AnalysisContext.h"
- #include "clang/Analysis/CFG.h"
- #include "clang/Basic/OperatorKinds.h"
- #include "clang/Basic/SourceLocation.h"
- #include "clang/Basic/SourceManager.h"
- #include "llvm/ADT/DenseMap.h"
- #include "llvm/ADT/SmallVector.h"
- #include "llvm/ADT/StringRef.h"
- #include <algorithm>
- #include <climits>
- #include <vector>
- namespace clang {
- namespace threadSafety {
- namespace til {
- // If E is a variable, then trace back through any aliases or redundant
- // Phi nodes to find the canonical definition.
- SExpr *getCanonicalVal(SExpr *E) {
- while (auto *V = dyn_cast<Variable>(E)) {
- SExpr *D;
- do {
- if (V->kind() != Variable::VK_Let)
- return V;
- D = V->definition();
- auto *V2 = dyn_cast<Variable>(D);
- if (V2)
- V = V2;
- else
- break;
- } while (true);
- if (ThreadSafetyTIL::isTrivial(D))
- return D;
- if (Phi *Ph = dyn_cast<Phi>(D)) {
- if (Ph->status() == Phi::PH_Incomplete)
- simplifyIncompleteArg(V, Ph);
- if (Ph->status() == Phi::PH_SingleVal) {
- E = Ph->values()[0];
- continue;
- }
- }
- return V;
- }
- return E;
- }
- // Trace the arguments of an incomplete Phi node to see if they have the same
- // canonical definition. If so, mark the Phi node as redundant.
- // getCanonicalVal() will recursively call simplifyIncompletePhi().
- void simplifyIncompleteArg(Variable *V, til::Phi *Ph) {
- assert(Ph && Ph->status() == Phi::PH_Incomplete);
- // eliminate infinite recursion -- assume that this node is not redundant.
- Ph->setStatus(Phi::PH_MultiVal);
- SExpr *E0 = getCanonicalVal(Ph->values()[0]);
- for (unsigned i=1, n=Ph->values().size(); i<n; ++i) {
- SExpr *Ei = getCanonicalVal(Ph->values()[i]);
- if (Ei == V)
- continue; // Recursive reference to itself. Don't count.
- if (Ei != E0) {
- return; // Status is already set to MultiVal.
- }
- }
- Ph->setStatus(Phi::PH_SingleVal);
- // Eliminate Redundant Phi node.
- V->setDefinition(Ph->values()[0]);
- }
- // Return true if E is a variable that points to an incomplete Phi node.
- inline bool isIncompleteVar(SExpr *E) {
- if (Variable *V = dyn_cast<Variable>(E)) {
- if (Phi *Ph = dyn_cast<Phi>(V->definition()))
- return Ph->status() == Phi::PH_Incomplete;
- }
- return false;
- }
- } // end namespace til
- typedef SExprBuilder::CallingContext CallingContext;
- til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
- auto It = SMap.find(S);
- if (It != SMap.end())
- return It->second;
- return nullptr;
- }
- til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
- Walker.walk(*this);
- return Scfg;
- }
- // Translate a clang statement or expression to a TIL expression.
- // Also performs substitution of variables; Ctx provides the context.
- // Dispatches on the type of S.
- til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
- if (!S)
- return nullptr;
- // Check if S has already been translated and cached.
- // This handles the lookup of SSA names for DeclRefExprs here.
- if (til::SExpr *E = lookupStmt(S))
- return E;
- switch (S->getStmtClass()) {
- case Stmt::DeclRefExprClass:
- return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
- case Stmt::CXXThisExprClass:
- return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
- case Stmt::MemberExprClass:
- return translateMemberExpr(cast<MemberExpr>(S), Ctx);
- case Stmt::CallExprClass:
- return translateCallExpr(cast<CallExpr>(S), Ctx);
- case Stmt::CXXMemberCallExprClass:
- return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
- case Stmt::CXXOperatorCallExprClass:
- return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
- case Stmt::UnaryOperatorClass:
- return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
- case Stmt::BinaryOperatorClass:
- case Stmt::CompoundAssignOperatorClass:
- return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
- case Stmt::ArraySubscriptExprClass:
- return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
- case Stmt::ConditionalOperatorClass:
- return translateConditionalOperator(cast<ConditionalOperator>(S), Ctx);
- case Stmt::BinaryConditionalOperatorClass:
- return translateBinaryConditionalOperator(
- cast<BinaryConditionalOperator>(S), Ctx);
- // We treat these as no-ops
- case Stmt::ParenExprClass:
- return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
- case Stmt::ExprWithCleanupsClass:
- return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
- case Stmt::CXXBindTemporaryExprClass:
- return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
- // Collect all literals
- case Stmt::CharacterLiteralClass:
- case Stmt::CXXNullPtrLiteralExprClass:
- case Stmt::GNUNullExprClass:
- case Stmt::CXXBoolLiteralExprClass:
- case Stmt::FloatingLiteralClass:
- case Stmt::ImaginaryLiteralClass:
- case Stmt::IntegerLiteralClass:
- case Stmt::StringLiteralClass:
- case Stmt::ObjCStringLiteralClass:
- return new (Arena) til::Literal(cast<Expr>(S));
- case Stmt::DeclStmtClass:
- return translateDeclStmt(cast<DeclStmt>(S), Ctx);
- default:
- break;
- }
- if (const CastExpr *CE = dyn_cast<CastExpr>(S))
- return translateCastExpr(CE, Ctx);
- return new (Arena) til::Undefined(S);
- }
- til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
- CallingContext *Ctx) {
- const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
- // Function parameters require substitution and/or renaming.
- if (const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(VD)) {
- const FunctionDecl *FD =
- cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
- unsigned I = PV->getFunctionScopeIndex();
- if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) {
- // Substitute call arguments for references to function parameters
- assert(I < Ctx->NumArgs);
- return translate(Ctx->FunArgs[I], Ctx->Prev);
- }
- // Map the param back to the param of the original function declaration
- // for consistent comparisons.
- VD = FD->getParamDecl(I);
- }
- // For non-local variables, treat it as a referenced to a named object.
- return new (Arena) til::LiteralPtr(VD);
- }
- til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
- CallingContext *Ctx) {
- // Substitute for 'this'
- if (Ctx && Ctx->SelfArg)
- return translate(Ctx->SelfArg, Ctx->Prev);
- assert(SelfVar && "We have no variable for 'this'!");
- return SelfVar;
- }
- til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
- CallingContext *Ctx) {
- til::SExpr *E = translate(ME->getBase(), Ctx);
- E = new (Arena) til::SApply(E);
- return new (Arena) til::Project(E, ME->getMemberDecl());
- }
- til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
- CallingContext *Ctx) {
- // TODO -- Lock returned
- til::SExpr *E = translate(CE->getCallee(), Ctx);
- for (const auto *Arg : CE->arguments()) {
- til::SExpr *A = translate(Arg, Ctx);
- E = new (Arena) til::Apply(E, A);
- }
- return new (Arena) til::Call(E, CE);
- }
- til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
- const CXXMemberCallExpr *ME, CallingContext *Ctx) {
- return translateCallExpr(cast<CallExpr>(ME), Ctx);
- }
- til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
- const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
- return translateCallExpr(cast<CallExpr>(OCE), Ctx);
- }
- til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
- CallingContext *Ctx) {
- switch (UO->getOpcode()) {
- case UO_PostInc:
- case UO_PostDec:
- case UO_PreInc:
- case UO_PreDec:
- return new (Arena) til::Undefined(UO);
- // We treat these as no-ops
- case UO_AddrOf:
- case UO_Deref:
- case UO_Plus:
- return translate(UO->getSubExpr(), Ctx);
- case UO_Minus:
- case UO_Not:
- case UO_LNot:
- case UO_Real:
- case UO_Imag:
- case UO_Extension:
- return new (Arena)
- til::UnaryOp(UO->getOpcode(), translate(UO->getSubExpr(), Ctx));
- }
- return new (Arena) til::Undefined(UO);
- }
- til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
- const BinaryOperator *BO,
- CallingContext *Ctx) {
- const Expr *LHS = BO->getLHS();
- const Expr *RHS = BO->getRHS();
- til::SExpr *E0 = translate(LHS, Ctx);
- til::SExpr *E1 = translate(RHS, Ctx);
- const ValueDecl *VD = nullptr;
- til::SExpr *CV = nullptr;
- if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHS)) {
- VD = DRE->getDecl();
- CV = lookupVarDecl(VD);
- }
- if (Op != BO_Assign) {
- til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
- E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
- E1 = addStatement(E1, nullptr, VD);
- }
- if (VD && CV)
- return updateVarDecl(VD, E1);
- return new (Arena) til::Store(E0, E1);
- }
- til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
- CallingContext *Ctx) {
- switch (BO->getOpcode()) {
- case BO_PtrMemD:
- case BO_PtrMemI:
- return new (Arena) til::Undefined(BO);
- case BO_Mul:
- case BO_Div:
- case BO_Rem:
- case BO_Add:
- case BO_Sub:
- case BO_Shl:
- case BO_Shr:
- case BO_LT:
- case BO_GT:
- case BO_LE:
- case BO_GE:
- case BO_EQ:
- case BO_NE:
- case BO_And:
- case BO_Xor:
- case BO_Or:
- case BO_LAnd:
- case BO_LOr:
- return new (Arena)
- til::BinaryOp(BO->getOpcode(), translate(BO->getLHS(), Ctx),
- translate(BO->getRHS(), Ctx));
- case BO_Assign: return translateBinAssign(BO_Assign, BO, Ctx);
- case BO_MulAssign: return translateBinAssign(BO_Mul, BO, Ctx);
- case BO_DivAssign: return translateBinAssign(BO_Div, BO, Ctx);
- case BO_RemAssign: return translateBinAssign(BO_Rem, BO, Ctx);
- case BO_AddAssign: return translateBinAssign(BO_Add, BO, Ctx);
- case BO_SubAssign: return translateBinAssign(BO_Sub, BO, Ctx);
- case BO_ShlAssign: return translateBinAssign(BO_Shl, BO, Ctx);
- case BO_ShrAssign: return translateBinAssign(BO_Shr, BO, Ctx);
- case BO_AndAssign: return translateBinAssign(BO_And, BO, Ctx);
- case BO_XorAssign: return translateBinAssign(BO_Xor, BO, Ctx);
- case BO_OrAssign: return translateBinAssign(BO_Or, BO, Ctx);
- case BO_Comma:
- // The clang CFG should have already processed both sides.
- return translate(BO->getRHS(), Ctx);
- }
- return new (Arena) til::Undefined(BO);
- }
- til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
- CallingContext *Ctx) {
- clang::CastKind K = CE->getCastKind();
- switch (K) {
- case CK_LValueToRValue: {
- if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
- til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
- if (E0)
- return E0;
- }
- til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
- return new (Arena) til::Load(E0);
- }
- case CK_NoOp:
- case CK_DerivedToBase:
- case CK_UncheckedDerivedToBase:
- case CK_ArrayToPointerDecay:
- case CK_FunctionToPointerDecay: {
- til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
- return E0;
- }
- default: {
- til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
- return new (Arena) til::Cast(K, E0);
- }
- }
- }
- til::SExpr *
- SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
- CallingContext *Ctx) {
- return new (Arena) til::Undefined(E);
- }
- til::SExpr *
- SExprBuilder::translateConditionalOperator(const ConditionalOperator *C,
- CallingContext *Ctx) {
- return new (Arena) til::Undefined(C);
- }
- til::SExpr *SExprBuilder::translateBinaryConditionalOperator(
- const BinaryConditionalOperator *C, CallingContext *Ctx) {
- return new (Arena) til::Undefined(C);
- }
- til::SExpr *
- SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
- DeclGroupRef DGrp = S->getDeclGroup();
- for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
- if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
- Expr *E = VD->getInit();
- til::SExpr* SE = translate(E, Ctx);
- // Add local variables with trivial type to the variable map
- QualType T = VD->getType();
- if (T.isTrivialType(VD->getASTContext())) {
- return addVarDecl(VD, SE);
- }
- else {
- // TODO: add alloca
- }
- }
- }
- return nullptr;
- }
- // If (E) is non-trivial, then add it to the current basic block, and
- // update the statement map so that S refers to E. Returns a new variable
- // that refers to E.
- // If E is trivial returns E.
- til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
- const ValueDecl *VD) {
- if (!E)
- return nullptr;
- if (til::ThreadSafetyTIL::isTrivial(E))
- return E;
- til::Variable *V = new (Arena) til::Variable(E, VD);
- CurrentInstructions.push_back(V);
- if (S)
- insertStmt(S, V);
- return V;
- }
- // Returns the current value of VD, if known, and nullptr otherwise.
- til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
- auto It = LVarIdxMap.find(VD);
- if (It != LVarIdxMap.end()) {
- assert(CurrentLVarMap[It->second].first == VD);
- return CurrentLVarMap[It->second].second;
- }
- return nullptr;
- }
- // if E is a til::Variable, update its clangDecl.
- inline void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
- if (!E)
- return;
- if (til::Variable *V = dyn_cast<til::Variable>(E)) {
- if (!V->clangDecl())
- V->setClangDecl(VD);
- }
- }
- // Adds a new variable declaration.
- til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
- maybeUpdateVD(E, VD);
- LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
- CurrentLVarMap.makeWritable();
- CurrentLVarMap.push_back(std::make_pair(VD, E));
- return E;
- }
- // Updates a current variable declaration. (E.g. by assignment)
- til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
- maybeUpdateVD(E, VD);
- auto It = LVarIdxMap.find(VD);
- if (It == LVarIdxMap.end()) {
- til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
- til::SExpr *St = new (Arena) til::Store(Ptr, E);
- return St;
- }
- CurrentLVarMap.makeWritable();
- CurrentLVarMap.elem(It->second).second = E;
- return E;
- }
- // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
- // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
- // If E == null, this is a backedge and will be set later.
- void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
- unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
- assert(ArgIndex > 0 && ArgIndex < NPreds);
- til::Variable *V = dyn_cast<til::Variable>(CurrentLVarMap[i].second);
- if (V && V->getBlockID() == CurrentBB->blockID()) {
- // We already have a Phi node in the current block,
- // so just add the new variable to the Phi node.
- til::Phi *Ph = dyn_cast<til::Phi>(V->definition());
- assert(Ph && "Expecting Phi node.");
- if (E)
- Ph->values()[ArgIndex] = E;
- return;
- }
- // Make a new phi node: phi(..., E)
- // All phi args up to the current index are set to the current value.
- til::SExpr *CurrE = CurrentLVarMap[i].second;
- til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
- Ph->values().setValues(NPreds, nullptr);
- for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
- Ph->values()[PIdx] = CurrE;
- if (E)
- Ph->values()[ArgIndex] = E;
- // If E is from a back-edge, or either E or CurrE are incomplete, then
- // mark this node as incomplete; we may need to remove it later.
- if (!E || isIncompleteVar(E) || isIncompleteVar(CurrE)) {
- Ph->setStatus(til::Phi::PH_Incomplete);
- }
- // Add Phi node to current block, and update CurrentLVarMap[i]
- auto *Var = new (Arena) til::Variable(Ph, CurrentLVarMap[i].first);
- CurrentArguments.push_back(Var);
- if (Ph->status() == til::Phi::PH_Incomplete)
- IncompleteArgs.push_back(Var);
- CurrentLVarMap.makeWritable();
- CurrentLVarMap.elem(i).second = Var;
- }
- // Merge values from Map into the current variable map.
- // This will construct Phi nodes in the current basic block as necessary.
- void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
- assert(CurrentBlockInfo && "Not processing a block!");
- if (!CurrentLVarMap.valid()) {
- // Steal Map, using copy-on-write.
- CurrentLVarMap = std::move(Map);
- return;
- }
- if (CurrentLVarMap.sameAs(Map))
- return; // Easy merge: maps from different predecessors are unchanged.
- unsigned NPreds = CurrentBB->numPredecessors();
- unsigned ESz = CurrentLVarMap.size();
- unsigned MSz = Map.size();
- unsigned Sz = std::min(ESz, MSz);
- for (unsigned i=0; i<Sz; ++i) {
- if (CurrentLVarMap[i].first != Map[i].first) {
- // We've reached the end of variables in common.
- CurrentLVarMap.makeWritable();
- CurrentLVarMap.downsize(i);
- break;
- }
- if (CurrentLVarMap[i].second != Map[i].second)
- makePhiNodeVar(i, NPreds, Map[i].second);
- }
- if (ESz > MSz) {
- CurrentLVarMap.makeWritable();
- CurrentLVarMap.downsize(Map.size());
- }
- }
- // Merge a back edge into the current variable map.
- // This will create phi nodes for all variables in the variable map.
- void SExprBuilder::mergeEntryMapBackEdge() {
- // We don't have definitions for variables on the backedge, because we
- // haven't gotten that far in the CFG. Thus, when encountering a back edge,
- // we conservatively create Phi nodes for all variables. Unnecessary Phi
- // nodes will be marked as incomplete, and stripped out at the end.
- //
- // An Phi node is unnecessary if it only refers to itself and one other
- // variable, e.g. x = Phi(y, y, x) can be reduced to x = y.
- assert(CurrentBlockInfo && "Not processing a block!");
- if (CurrentBlockInfo->HasBackEdges)
- return;
- CurrentBlockInfo->HasBackEdges = true;
- CurrentLVarMap.makeWritable();
- unsigned Sz = CurrentLVarMap.size();
- unsigned NPreds = CurrentBB->numPredecessors();
- for (unsigned i=0; i < Sz; ++i) {
- makePhiNodeVar(i, NPreds, nullptr);
- }
- }
- // Update the phi nodes that were initially created for a back edge
- // once the variable definitions have been computed.
- // I.e., merge the current variable map into the phi nodes for Blk.
- void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
- til::BasicBlock *BB = lookupBlock(Blk);
- unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
- assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
- for (til::Variable *V : BB->arguments()) {
- til::Phi *Ph = dyn_cast_or_null<til::Phi>(V->definition());
- assert(Ph && "Expecting Phi Node.");
- assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
- assert(V->clangDecl() && "No local variable for Phi node.");
- til::SExpr *E = lookupVarDecl(V->clangDecl());
- assert(E && "Couldn't find local variable for Phi node.");
- Ph->values()[ArgIndex] = E;
- }
- }
- void SExprBuilder::enterCFG(CFG *Cfg, const FunctionDecl *FD,
- const CFGBlock *First) {
- // Perform initial setup operations.
- unsigned NBlocks = Cfg->getNumBlockIDs();
- Scfg = new (Arena) til::SCFG(Arena, NBlocks);
- // allocate all basic blocks immediately, to handle forward references.
- BBInfo.resize(NBlocks);
- BlockMap.resize(NBlocks, nullptr);
- // create map from clang blockID to til::BasicBlocks
- for (auto *B : *Cfg) {
- auto *BB = new (Arena) til::BasicBlock(Arena, 0, B->size());
- BlockMap[B->getBlockID()] = BB;
- }
- CallCtx = new SExprBuilder::CallingContext(FD);
- CurrentBB = lookupBlock(&Cfg->getEntry());
- for (auto *Pm : FD->parameters()) {
- QualType T = Pm->getType();
- if (!T.isTrivialType(Pm->getASTContext()))
- continue;
- // Add parameters to local variable map.
- // FIXME: right now we emulate params with loads; that should be fixed.
- til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
- til::SExpr *Ld = new (Arena) til::Load(Lp);
- til::SExpr *V = addStatement(Ld, nullptr, Pm);
- addVarDecl(Pm, V);
- }
- }
- void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
- // Intialize TIL basic block and add it to the CFG.
- CurrentBB = lookupBlock(B);
- CurrentBB->setNumPredecessors(B->pred_size());
- Scfg->add(CurrentBB);
- CurrentBlockInfo = &BBInfo[B->getBlockID()];
- // CurrentLVarMap is moved to ExitMap on block exit.
- // FIXME: the entry block will hold function parameters.
- // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
- }
- void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
- // Compute CurrentLVarMap on entry from ExitMaps of predecessors
- BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
- assert(PredInfo->UnprocessedSuccessors > 0);
- if (--PredInfo->UnprocessedSuccessors == 0)
- mergeEntryMap(std::move(PredInfo->ExitMap));
- else
- mergeEntryMap(PredInfo->ExitMap.clone());
- ++CurrentBlockInfo->ProcessedPredecessors;
- }
- void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
- mergeEntryMapBackEdge();
- }
- void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
- // The merge*() methods have created arguments.
- // Push those arguments onto the basic block.
- CurrentBB->arguments().reserve(
- static_cast<unsigned>(CurrentArguments.size()), Arena);
- for (auto *V : CurrentArguments)
- CurrentBB->addArgument(V);
- }
- void SExprBuilder::handleStatement(const Stmt *S) {
- til::SExpr *E = translate(S, CallCtx);
- addStatement(E, S);
- }
- void SExprBuilder::handleDestructorCall(const VarDecl *VD,
- const CXXDestructorDecl *DD) {
- til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
- til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
- til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
- til::SExpr *E = new (Arena) til::Call(Ap);
- addStatement(E, nullptr);
- }
- void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
- CurrentBB->instructions().reserve(
- static_cast<unsigned>(CurrentInstructions.size()), Arena);
- for (auto *V : CurrentInstructions)
- CurrentBB->addInstruction(V);
- // Create an appropriate terminator
- unsigned N = B->succ_size();
- auto It = B->succ_begin();
- if (N == 1) {
- til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
- // TODO: set index
- til::SExpr *Tm = new (Arena) til::Goto(BB, 0);
- CurrentBB->setTerminator(Tm);
- }
- else if (N == 2) {
- til::SExpr *C = translate(B->getTerminatorCondition(true), CallCtx);
- til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
- ++It;
- til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
- // TODO: set conditional, set index
- til::SExpr *Tm = new (Arena) til::Branch(C, BB1, BB2);
- CurrentBB->setTerminator(Tm);
- }
- }
- void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
- ++CurrentBlockInfo->UnprocessedSuccessors;
- }
- void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
- mergePhiNodesBackEdge(Succ);
- ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
- }
- void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
- CurrentArguments.clear();
- CurrentInstructions.clear();
- CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
- CurrentBB = nullptr;
- CurrentBlockInfo = nullptr;
- }
- void SExprBuilder::exitCFG(const CFGBlock *Last) {
- for (auto *V : IncompleteArgs) {
- til::Phi *Ph = dyn_cast<til::Phi>(V->definition());
- if (Ph && Ph->status() == til::Phi::PH_Incomplete)
- simplifyIncompleteArg(V, Ph);
- }
- CurrentArguments.clear();
- CurrentInstructions.clear();
- IncompleteArgs.clear();
- }
- class LLVMPrinter : public til::PrettyPrinter<LLVMPrinter, llvm::raw_ostream> {
- };
- void printSCFG(CFGWalker &Walker) {
- llvm::BumpPtrAllocator Bpa;
- til::MemRegionRef Arena(&Bpa);
- SExprBuilder builder(Arena);
- til::SCFG *Cfg = builder.buildCFG(Walker);
- LLVMPrinter::print(Cfg, llvm::errs());
- }
- } // end namespace threadSafety
- } // end namespace clang
|