ThreadSafetyCommon.cpp 32 KB

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