ThreadSafetyCommon.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. //===- ThreadSafetyCommon.cpp ----------------------------------*- C++ --*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Implementation of the interfaces declared in ThreadSafetyCommon.h
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
  14. #include "clang/AST/Attr.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/StmtCXX.h"
  18. #include "clang/Analysis/Analyses/PostOrderCFGView.h"
  19. #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
  20. #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
  21. #include "clang/Analysis/AnalysisContext.h"
  22. #include "clang/Analysis/CFG.h"
  23. #include "clang/Basic/OperatorKinds.h"
  24. #include "clang/Basic/SourceLocation.h"
  25. #include "clang/Basic/SourceManager.h"
  26. #include "llvm/ADT/DenseMap.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/StringRef.h"
  29. #include <algorithm>
  30. #include <climits>
  31. #include <vector>
  32. namespace clang {
  33. namespace threadSafety {
  34. namespace til {
  35. // If E is a variable, then trace back through any aliases or redundant
  36. // Phi nodes to find the canonical definition.
  37. SExpr *getCanonicalVal(SExpr *E) {
  38. while (auto *V = dyn_cast<Variable>(E)) {
  39. SExpr *D;
  40. do {
  41. if (V->kind() != Variable::VK_Let)
  42. return V;
  43. D = V->definition();
  44. auto *V2 = dyn_cast<Variable>(D);
  45. if (V2)
  46. V = V2;
  47. else
  48. break;
  49. } while (true);
  50. if (ThreadSafetyTIL::isTrivial(D))
  51. return D;
  52. if (Phi *Ph = dyn_cast<Phi>(D)) {
  53. if (Ph->status() == Phi::PH_Incomplete)
  54. simplifyIncompleteArg(V, Ph);
  55. if (Ph->status() == Phi::PH_SingleVal) {
  56. E = Ph->values()[0];
  57. continue;
  58. }
  59. }
  60. return V;
  61. }
  62. return E;
  63. }
  64. // Trace the arguments of an incomplete Phi node to see if they have the same
  65. // canonical definition. If so, mark the Phi node as redundant.
  66. // getCanonicalVal() will recursively call simplifyIncompletePhi().
  67. void simplifyIncompleteArg(Variable *V, til::Phi *Ph) {
  68. assert(Ph && Ph->status() == Phi::PH_Incomplete);
  69. // eliminate infinite recursion -- assume that this node is not redundant.
  70. Ph->setStatus(Phi::PH_MultiVal);
  71. SExpr *E0 = getCanonicalVal(Ph->values()[0]);
  72. for (unsigned i=1, n=Ph->values().size(); i<n; ++i) {
  73. SExpr *Ei = getCanonicalVal(Ph->values()[i]);
  74. if (Ei == V)
  75. continue; // Recursive reference to itself. Don't count.
  76. if (Ei != E0) {
  77. return; // Status is already set to MultiVal.
  78. }
  79. }
  80. Ph->setStatus(Phi::PH_SingleVal);
  81. // Eliminate Redundant Phi node.
  82. V->setDefinition(Ph->values()[0]);
  83. }
  84. // Return true if E is a variable that points to an incomplete Phi node.
  85. inline bool isIncompleteVar(SExpr *E) {
  86. if (Variable *V = dyn_cast<Variable>(E)) {
  87. if (Phi *Ph = dyn_cast<Phi>(V->definition()))
  88. return Ph->status() == Phi::PH_Incomplete;
  89. }
  90. return false;
  91. }
  92. } // end namespace til
  93. typedef SExprBuilder::CallingContext CallingContext;
  94. til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
  95. auto It = SMap.find(S);
  96. if (It != SMap.end())
  97. return It->second;
  98. return nullptr;
  99. }
  100. til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
  101. Walker.walk(*this);
  102. return Scfg;
  103. }
  104. // Translate a clang statement or expression to a TIL expression.
  105. // Also performs substitution of variables; Ctx provides the context.
  106. // Dispatches on the type of S.
  107. til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
  108. if (!S)
  109. return nullptr;
  110. // Check if S has already been translated and cached.
  111. // This handles the lookup of SSA names for DeclRefExprs here.
  112. if (til::SExpr *E = lookupStmt(S))
  113. return E;
  114. switch (S->getStmtClass()) {
  115. case Stmt::DeclRefExprClass:
  116. return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
  117. case Stmt::CXXThisExprClass:
  118. return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
  119. case Stmt::MemberExprClass:
  120. return translateMemberExpr(cast<MemberExpr>(S), Ctx);
  121. case Stmt::CallExprClass:
  122. return translateCallExpr(cast<CallExpr>(S), Ctx);
  123. case Stmt::CXXMemberCallExprClass:
  124. return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
  125. case Stmt::CXXOperatorCallExprClass:
  126. return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
  127. case Stmt::UnaryOperatorClass:
  128. return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
  129. case Stmt::BinaryOperatorClass:
  130. case Stmt::CompoundAssignOperatorClass:
  131. return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
  132. case Stmt::ArraySubscriptExprClass:
  133. return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
  134. case Stmt::ConditionalOperatorClass:
  135. return translateConditionalOperator(cast<ConditionalOperator>(S), Ctx);
  136. case Stmt::BinaryConditionalOperatorClass:
  137. return translateBinaryConditionalOperator(
  138. cast<BinaryConditionalOperator>(S), Ctx);
  139. // We treat these as no-ops
  140. case Stmt::ParenExprClass:
  141. return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
  142. case Stmt::ExprWithCleanupsClass:
  143. return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
  144. case Stmt::CXXBindTemporaryExprClass:
  145. return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
  146. // Collect all literals
  147. case Stmt::CharacterLiteralClass:
  148. case Stmt::CXXNullPtrLiteralExprClass:
  149. case Stmt::GNUNullExprClass:
  150. case Stmt::CXXBoolLiteralExprClass:
  151. case Stmt::FloatingLiteralClass:
  152. case Stmt::ImaginaryLiteralClass:
  153. case Stmt::IntegerLiteralClass:
  154. case Stmt::StringLiteralClass:
  155. case Stmt::ObjCStringLiteralClass:
  156. return new (Arena) til::Literal(cast<Expr>(S));
  157. case Stmt::DeclStmtClass:
  158. return translateDeclStmt(cast<DeclStmt>(S), Ctx);
  159. default:
  160. break;
  161. }
  162. if (const CastExpr *CE = dyn_cast<CastExpr>(S))
  163. return translateCastExpr(CE, Ctx);
  164. return new (Arena) til::Undefined(S);
  165. }
  166. til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
  167. CallingContext *Ctx) {
  168. const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
  169. // Function parameters require substitution and/or renaming.
  170. if (const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(VD)) {
  171. const FunctionDecl *FD =
  172. cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
  173. unsigned I = PV->getFunctionScopeIndex();
  174. if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) {
  175. // Substitute call arguments for references to function parameters
  176. assert(I < Ctx->NumArgs);
  177. return translate(Ctx->FunArgs[I], Ctx->Prev);
  178. }
  179. // Map the param back to the param of the original function declaration
  180. // for consistent comparisons.
  181. VD = FD->getParamDecl(I);
  182. }
  183. // For non-local variables, treat it as a referenced to a named object.
  184. return new (Arena) til::LiteralPtr(VD);
  185. }
  186. til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
  187. CallingContext *Ctx) {
  188. // Substitute for 'this'
  189. if (Ctx && Ctx->SelfArg)
  190. return translate(Ctx->SelfArg, Ctx->Prev);
  191. assert(SelfVar && "We have no variable for 'this'!");
  192. return SelfVar;
  193. }
  194. til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
  195. CallingContext *Ctx) {
  196. til::SExpr *E = translate(ME->getBase(), Ctx);
  197. E = new (Arena) til::SApply(E);
  198. return new (Arena) til::Project(E, ME->getMemberDecl());
  199. }
  200. til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
  201. CallingContext *Ctx) {
  202. // TODO -- Lock returned
  203. til::SExpr *E = translate(CE->getCallee(), Ctx);
  204. for (const auto *Arg : CE->arguments()) {
  205. til::SExpr *A = translate(Arg, Ctx);
  206. E = new (Arena) til::Apply(E, A);
  207. }
  208. return new (Arena) til::Call(E, CE);
  209. }
  210. til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
  211. const CXXMemberCallExpr *ME, CallingContext *Ctx) {
  212. return translateCallExpr(cast<CallExpr>(ME), Ctx);
  213. }
  214. til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
  215. const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
  216. return translateCallExpr(cast<CallExpr>(OCE), Ctx);
  217. }
  218. til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
  219. CallingContext *Ctx) {
  220. switch (UO->getOpcode()) {
  221. case UO_PostInc:
  222. case UO_PostDec:
  223. case UO_PreInc:
  224. case UO_PreDec:
  225. return new (Arena) til::Undefined(UO);
  226. // We treat these as no-ops
  227. case UO_AddrOf:
  228. case UO_Deref:
  229. case UO_Plus:
  230. return translate(UO->getSubExpr(), Ctx);
  231. case UO_Minus:
  232. case UO_Not:
  233. case UO_LNot:
  234. case UO_Real:
  235. case UO_Imag:
  236. case UO_Extension:
  237. return new (Arena)
  238. til::UnaryOp(UO->getOpcode(), translate(UO->getSubExpr(), Ctx));
  239. }
  240. return new (Arena) til::Undefined(UO);
  241. }
  242. til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
  243. const BinaryOperator *BO,
  244. CallingContext *Ctx) {
  245. const Expr *LHS = BO->getLHS();
  246. const Expr *RHS = BO->getRHS();
  247. til::SExpr *E0 = translate(LHS, Ctx);
  248. til::SExpr *E1 = translate(RHS, Ctx);
  249. const ValueDecl *VD = nullptr;
  250. til::SExpr *CV = nullptr;
  251. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  252. VD = DRE->getDecl();
  253. CV = lookupVarDecl(VD);
  254. }
  255. if (Op != BO_Assign) {
  256. til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
  257. E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
  258. E1 = addStatement(E1, nullptr, VD);
  259. }
  260. if (VD && CV)
  261. return updateVarDecl(VD, E1);
  262. return new (Arena) til::Store(E0, E1);
  263. }
  264. til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
  265. CallingContext *Ctx) {
  266. switch (BO->getOpcode()) {
  267. case BO_PtrMemD:
  268. case BO_PtrMemI:
  269. return new (Arena) til::Undefined(BO);
  270. case BO_Mul:
  271. case BO_Div:
  272. case BO_Rem:
  273. case BO_Add:
  274. case BO_Sub:
  275. case BO_Shl:
  276. case BO_Shr:
  277. case BO_LT:
  278. case BO_GT:
  279. case BO_LE:
  280. case BO_GE:
  281. case BO_EQ:
  282. case BO_NE:
  283. case BO_And:
  284. case BO_Xor:
  285. case BO_Or:
  286. case BO_LAnd:
  287. case BO_LOr:
  288. return new (Arena)
  289. til::BinaryOp(BO->getOpcode(), translate(BO->getLHS(), Ctx),
  290. translate(BO->getRHS(), Ctx));
  291. case BO_Assign: return translateBinAssign(BO_Assign, BO, Ctx);
  292. case BO_MulAssign: return translateBinAssign(BO_Mul, BO, Ctx);
  293. case BO_DivAssign: return translateBinAssign(BO_Div, BO, Ctx);
  294. case BO_RemAssign: return translateBinAssign(BO_Rem, BO, Ctx);
  295. case BO_AddAssign: return translateBinAssign(BO_Add, BO, Ctx);
  296. case BO_SubAssign: return translateBinAssign(BO_Sub, BO, Ctx);
  297. case BO_ShlAssign: return translateBinAssign(BO_Shl, BO, Ctx);
  298. case BO_ShrAssign: return translateBinAssign(BO_Shr, BO, Ctx);
  299. case BO_AndAssign: return translateBinAssign(BO_And, BO, Ctx);
  300. case BO_XorAssign: return translateBinAssign(BO_Xor, BO, Ctx);
  301. case BO_OrAssign: return translateBinAssign(BO_Or, BO, Ctx);
  302. case BO_Comma:
  303. // The clang CFG should have already processed both sides.
  304. return translate(BO->getRHS(), Ctx);
  305. }
  306. return new (Arena) til::Undefined(BO);
  307. }
  308. til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
  309. CallingContext *Ctx) {
  310. clang::CastKind K = CE->getCastKind();
  311. switch (K) {
  312. case CK_LValueToRValue: {
  313. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
  314. til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
  315. if (E0)
  316. return E0;
  317. }
  318. til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
  319. return new (Arena) til::Load(E0);
  320. }
  321. case CK_NoOp:
  322. case CK_DerivedToBase:
  323. case CK_UncheckedDerivedToBase:
  324. case CK_ArrayToPointerDecay:
  325. case CK_FunctionToPointerDecay: {
  326. til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
  327. return E0;
  328. }
  329. default: {
  330. til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
  331. return new (Arena) til::Cast(K, E0);
  332. }
  333. }
  334. }
  335. til::SExpr *
  336. SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
  337. CallingContext *Ctx) {
  338. return new (Arena) til::Undefined(E);
  339. }
  340. til::SExpr *
  341. SExprBuilder::translateConditionalOperator(const ConditionalOperator *C,
  342. CallingContext *Ctx) {
  343. return new (Arena) til::Undefined(C);
  344. }
  345. til::SExpr *SExprBuilder::translateBinaryConditionalOperator(
  346. const BinaryConditionalOperator *C, CallingContext *Ctx) {
  347. return new (Arena) til::Undefined(C);
  348. }
  349. til::SExpr *
  350. SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
  351. DeclGroupRef DGrp = S->getDeclGroup();
  352. for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
  353. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
  354. Expr *E = VD->getInit();
  355. til::SExpr* SE = translate(E, Ctx);
  356. // Add local variables with trivial type to the variable map
  357. QualType T = VD->getType();
  358. if (T.isTrivialType(VD->getASTContext())) {
  359. return addVarDecl(VD, SE);
  360. }
  361. else {
  362. // TODO: add alloca
  363. }
  364. }
  365. }
  366. return nullptr;
  367. }
  368. // If (E) is non-trivial, then add it to the current basic block, and
  369. // update the statement map so that S refers to E. Returns a new variable
  370. // that refers to E.
  371. // If E is trivial returns E.
  372. til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
  373. const ValueDecl *VD) {
  374. if (!E)
  375. return nullptr;
  376. if (til::ThreadSafetyTIL::isTrivial(E))
  377. return E;
  378. til::Variable *V = new (Arena) til::Variable(E, VD);
  379. CurrentInstructions.push_back(V);
  380. if (S)
  381. insertStmt(S, V);
  382. return V;
  383. }
  384. // Returns the current value of VD, if known, and nullptr otherwise.
  385. til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
  386. auto It = LVarIdxMap.find(VD);
  387. if (It != LVarIdxMap.end()) {
  388. assert(CurrentLVarMap[It->second].first == VD);
  389. return CurrentLVarMap[It->second].second;
  390. }
  391. return nullptr;
  392. }
  393. // if E is a til::Variable, update its clangDecl.
  394. inline void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
  395. if (!E)
  396. return;
  397. if (til::Variable *V = dyn_cast<til::Variable>(E)) {
  398. if (!V->clangDecl())
  399. V->setClangDecl(VD);
  400. }
  401. }
  402. // Adds a new variable declaration.
  403. til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
  404. maybeUpdateVD(E, VD);
  405. LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
  406. CurrentLVarMap.makeWritable();
  407. CurrentLVarMap.push_back(std::make_pair(VD, E));
  408. return E;
  409. }
  410. // Updates a current variable declaration. (E.g. by assignment)
  411. til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
  412. maybeUpdateVD(E, VD);
  413. auto It = LVarIdxMap.find(VD);
  414. if (It == LVarIdxMap.end()) {
  415. til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
  416. til::SExpr *St = new (Arena) til::Store(Ptr, E);
  417. return St;
  418. }
  419. CurrentLVarMap.makeWritable();
  420. CurrentLVarMap.elem(It->second).second = E;
  421. return E;
  422. }
  423. // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
  424. // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
  425. // If E == null, this is a backedge and will be set later.
  426. void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
  427. unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
  428. assert(ArgIndex > 0 && ArgIndex < NPreds);
  429. til::Variable *V = dyn_cast<til::Variable>(CurrentLVarMap[i].second);
  430. if (V && V->getBlockID() == CurrentBB->blockID()) {
  431. // We already have a Phi node in the current block,
  432. // so just add the new variable to the Phi node.
  433. til::Phi *Ph = dyn_cast<til::Phi>(V->definition());
  434. assert(Ph && "Expecting Phi node.");
  435. if (E)
  436. Ph->values()[ArgIndex] = E;
  437. return;
  438. }
  439. // Make a new phi node: phi(..., E)
  440. // All phi args up to the current index are set to the current value.
  441. til::SExpr *CurrE = CurrentLVarMap[i].second;
  442. til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
  443. Ph->values().setValues(NPreds, nullptr);
  444. for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
  445. Ph->values()[PIdx] = CurrE;
  446. if (E)
  447. Ph->values()[ArgIndex] = E;
  448. // If E is from a back-edge, or either E or CurrE are incomplete, then
  449. // mark this node as incomplete; we may need to remove it later.
  450. if (!E || isIncompleteVar(E) || isIncompleteVar(CurrE)) {
  451. Ph->setStatus(til::Phi::PH_Incomplete);
  452. }
  453. // Add Phi node to current block, and update CurrentLVarMap[i]
  454. auto *Var = new (Arena) til::Variable(Ph, CurrentLVarMap[i].first);
  455. CurrentArguments.push_back(Var);
  456. if (Ph->status() == til::Phi::PH_Incomplete)
  457. IncompleteArgs.push_back(Var);
  458. CurrentLVarMap.makeWritable();
  459. CurrentLVarMap.elem(i).second = Var;
  460. }
  461. // Merge values from Map into the current variable map.
  462. // This will construct Phi nodes in the current basic block as necessary.
  463. void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
  464. assert(CurrentBlockInfo && "Not processing a block!");
  465. if (!CurrentLVarMap.valid()) {
  466. // Steal Map, using copy-on-write.
  467. CurrentLVarMap = std::move(Map);
  468. return;
  469. }
  470. if (CurrentLVarMap.sameAs(Map))
  471. return; // Easy merge: maps from different predecessors are unchanged.
  472. unsigned NPreds = CurrentBB->numPredecessors();
  473. unsigned ESz = CurrentLVarMap.size();
  474. unsigned MSz = Map.size();
  475. unsigned Sz = std::min(ESz, MSz);
  476. for (unsigned i=0; i<Sz; ++i) {
  477. if (CurrentLVarMap[i].first != Map[i].first) {
  478. // We've reached the end of variables in common.
  479. CurrentLVarMap.makeWritable();
  480. CurrentLVarMap.downsize(i);
  481. break;
  482. }
  483. if (CurrentLVarMap[i].second != Map[i].second)
  484. makePhiNodeVar(i, NPreds, Map[i].second);
  485. }
  486. if (ESz > MSz) {
  487. CurrentLVarMap.makeWritable();
  488. CurrentLVarMap.downsize(Map.size());
  489. }
  490. }
  491. // Merge a back edge into the current variable map.
  492. // This will create phi nodes for all variables in the variable map.
  493. void SExprBuilder::mergeEntryMapBackEdge() {
  494. // We don't have definitions for variables on the backedge, because we
  495. // haven't gotten that far in the CFG. Thus, when encountering a back edge,
  496. // we conservatively create Phi nodes for all variables. Unnecessary Phi
  497. // nodes will be marked as incomplete, and stripped out at the end.
  498. //
  499. // An Phi node is unnecessary if it only refers to itself and one other
  500. // variable, e.g. x = Phi(y, y, x) can be reduced to x = y.
  501. assert(CurrentBlockInfo && "Not processing a block!");
  502. if (CurrentBlockInfo->HasBackEdges)
  503. return;
  504. CurrentBlockInfo->HasBackEdges = true;
  505. CurrentLVarMap.makeWritable();
  506. unsigned Sz = CurrentLVarMap.size();
  507. unsigned NPreds = CurrentBB->numPredecessors();
  508. for (unsigned i=0; i < Sz; ++i) {
  509. makePhiNodeVar(i, NPreds, nullptr);
  510. }
  511. }
  512. // Update the phi nodes that were initially created for a back edge
  513. // once the variable definitions have been computed.
  514. // I.e., merge the current variable map into the phi nodes for Blk.
  515. void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
  516. til::BasicBlock *BB = lookupBlock(Blk);
  517. unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
  518. assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
  519. for (til::Variable *V : BB->arguments()) {
  520. til::Phi *Ph = dyn_cast_or_null<til::Phi>(V->definition());
  521. assert(Ph && "Expecting Phi Node.");
  522. assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
  523. assert(V->clangDecl() && "No local variable for Phi node.");
  524. til::SExpr *E = lookupVarDecl(V->clangDecl());
  525. assert(E && "Couldn't find local variable for Phi node.");
  526. Ph->values()[ArgIndex] = E;
  527. }
  528. }
  529. void SExprBuilder::enterCFG(CFG *Cfg, const FunctionDecl *FD,
  530. const CFGBlock *First) {
  531. // Perform initial setup operations.
  532. unsigned NBlocks = Cfg->getNumBlockIDs();
  533. Scfg = new (Arena) til::SCFG(Arena, NBlocks);
  534. // allocate all basic blocks immediately, to handle forward references.
  535. BBInfo.resize(NBlocks);
  536. BlockMap.resize(NBlocks, nullptr);
  537. // create map from clang blockID to til::BasicBlocks
  538. for (auto *B : *Cfg) {
  539. auto *BB = new (Arena) til::BasicBlock(Arena, 0, B->size());
  540. BlockMap[B->getBlockID()] = BB;
  541. }
  542. CallCtx = new SExprBuilder::CallingContext(FD);
  543. CurrentBB = lookupBlock(&Cfg->getEntry());
  544. for (auto *Pm : FD->parameters()) {
  545. QualType T = Pm->getType();
  546. if (!T.isTrivialType(Pm->getASTContext()))
  547. continue;
  548. // Add parameters to local variable map.
  549. // FIXME: right now we emulate params with loads; that should be fixed.
  550. til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
  551. til::SExpr *Ld = new (Arena) til::Load(Lp);
  552. til::SExpr *V = addStatement(Ld, nullptr, Pm);
  553. addVarDecl(Pm, V);
  554. }
  555. }
  556. void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
  557. // Intialize TIL basic block and add it to the CFG.
  558. CurrentBB = lookupBlock(B);
  559. CurrentBB->setNumPredecessors(B->pred_size());
  560. Scfg->add(CurrentBB);
  561. CurrentBlockInfo = &BBInfo[B->getBlockID()];
  562. // CurrentLVarMap is moved to ExitMap on block exit.
  563. // FIXME: the entry block will hold function parameters.
  564. // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
  565. }
  566. void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
  567. // Compute CurrentLVarMap on entry from ExitMaps of predecessors
  568. BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
  569. assert(PredInfo->UnprocessedSuccessors > 0);
  570. if (--PredInfo->UnprocessedSuccessors == 0)
  571. mergeEntryMap(std::move(PredInfo->ExitMap));
  572. else
  573. mergeEntryMap(PredInfo->ExitMap.clone());
  574. ++CurrentBlockInfo->ProcessedPredecessors;
  575. }
  576. void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
  577. mergeEntryMapBackEdge();
  578. }
  579. void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
  580. // The merge*() methods have created arguments.
  581. // Push those arguments onto the basic block.
  582. CurrentBB->arguments().reserve(
  583. static_cast<unsigned>(CurrentArguments.size()), Arena);
  584. for (auto *V : CurrentArguments)
  585. CurrentBB->addArgument(V);
  586. }
  587. void SExprBuilder::handleStatement(const Stmt *S) {
  588. til::SExpr *E = translate(S, CallCtx);
  589. addStatement(E, S);
  590. }
  591. void SExprBuilder::handleDestructorCall(const VarDecl *VD,
  592. const CXXDestructorDecl *DD) {
  593. til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
  594. til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
  595. til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
  596. til::SExpr *E = new (Arena) til::Call(Ap);
  597. addStatement(E, nullptr);
  598. }
  599. void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
  600. CurrentBB->instructions().reserve(
  601. static_cast<unsigned>(CurrentInstructions.size()), Arena);
  602. for (auto *V : CurrentInstructions)
  603. CurrentBB->addInstruction(V);
  604. // Create an appropriate terminator
  605. unsigned N = B->succ_size();
  606. auto It = B->succ_begin();
  607. if (N == 1) {
  608. til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
  609. // TODO: set index
  610. til::SExpr *Tm = new (Arena) til::Goto(BB, 0);
  611. CurrentBB->setTerminator(Tm);
  612. }
  613. else if (N == 2) {
  614. til::SExpr *C = translate(B->getTerminatorCondition(true), CallCtx);
  615. til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
  616. ++It;
  617. til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
  618. // TODO: set conditional, set index
  619. til::SExpr *Tm = new (Arena) til::Branch(C, BB1, BB2);
  620. CurrentBB->setTerminator(Tm);
  621. }
  622. }
  623. void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
  624. ++CurrentBlockInfo->UnprocessedSuccessors;
  625. }
  626. void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
  627. mergePhiNodesBackEdge(Succ);
  628. ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
  629. }
  630. void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
  631. CurrentArguments.clear();
  632. CurrentInstructions.clear();
  633. CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
  634. CurrentBB = nullptr;
  635. CurrentBlockInfo = nullptr;
  636. }
  637. void SExprBuilder::exitCFG(const CFGBlock *Last) {
  638. for (auto *V : IncompleteArgs) {
  639. til::Phi *Ph = dyn_cast<til::Phi>(V->definition());
  640. if (Ph && Ph->status() == til::Phi::PH_Incomplete)
  641. simplifyIncompleteArg(V, Ph);
  642. }
  643. CurrentArguments.clear();
  644. CurrentInstructions.clear();
  645. IncompleteArgs.clear();
  646. }
  647. class LLVMPrinter : public til::PrettyPrinter<LLVMPrinter, llvm::raw_ostream> {
  648. };
  649. void printSCFG(CFGWalker &Walker) {
  650. llvm::BumpPtrAllocator Bpa;
  651. til::MemRegionRef Arena(&Bpa);
  652. SExprBuilder builder(Arena);
  653. til::SCFG *Cfg = builder.buildCFG(Walker);
  654. LLVMPrinter::print(Cfg, llvm::errs());
  655. }
  656. } // end namespace threadSafety
  657. } // end namespace clang