ThreadSafety.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462
  1. //===- ThreadSafety.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. // A intra-procedural analysis for thread safety (e.g. deadlocks and race
  11. // conditions), based off of an annotation system.
  12. //
  13. // See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
  14. // information.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/Analysis/Analyses/ThreadSafety.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/Analysis/Analyses/PostOrderCFGView.h"
  24. #include "clang/Analysis/AnalysisContext.h"
  25. #include "clang/Analysis/CFG.h"
  26. #include "clang/Analysis/CFGStmtMap.h"
  27. #include "clang/Basic/OperatorKinds.h"
  28. #include "clang/Basic/SourceLocation.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "llvm/ADT/BitVector.h"
  31. #include "llvm/ADT/FoldingSet.h"
  32. #include "llvm/ADT/ImmutableMap.h"
  33. #include "llvm/ADT/PostOrderIterator.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/ADT/StringRef.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <algorithm>
  38. #include <utility>
  39. #include <vector>
  40. using namespace clang;
  41. using namespace thread_safety;
  42. // Key method definition
  43. ThreadSafetyHandler::~ThreadSafetyHandler() {}
  44. namespace {
  45. /// SExpr implements a simple expression language that is used to store,
  46. /// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
  47. /// does not capture surface syntax, and it does not distinguish between
  48. /// C++ concepts, like pointers and references, that have no real semantic
  49. /// differences. This simplicity allows SExprs to be meaningfully compared,
  50. /// e.g.
  51. /// (x) = x
  52. /// (*this).foo = this->foo
  53. /// *&a = a
  54. ///
  55. /// Thread-safety analysis works by comparing lock expressions. Within the
  56. /// body of a function, an expression such as "x->foo->bar.mu" will resolve to
  57. /// a particular mutex object at run-time. Subsequent occurrences of the same
  58. /// expression (where "same" means syntactic equality) will refer to the same
  59. /// run-time object if three conditions hold:
  60. /// (1) Local variables in the expression, such as "x" have not changed.
  61. /// (2) Values on the heap that affect the expression have not changed.
  62. /// (3) The expression involves only pure function calls.
  63. ///
  64. /// The current implementation assumes, but does not verify, that multiple uses
  65. /// of the same lock expression satisfies these criteria.
  66. class SExpr {
  67. private:
  68. enum ExprOp {
  69. EOP_Nop, ///< No-op
  70. EOP_Wildcard, ///< Matches anything.
  71. EOP_Universal, ///< Universal lock.
  72. EOP_This, ///< This keyword.
  73. EOP_NVar, ///< Named variable.
  74. EOP_LVar, ///< Local variable.
  75. EOP_Dot, ///< Field access
  76. EOP_Call, ///< Function call
  77. EOP_MCall, ///< Method call
  78. EOP_Index, ///< Array index
  79. EOP_Unary, ///< Unary operation
  80. EOP_Binary, ///< Binary operation
  81. EOP_Unknown ///< Catchall for everything else
  82. };
  83. class SExprNode {
  84. private:
  85. unsigned char Op; ///< Opcode of the root node
  86. unsigned char Flags; ///< Additional opcode-specific data
  87. unsigned short Sz; ///< Number of child nodes
  88. const void* Data; ///< Additional opcode-specific data
  89. public:
  90. SExprNode(ExprOp O, unsigned F, const void* D)
  91. : Op(static_cast<unsigned char>(O)),
  92. Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
  93. { }
  94. unsigned size() const { return Sz; }
  95. void setSize(unsigned S) { Sz = S; }
  96. ExprOp kind() const { return static_cast<ExprOp>(Op); }
  97. const NamedDecl* getNamedDecl() const {
  98. assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
  99. return reinterpret_cast<const NamedDecl*>(Data);
  100. }
  101. const NamedDecl* getFunctionDecl() const {
  102. assert(Op == EOP_Call || Op == EOP_MCall);
  103. return reinterpret_cast<const NamedDecl*>(Data);
  104. }
  105. bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
  106. void setArrow(bool A) { Flags = A ? 1 : 0; }
  107. unsigned arity() const {
  108. switch (Op) {
  109. case EOP_Nop: return 0;
  110. case EOP_Wildcard: return 0;
  111. case EOP_Universal: return 0;
  112. case EOP_NVar: return 0;
  113. case EOP_LVar: return 0;
  114. case EOP_This: return 0;
  115. case EOP_Dot: return 1;
  116. case EOP_Call: return Flags+1; // First arg is function.
  117. case EOP_MCall: return Flags+1; // First arg is implicit obj.
  118. case EOP_Index: return 2;
  119. case EOP_Unary: return 1;
  120. case EOP_Binary: return 2;
  121. case EOP_Unknown: return Flags;
  122. }
  123. return 0;
  124. }
  125. bool operator==(const SExprNode& Other) const {
  126. // Ignore flags and size -- they don't matter.
  127. return (Op == Other.Op &&
  128. Data == Other.Data);
  129. }
  130. bool operator!=(const SExprNode& Other) const {
  131. return !(*this == Other);
  132. }
  133. bool matches(const SExprNode& Other) const {
  134. return (*this == Other) ||
  135. (Op == EOP_Wildcard) ||
  136. (Other.Op == EOP_Wildcard);
  137. }
  138. };
  139. /// \brief Encapsulates the lexical context of a function call. The lexical
  140. /// context includes the arguments to the call, including the implicit object
  141. /// argument. When an attribute containing a mutex expression is attached to
  142. /// a method, the expression may refer to formal parameters of the method.
  143. /// Actual arguments must be substituted for formal parameters to derive
  144. /// the appropriate mutex expression in the lexical context where the function
  145. /// is called. PrevCtx holds the context in which the arguments themselves
  146. /// should be evaluated; multiple calling contexts can be chained together
  147. /// by the lock_returned attribute.
  148. struct CallingContext {
  149. const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
  150. Expr* SelfArg; // Implicit object argument -- e.g. 'this'
  151. bool SelfArrow; // is Self referred to with -> or .?
  152. unsigned NumArgs; // Number of funArgs
  153. Expr** FunArgs; // Function arguments
  154. CallingContext* PrevCtx; // The previous context; or 0 if none.
  155. CallingContext(const NamedDecl *D = 0, Expr *S = 0,
  156. unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
  157. : AttrDecl(D), SelfArg(S), SelfArrow(false),
  158. NumArgs(N), FunArgs(A), PrevCtx(P)
  159. { }
  160. };
  161. typedef SmallVector<SExprNode, 4> NodeVector;
  162. private:
  163. // A SExpr is a list of SExprNodes in prefix order. The Size field allows
  164. // the list to be traversed as a tree.
  165. NodeVector NodeVec;
  166. private:
  167. unsigned makeNop() {
  168. NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
  169. return NodeVec.size()-1;
  170. }
  171. unsigned makeWildcard() {
  172. NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
  173. return NodeVec.size()-1;
  174. }
  175. unsigned makeUniversal() {
  176. NodeVec.push_back(SExprNode(EOP_Universal, 0, 0));
  177. return NodeVec.size()-1;
  178. }
  179. unsigned makeNamedVar(const NamedDecl *D) {
  180. NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
  181. return NodeVec.size()-1;
  182. }
  183. unsigned makeLocalVar(const NamedDecl *D) {
  184. NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
  185. return NodeVec.size()-1;
  186. }
  187. unsigned makeThis() {
  188. NodeVec.push_back(SExprNode(EOP_This, 0, 0));
  189. return NodeVec.size()-1;
  190. }
  191. unsigned makeDot(const NamedDecl *D, bool Arrow) {
  192. NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
  193. return NodeVec.size()-1;
  194. }
  195. unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
  196. NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
  197. return NodeVec.size()-1;
  198. }
  199. // Grab the very first declaration of virtual method D
  200. const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
  201. while (true) {
  202. D = D->getCanonicalDecl();
  203. CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
  204. E = D->end_overridden_methods();
  205. if (I == E)
  206. return D; // Method does not override anything
  207. D = *I; // FIXME: this does not work with multiple inheritance.
  208. }
  209. return 0;
  210. }
  211. unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
  212. NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, getFirstVirtualDecl(D)));
  213. return NodeVec.size()-1;
  214. }
  215. unsigned makeIndex() {
  216. NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
  217. return NodeVec.size()-1;
  218. }
  219. unsigned makeUnary() {
  220. NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
  221. return NodeVec.size()-1;
  222. }
  223. unsigned makeBinary() {
  224. NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
  225. return NodeVec.size()-1;
  226. }
  227. unsigned makeUnknown(unsigned Arity) {
  228. NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
  229. return NodeVec.size()-1;
  230. }
  231. /// Build an SExpr from the given C++ expression.
  232. /// Recursive function that terminates on DeclRefExpr.
  233. /// Note: this function merely creates a SExpr; it does not check to
  234. /// ensure that the original expression is a valid mutex expression.
  235. ///
  236. /// NDeref returns the number of Derefence and AddressOf operations
  237. /// preceeding the Expr; this is used to decide whether to pretty-print
  238. /// SExprs with . or ->.
  239. unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
  240. if (!Exp)
  241. return 0;
  242. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
  243. NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  244. ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
  245. if (PV) {
  246. FunctionDecl *FD =
  247. cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
  248. unsigned i = PV->getFunctionScopeIndex();
  249. if (CallCtx && CallCtx->FunArgs &&
  250. FD == CallCtx->AttrDecl->getCanonicalDecl()) {
  251. // Substitute call arguments for references to function parameters
  252. assert(i < CallCtx->NumArgs);
  253. return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
  254. }
  255. // Map the param back to the param of the original function declaration.
  256. makeNamedVar(FD->getParamDecl(i));
  257. return 1;
  258. }
  259. // Not a function parameter -- just store the reference.
  260. makeNamedVar(ND);
  261. return 1;
  262. } else if (isa<CXXThisExpr>(Exp)) {
  263. // Substitute parent for 'this'
  264. if (CallCtx && CallCtx->SelfArg) {
  265. if (!CallCtx->SelfArrow && NDeref)
  266. // 'this' is a pointer, but self is not, so need to take address.
  267. --(*NDeref);
  268. return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
  269. }
  270. else {
  271. makeThis();
  272. return 1;
  273. }
  274. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
  275. NamedDecl *ND = ME->getMemberDecl();
  276. int ImplicitDeref = ME->isArrow() ? 1 : 0;
  277. unsigned Root = makeDot(ND, false);
  278. unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
  279. NodeVec[Root].setArrow(ImplicitDeref > 0);
  280. NodeVec[Root].setSize(Sz + 1);
  281. return Sz + 1;
  282. } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
  283. // When calling a function with a lock_returned attribute, replace
  284. // the function call with the expression in lock_returned.
  285. CXXMethodDecl* MD =
  286. cast<CXXMethodDecl>(CMCE->getMethodDecl()->getMostRecentDecl());
  287. if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
  288. CallingContext LRCallCtx(CMCE->getMethodDecl());
  289. LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
  290. LRCallCtx.SelfArrow =
  291. dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
  292. LRCallCtx.NumArgs = CMCE->getNumArgs();
  293. LRCallCtx.FunArgs = CMCE->getArgs();
  294. LRCallCtx.PrevCtx = CallCtx;
  295. return buildSExpr(At->getArg(), &LRCallCtx);
  296. }
  297. // Hack to treat smart pointers and iterators as pointers;
  298. // ignore any method named get().
  299. if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
  300. CMCE->getNumArgs() == 0) {
  301. if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
  302. ++(*NDeref);
  303. return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
  304. }
  305. unsigned NumCallArgs = CMCE->getNumArgs();
  306. unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
  307. unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
  308. Expr** CallArgs = CMCE->getArgs();
  309. for (unsigned i = 0; i < NumCallArgs; ++i) {
  310. Sz += buildSExpr(CallArgs[i], CallCtx);
  311. }
  312. NodeVec[Root].setSize(Sz + 1);
  313. return Sz + 1;
  314. } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
  315. FunctionDecl* FD =
  316. cast<FunctionDecl>(CE->getDirectCallee()->getMostRecentDecl());
  317. if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
  318. CallingContext LRCallCtx(CE->getDirectCallee());
  319. LRCallCtx.NumArgs = CE->getNumArgs();
  320. LRCallCtx.FunArgs = CE->getArgs();
  321. LRCallCtx.PrevCtx = CallCtx;
  322. return buildSExpr(At->getArg(), &LRCallCtx);
  323. }
  324. // Treat smart pointers and iterators as pointers;
  325. // ignore the * and -> operators.
  326. if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
  327. OverloadedOperatorKind k = OE->getOperator();
  328. if (k == OO_Star) {
  329. if (NDeref) ++(*NDeref);
  330. return buildSExpr(OE->getArg(0), CallCtx, NDeref);
  331. }
  332. else if (k == OO_Arrow) {
  333. return buildSExpr(OE->getArg(0), CallCtx, NDeref);
  334. }
  335. }
  336. unsigned NumCallArgs = CE->getNumArgs();
  337. unsigned Root = makeCall(NumCallArgs, 0);
  338. unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
  339. Expr** CallArgs = CE->getArgs();
  340. for (unsigned i = 0; i < NumCallArgs; ++i) {
  341. Sz += buildSExpr(CallArgs[i], CallCtx);
  342. }
  343. NodeVec[Root].setSize(Sz+1);
  344. return Sz+1;
  345. } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
  346. unsigned Root = makeBinary();
  347. unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
  348. Sz += buildSExpr(BOE->getRHS(), CallCtx);
  349. NodeVec[Root].setSize(Sz);
  350. return Sz;
  351. } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
  352. // Ignore & and * operators -- they're no-ops.
  353. // However, we try to figure out whether the expression is a pointer,
  354. // so we can use . and -> appropriately in error messages.
  355. if (UOE->getOpcode() == UO_Deref) {
  356. if (NDeref) ++(*NDeref);
  357. return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
  358. }
  359. if (UOE->getOpcode() == UO_AddrOf) {
  360. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
  361. if (DRE->getDecl()->isCXXInstanceMember()) {
  362. // This is a pointer-to-member expression, e.g. &MyClass::mu_.
  363. // We interpret this syntax specially, as a wildcard.
  364. unsigned Root = makeDot(DRE->getDecl(), false);
  365. makeWildcard();
  366. NodeVec[Root].setSize(2);
  367. return 2;
  368. }
  369. }
  370. if (NDeref) --(*NDeref);
  371. return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
  372. }
  373. unsigned Root = makeUnary();
  374. unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
  375. NodeVec[Root].setSize(Sz);
  376. return Sz;
  377. } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
  378. unsigned Root = makeIndex();
  379. unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
  380. Sz += buildSExpr(ASE->getIdx(), CallCtx);
  381. NodeVec[Root].setSize(Sz);
  382. return Sz;
  383. } else if (AbstractConditionalOperator *CE =
  384. dyn_cast<AbstractConditionalOperator>(Exp)) {
  385. unsigned Root = makeUnknown(3);
  386. unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
  387. Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
  388. Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
  389. NodeVec[Root].setSize(Sz);
  390. return Sz;
  391. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
  392. unsigned Root = makeUnknown(3);
  393. unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
  394. Sz += buildSExpr(CE->getLHS(), CallCtx);
  395. Sz += buildSExpr(CE->getRHS(), CallCtx);
  396. NodeVec[Root].setSize(Sz);
  397. return Sz;
  398. } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
  399. return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
  400. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
  401. return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
  402. } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
  403. return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
  404. } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
  405. return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
  406. } else if (isa<CharacterLiteral>(Exp) ||
  407. isa<CXXNullPtrLiteralExpr>(Exp) ||
  408. isa<GNUNullExpr>(Exp) ||
  409. isa<CXXBoolLiteralExpr>(Exp) ||
  410. isa<FloatingLiteral>(Exp) ||
  411. isa<ImaginaryLiteral>(Exp) ||
  412. isa<IntegerLiteral>(Exp) ||
  413. isa<StringLiteral>(Exp) ||
  414. isa<ObjCStringLiteral>(Exp)) {
  415. makeNop();
  416. return 1; // FIXME: Ignore literals for now
  417. } else {
  418. makeNop();
  419. return 1; // Ignore. FIXME: mark as invalid expression?
  420. }
  421. }
  422. /// \brief Construct a SExpr from an expression.
  423. /// \param MutexExp The original mutex expression within an attribute
  424. /// \param DeclExp An expression involving the Decl on which the attribute
  425. /// occurs.
  426. /// \param D The declaration to which the lock/unlock attribute is attached.
  427. void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D,
  428. VarDecl *SelfDecl = 0) {
  429. CallingContext CallCtx(D);
  430. if (MutexExp) {
  431. if (StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
  432. if (SLit->getString() == StringRef("*"))
  433. // The "*" expr is a universal lock, which essentially turns off
  434. // checks until it is removed from the lockset.
  435. makeUniversal();
  436. else
  437. // Ignore other string literals for now.
  438. makeNop();
  439. return;
  440. }
  441. }
  442. // If we are processing a raw attribute expression, with no substitutions.
  443. if (DeclExp == 0) {
  444. buildSExpr(MutexExp, 0);
  445. return;
  446. }
  447. // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
  448. // for formal parameters when we call buildMutexID later.
  449. if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
  450. CallCtx.SelfArg = ME->getBase();
  451. CallCtx.SelfArrow = ME->isArrow();
  452. } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
  453. CallCtx.SelfArg = CE->getImplicitObjectArgument();
  454. CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
  455. CallCtx.NumArgs = CE->getNumArgs();
  456. CallCtx.FunArgs = CE->getArgs();
  457. } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
  458. CallCtx.NumArgs = CE->getNumArgs();
  459. CallCtx.FunArgs = CE->getArgs();
  460. } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
  461. CallCtx.SelfArg = 0; // Will be set below
  462. CallCtx.NumArgs = CE->getNumArgs();
  463. CallCtx.FunArgs = CE->getArgs();
  464. } else if (D && isa<CXXDestructorDecl>(D)) {
  465. // There's no such thing as a "destructor call" in the AST.
  466. CallCtx.SelfArg = DeclExp;
  467. }
  468. // Hack to handle constructors, where self cannot be recovered from
  469. // the expression.
  470. if (SelfDecl && !CallCtx.SelfArg) {
  471. DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
  472. SelfDecl->getLocation());
  473. CallCtx.SelfArg = &SelfDRE;
  474. // If the attribute has no arguments, then assume the argument is "this".
  475. if (MutexExp == 0)
  476. buildSExpr(CallCtx.SelfArg, 0);
  477. else // For most attributes.
  478. buildSExpr(MutexExp, &CallCtx);
  479. return;
  480. }
  481. // If the attribute has no arguments, then assume the argument is "this".
  482. if (MutexExp == 0)
  483. buildSExpr(CallCtx.SelfArg, 0);
  484. else // For most attributes.
  485. buildSExpr(MutexExp, &CallCtx);
  486. }
  487. /// \brief Get index of next sibling of node i.
  488. unsigned getNextSibling(unsigned i) const {
  489. return i + NodeVec[i].size();
  490. }
  491. public:
  492. explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
  493. /// \param MutexExp The original mutex expression within an attribute
  494. /// \param DeclExp An expression involving the Decl on which the attribute
  495. /// occurs.
  496. /// \param D The declaration to which the lock/unlock attribute is attached.
  497. /// Caller must check isValid() after construction.
  498. SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D,
  499. VarDecl *SelfDecl=0) {
  500. buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
  501. }
  502. /// Return true if this is a valid decl sequence.
  503. /// Caller must call this by hand after construction to handle errors.
  504. bool isValid() const {
  505. return !NodeVec.empty();
  506. }
  507. bool shouldIgnore() const {
  508. // Nop is a mutex that we have decided to deliberately ignore.
  509. assert(NodeVec.size() > 0 && "Invalid Mutex");
  510. return NodeVec[0].kind() == EOP_Nop;
  511. }
  512. bool isUniversal() const {
  513. assert(NodeVec.size() > 0 && "Invalid Mutex");
  514. return NodeVec[0].kind() == EOP_Universal;
  515. }
  516. /// Issue a warning about an invalid lock expression
  517. static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
  518. Expr *DeclExp, const NamedDecl* D) {
  519. SourceLocation Loc;
  520. if (DeclExp)
  521. Loc = DeclExp->getExprLoc();
  522. // FIXME: add a note about the attribute location in MutexExp or D
  523. if (Loc.isValid())
  524. Handler.handleInvalidLockExp(Loc);
  525. }
  526. bool operator==(const SExpr &other) const {
  527. return NodeVec == other.NodeVec;
  528. }
  529. bool operator!=(const SExpr &other) const {
  530. return !(*this == other);
  531. }
  532. bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
  533. if (NodeVec[i].matches(Other.NodeVec[j])) {
  534. unsigned ni = NodeVec[i].arity();
  535. unsigned nj = Other.NodeVec[j].arity();
  536. unsigned n = (ni < nj) ? ni : nj;
  537. bool Result = true;
  538. unsigned ci = i+1; // first child of i
  539. unsigned cj = j+1; // first child of j
  540. for (unsigned k = 0; k < n;
  541. ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
  542. Result = Result && matches(Other, ci, cj);
  543. }
  544. return Result;
  545. }
  546. return false;
  547. }
  548. // A partial match between a.mu and b.mu returns true a and b have the same
  549. // type (and thus mu refers to the same mutex declaration), regardless of
  550. // whether a and b are different objects or not.
  551. bool partiallyMatches(const SExpr &Other) const {
  552. if (NodeVec[0].kind() == EOP_Dot)
  553. return NodeVec[0].matches(Other.NodeVec[0]);
  554. return false;
  555. }
  556. /// \brief Pretty print a lock expression for use in error messages.
  557. std::string toString(unsigned i = 0) const {
  558. assert(isValid());
  559. if (i >= NodeVec.size())
  560. return "";
  561. const SExprNode* N = &NodeVec[i];
  562. switch (N->kind()) {
  563. case EOP_Nop:
  564. return "_";
  565. case EOP_Wildcard:
  566. return "(?)";
  567. case EOP_Universal:
  568. return "*";
  569. case EOP_This:
  570. return "this";
  571. case EOP_NVar:
  572. case EOP_LVar: {
  573. return N->getNamedDecl()->getNameAsString();
  574. }
  575. case EOP_Dot: {
  576. if (NodeVec[i+1].kind() == EOP_Wildcard) {
  577. std::string S = "&";
  578. S += N->getNamedDecl()->getQualifiedNameAsString();
  579. return S;
  580. }
  581. std::string FieldName = N->getNamedDecl()->getNameAsString();
  582. if (NodeVec[i+1].kind() == EOP_This)
  583. return FieldName;
  584. std::string S = toString(i+1);
  585. if (N->isArrow())
  586. return S + "->" + FieldName;
  587. else
  588. return S + "." + FieldName;
  589. }
  590. case EOP_Call: {
  591. std::string S = toString(i+1) + "(";
  592. unsigned NumArgs = N->arity()-1;
  593. unsigned ci = getNextSibling(i+1);
  594. for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
  595. S += toString(ci);
  596. if (k+1 < NumArgs) S += ",";
  597. }
  598. S += ")";
  599. return S;
  600. }
  601. case EOP_MCall: {
  602. std::string S = "";
  603. if (NodeVec[i+1].kind() != EOP_This)
  604. S = toString(i+1) + ".";
  605. if (const NamedDecl *D = N->getFunctionDecl())
  606. S += D->getNameAsString() + "(";
  607. else
  608. S += "#(";
  609. unsigned NumArgs = N->arity()-1;
  610. unsigned ci = getNextSibling(i+1);
  611. for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
  612. S += toString(ci);
  613. if (k+1 < NumArgs) S += ",";
  614. }
  615. S += ")";
  616. return S;
  617. }
  618. case EOP_Index: {
  619. std::string S1 = toString(i+1);
  620. std::string S2 = toString(i+1 + NodeVec[i+1].size());
  621. return S1 + "[" + S2 + "]";
  622. }
  623. case EOP_Unary: {
  624. std::string S = toString(i+1);
  625. return "#" + S;
  626. }
  627. case EOP_Binary: {
  628. std::string S1 = toString(i+1);
  629. std::string S2 = toString(i+1 + NodeVec[i+1].size());
  630. return "(" + S1 + "#" + S2 + ")";
  631. }
  632. case EOP_Unknown: {
  633. unsigned NumChildren = N->arity();
  634. if (NumChildren == 0)
  635. return "(...)";
  636. std::string S = "(";
  637. unsigned ci = i+1;
  638. for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
  639. S += toString(ci);
  640. if (j+1 < NumChildren) S += "#";
  641. }
  642. S += ")";
  643. return S;
  644. }
  645. }
  646. return "";
  647. }
  648. };
  649. /// \brief A short list of SExprs
  650. class MutexIDList : public SmallVector<SExpr, 3> {
  651. public:
  652. /// \brief Return true if the list contains the specified SExpr
  653. /// Performs a linear search, because these lists are almost always very small.
  654. bool contains(const SExpr& M) {
  655. for (iterator I=begin(),E=end(); I != E; ++I)
  656. if ((*I) == M) return true;
  657. return false;
  658. }
  659. /// \brief Push M onto list, bud discard duplicates
  660. void push_back_nodup(const SExpr& M) {
  661. if (!contains(M)) push_back(M);
  662. }
  663. };
  664. /// \brief This is a helper class that stores info about the most recent
  665. /// accquire of a Lock.
  666. ///
  667. /// The main body of the analysis maps MutexIDs to LockDatas.
  668. struct LockData {
  669. SourceLocation AcquireLoc;
  670. /// \brief LKind stores whether a lock is held shared or exclusively.
  671. /// Note that this analysis does not currently support either re-entrant
  672. /// locking or lock "upgrading" and "downgrading" between exclusive and
  673. /// shared.
  674. ///
  675. /// FIXME: add support for re-entrant locking and lock up/downgrading
  676. LockKind LKind;
  677. bool Managed; // for ScopedLockable objects
  678. SExpr UnderlyingMutex; // for ScopedLockable objects
  679. LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
  680. : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
  681. UnderlyingMutex(Decl::EmptyShell())
  682. {}
  683. LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
  684. : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
  685. UnderlyingMutex(Mu)
  686. {}
  687. bool operator==(const LockData &other) const {
  688. return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
  689. }
  690. bool operator!=(const LockData &other) const {
  691. return !(*this == other);
  692. }
  693. void Profile(llvm::FoldingSetNodeID &ID) const {
  694. ID.AddInteger(AcquireLoc.getRawEncoding());
  695. ID.AddInteger(LKind);
  696. }
  697. bool isAtLeast(LockKind LK) {
  698. return (LK == LK_Shared) || (LKind == LK_Exclusive);
  699. }
  700. };
  701. /// \brief A FactEntry stores a single fact that is known at a particular point
  702. /// in the program execution. Currently, this is information regarding a lock
  703. /// that is held at that point.
  704. struct FactEntry {
  705. SExpr MutID;
  706. LockData LDat;
  707. FactEntry(const SExpr& M, const LockData& L)
  708. : MutID(M), LDat(L)
  709. { }
  710. };
  711. typedef unsigned short FactID;
  712. /// \brief FactManager manages the memory for all facts that are created during
  713. /// the analysis of a single routine.
  714. class FactManager {
  715. private:
  716. std::vector<FactEntry> Facts;
  717. public:
  718. FactID newLock(const SExpr& M, const LockData& L) {
  719. Facts.push_back(FactEntry(M,L));
  720. return static_cast<unsigned short>(Facts.size() - 1);
  721. }
  722. const FactEntry& operator[](FactID F) const { return Facts[F]; }
  723. FactEntry& operator[](FactID F) { return Facts[F]; }
  724. };
  725. /// \brief A FactSet is the set of facts that are known to be true at a
  726. /// particular program point. FactSets must be small, because they are
  727. /// frequently copied, and are thus implemented as a set of indices into a
  728. /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
  729. /// locks, so we can get away with doing a linear search for lookup. Note
  730. /// that a hashtable or map is inappropriate in this case, because lookups
  731. /// may involve partial pattern matches, rather than exact matches.
  732. class FactSet {
  733. private:
  734. typedef SmallVector<FactID, 4> FactVec;
  735. FactVec FactIDs;
  736. public:
  737. typedef FactVec::iterator iterator;
  738. typedef FactVec::const_iterator const_iterator;
  739. iterator begin() { return FactIDs.begin(); }
  740. const_iterator begin() const { return FactIDs.begin(); }
  741. iterator end() { return FactIDs.end(); }
  742. const_iterator end() const { return FactIDs.end(); }
  743. bool isEmpty() const { return FactIDs.size() == 0; }
  744. FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
  745. FactID F = FM.newLock(M, L);
  746. FactIDs.push_back(F);
  747. return F;
  748. }
  749. bool removeLock(FactManager& FM, const SExpr& M) {
  750. unsigned n = FactIDs.size();
  751. if (n == 0)
  752. return false;
  753. for (unsigned i = 0; i < n-1; ++i) {
  754. if (FM[FactIDs[i]].MutID.matches(M)) {
  755. FactIDs[i] = FactIDs[n-1];
  756. FactIDs.pop_back();
  757. return true;
  758. }
  759. }
  760. if (FM[FactIDs[n-1]].MutID.matches(M)) {
  761. FactIDs.pop_back();
  762. return true;
  763. }
  764. return false;
  765. }
  766. LockData* findLock(FactManager &FM, const SExpr &M) const {
  767. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  768. const SExpr &Exp = FM[*I].MutID;
  769. if (Exp.matches(M))
  770. return &FM[*I].LDat;
  771. }
  772. return 0;
  773. }
  774. LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
  775. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  776. const SExpr &Exp = FM[*I].MutID;
  777. if (Exp.matches(M) || Exp.isUniversal())
  778. return &FM[*I].LDat;
  779. }
  780. return 0;
  781. }
  782. FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
  783. for (const_iterator I=begin(), E=end(); I != E; ++I) {
  784. const SExpr& Exp = FM[*I].MutID;
  785. if (Exp.partiallyMatches(M)) return &FM[*I];
  786. }
  787. return 0;
  788. }
  789. };
  790. /// A Lockset maps each SExpr (defined above) to information about how it has
  791. /// been locked.
  792. typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
  793. typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
  794. class LocalVariableMap;
  795. /// A side (entry or exit) of a CFG node.
  796. enum CFGBlockSide { CBS_Entry, CBS_Exit };
  797. /// CFGBlockInfo is a struct which contains all the information that is
  798. /// maintained for each block in the CFG. See LocalVariableMap for more
  799. /// information about the contexts.
  800. struct CFGBlockInfo {
  801. FactSet EntrySet; // Lockset held at entry to block
  802. FactSet ExitSet; // Lockset held at exit from block
  803. LocalVarContext EntryContext; // Context held at entry to block
  804. LocalVarContext ExitContext; // Context held at exit from block
  805. SourceLocation EntryLoc; // Location of first statement in block
  806. SourceLocation ExitLoc; // Location of last statement in block.
  807. unsigned EntryIndex; // Used to replay contexts later
  808. bool Reachable; // Is this block reachable?
  809. const FactSet &getSet(CFGBlockSide Side) const {
  810. return Side == CBS_Entry ? EntrySet : ExitSet;
  811. }
  812. SourceLocation getLocation(CFGBlockSide Side) const {
  813. return Side == CBS_Entry ? EntryLoc : ExitLoc;
  814. }
  815. private:
  816. CFGBlockInfo(LocalVarContext EmptyCtx)
  817. : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
  818. { }
  819. public:
  820. static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
  821. };
  822. // A LocalVariableMap maintains a map from local variables to their currently
  823. // valid definitions. It provides SSA-like functionality when traversing the
  824. // CFG. Like SSA, each definition or assignment to a variable is assigned a
  825. // unique name (an integer), which acts as the SSA name for that definition.
  826. // The total set of names is shared among all CFG basic blocks.
  827. // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
  828. // with their SSA-names. Instead, we compute a Context for each point in the
  829. // code, which maps local variables to the appropriate SSA-name. This map
  830. // changes with each assignment.
  831. //
  832. // The map is computed in a single pass over the CFG. Subsequent analyses can
  833. // then query the map to find the appropriate Context for a statement, and use
  834. // that Context to look up the definitions of variables.
  835. class LocalVariableMap {
  836. public:
  837. typedef LocalVarContext Context;
  838. /// A VarDefinition consists of an expression, representing the value of the
  839. /// variable, along with the context in which that expression should be
  840. /// interpreted. A reference VarDefinition does not itself contain this
  841. /// information, but instead contains a pointer to a previous VarDefinition.
  842. struct VarDefinition {
  843. public:
  844. friend class LocalVariableMap;
  845. const NamedDecl *Dec; // The original declaration for this variable.
  846. const Expr *Exp; // The expression for this variable, OR
  847. unsigned Ref; // Reference to another VarDefinition
  848. Context Ctx; // The map with which Exp should be interpreted.
  849. bool isReference() { return !Exp; }
  850. private:
  851. // Create ordinary variable definition
  852. VarDefinition(const NamedDecl *D, const Expr *E, Context C)
  853. : Dec(D), Exp(E), Ref(0), Ctx(C)
  854. { }
  855. // Create reference to previous definition
  856. VarDefinition(const NamedDecl *D, unsigned R, Context C)
  857. : Dec(D), Exp(0), Ref(R), Ctx(C)
  858. { }
  859. };
  860. private:
  861. Context::Factory ContextFactory;
  862. std::vector<VarDefinition> VarDefinitions;
  863. std::vector<unsigned> CtxIndices;
  864. std::vector<std::pair<Stmt*, Context> > SavedContexts;
  865. public:
  866. LocalVariableMap() {
  867. // index 0 is a placeholder for undefined variables (aka phi-nodes).
  868. VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
  869. }
  870. /// Look up a definition, within the given context.
  871. const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
  872. const unsigned *i = Ctx.lookup(D);
  873. if (!i)
  874. return 0;
  875. assert(*i < VarDefinitions.size());
  876. return &VarDefinitions[*i];
  877. }
  878. /// Look up the definition for D within the given context. Returns
  879. /// NULL if the expression is not statically known. If successful, also
  880. /// modifies Ctx to hold the context of the return Expr.
  881. const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
  882. const unsigned *P = Ctx.lookup(D);
  883. if (!P)
  884. return 0;
  885. unsigned i = *P;
  886. while (i > 0) {
  887. if (VarDefinitions[i].Exp) {
  888. Ctx = VarDefinitions[i].Ctx;
  889. return VarDefinitions[i].Exp;
  890. }
  891. i = VarDefinitions[i].Ref;
  892. }
  893. return 0;
  894. }
  895. Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
  896. /// Return the next context after processing S. This function is used by
  897. /// clients of the class to get the appropriate context when traversing the
  898. /// CFG. It must be called for every assignment or DeclStmt.
  899. Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
  900. if (SavedContexts[CtxIndex+1].first == S) {
  901. CtxIndex++;
  902. Context Result = SavedContexts[CtxIndex].second;
  903. return Result;
  904. }
  905. return C;
  906. }
  907. void dumpVarDefinitionName(unsigned i) {
  908. if (i == 0) {
  909. llvm::errs() << "Undefined";
  910. return;
  911. }
  912. const NamedDecl *Dec = VarDefinitions[i].Dec;
  913. if (!Dec) {
  914. llvm::errs() << "<<NULL>>";
  915. return;
  916. }
  917. Dec->printName(llvm::errs());
  918. llvm::errs() << "." << i << " " << ((const void*) Dec);
  919. }
  920. /// Dumps an ASCII representation of the variable map to llvm::errs()
  921. void dump() {
  922. for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
  923. const Expr *Exp = VarDefinitions[i].Exp;
  924. unsigned Ref = VarDefinitions[i].Ref;
  925. dumpVarDefinitionName(i);
  926. llvm::errs() << " = ";
  927. if (Exp) Exp->dump();
  928. else {
  929. dumpVarDefinitionName(Ref);
  930. llvm::errs() << "\n";
  931. }
  932. }
  933. }
  934. /// Dumps an ASCII representation of a Context to llvm::errs()
  935. void dumpContext(Context C) {
  936. for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
  937. const NamedDecl *D = I.getKey();
  938. D->printName(llvm::errs());
  939. const unsigned *i = C.lookup(D);
  940. llvm::errs() << " -> ";
  941. dumpVarDefinitionName(*i);
  942. llvm::errs() << "\n";
  943. }
  944. }
  945. /// Builds the variable map.
  946. void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
  947. std::vector<CFGBlockInfo> &BlockInfo);
  948. protected:
  949. // Get the current context index
  950. unsigned getContextIndex() { return SavedContexts.size()-1; }
  951. // Save the current context for later replay
  952. void saveContext(Stmt *S, Context C) {
  953. SavedContexts.push_back(std::make_pair(S,C));
  954. }
  955. // Adds a new definition to the given context, and returns a new context.
  956. // This method should be called when declaring a new variable.
  957. Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
  958. assert(!Ctx.contains(D));
  959. unsigned newID = VarDefinitions.size();
  960. Context NewCtx = ContextFactory.add(Ctx, D, newID);
  961. VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
  962. return NewCtx;
  963. }
  964. // Add a new reference to an existing definition.
  965. Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
  966. unsigned newID = VarDefinitions.size();
  967. Context NewCtx = ContextFactory.add(Ctx, D, newID);
  968. VarDefinitions.push_back(VarDefinition(D, i, Ctx));
  969. return NewCtx;
  970. }
  971. // Updates a definition only if that definition is already in the map.
  972. // This method should be called when assigning to an existing variable.
  973. Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
  974. if (Ctx.contains(D)) {
  975. unsigned newID = VarDefinitions.size();
  976. Context NewCtx = ContextFactory.remove(Ctx, D);
  977. NewCtx = ContextFactory.add(NewCtx, D, newID);
  978. VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
  979. return NewCtx;
  980. }
  981. return Ctx;
  982. }
  983. // Removes a definition from the context, but keeps the variable name
  984. // as a valid variable. The index 0 is a placeholder for cleared definitions.
  985. Context clearDefinition(const NamedDecl *D, Context Ctx) {
  986. Context NewCtx = Ctx;
  987. if (NewCtx.contains(D)) {
  988. NewCtx = ContextFactory.remove(NewCtx, D);
  989. NewCtx = ContextFactory.add(NewCtx, D, 0);
  990. }
  991. return NewCtx;
  992. }
  993. // Remove a definition entirely frmo the context.
  994. Context removeDefinition(const NamedDecl *D, Context Ctx) {
  995. Context NewCtx = Ctx;
  996. if (NewCtx.contains(D)) {
  997. NewCtx = ContextFactory.remove(NewCtx, D);
  998. }
  999. return NewCtx;
  1000. }
  1001. Context intersectContexts(Context C1, Context C2);
  1002. Context createReferenceContext(Context C);
  1003. void intersectBackEdge(Context C1, Context C2);
  1004. friend class VarMapBuilder;
  1005. };
  1006. // This has to be defined after LocalVariableMap.
  1007. CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
  1008. return CFGBlockInfo(M.getEmptyContext());
  1009. }
  1010. /// Visitor which builds a LocalVariableMap
  1011. class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
  1012. public:
  1013. LocalVariableMap* VMap;
  1014. LocalVariableMap::Context Ctx;
  1015. VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
  1016. : VMap(VM), Ctx(C) {}
  1017. void VisitDeclStmt(DeclStmt *S);
  1018. void VisitBinaryOperator(BinaryOperator *BO);
  1019. };
  1020. // Add new local variables to the variable map
  1021. void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
  1022. bool modifiedCtx = false;
  1023. DeclGroupRef DGrp = S->getDeclGroup();
  1024. for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
  1025. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
  1026. Expr *E = VD->getInit();
  1027. // Add local variables with trivial type to the variable map
  1028. QualType T = VD->getType();
  1029. if (T.isTrivialType(VD->getASTContext())) {
  1030. Ctx = VMap->addDefinition(VD, E, Ctx);
  1031. modifiedCtx = true;
  1032. }
  1033. }
  1034. }
  1035. if (modifiedCtx)
  1036. VMap->saveContext(S, Ctx);
  1037. }
  1038. // Update local variable definitions in variable map
  1039. void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
  1040. if (!BO->isAssignmentOp())
  1041. return;
  1042. Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
  1043. // Update the variable map and current context.
  1044. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
  1045. ValueDecl *VDec = DRE->getDecl();
  1046. if (Ctx.lookup(VDec)) {
  1047. if (BO->getOpcode() == BO_Assign)
  1048. Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
  1049. else
  1050. // FIXME -- handle compound assignment operators
  1051. Ctx = VMap->clearDefinition(VDec, Ctx);
  1052. VMap->saveContext(BO, Ctx);
  1053. }
  1054. }
  1055. }
  1056. // Computes the intersection of two contexts. The intersection is the
  1057. // set of variables which have the same definition in both contexts;
  1058. // variables with different definitions are discarded.
  1059. LocalVariableMap::Context
  1060. LocalVariableMap::intersectContexts(Context C1, Context C2) {
  1061. Context Result = C1;
  1062. for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
  1063. const NamedDecl *Dec = I.getKey();
  1064. unsigned i1 = I.getData();
  1065. const unsigned *i2 = C2.lookup(Dec);
  1066. if (!i2) // variable doesn't exist on second path
  1067. Result = removeDefinition(Dec, Result);
  1068. else if (*i2 != i1) // variable exists, but has different definition
  1069. Result = clearDefinition(Dec, Result);
  1070. }
  1071. return Result;
  1072. }
  1073. // For every variable in C, create a new variable that refers to the
  1074. // definition in C. Return a new context that contains these new variables.
  1075. // (We use this for a naive implementation of SSA on loop back-edges.)
  1076. LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
  1077. Context Result = getEmptyContext();
  1078. for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
  1079. const NamedDecl *Dec = I.getKey();
  1080. unsigned i = I.getData();
  1081. Result = addReference(Dec, i, Result);
  1082. }
  1083. return Result;
  1084. }
  1085. // This routine also takes the intersection of C1 and C2, but it does so by
  1086. // altering the VarDefinitions. C1 must be the result of an earlier call to
  1087. // createReferenceContext.
  1088. void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
  1089. for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
  1090. const NamedDecl *Dec = I.getKey();
  1091. unsigned i1 = I.getData();
  1092. VarDefinition *VDef = &VarDefinitions[i1];
  1093. assert(VDef->isReference());
  1094. const unsigned *i2 = C2.lookup(Dec);
  1095. if (!i2 || (*i2 != i1))
  1096. VDef->Ref = 0; // Mark this variable as undefined
  1097. }
  1098. }
  1099. // Traverse the CFG in topological order, so all predecessors of a block
  1100. // (excluding back-edges) are visited before the block itself. At
  1101. // each point in the code, we calculate a Context, which holds the set of
  1102. // variable definitions which are visible at that point in execution.
  1103. // Visible variables are mapped to their definitions using an array that
  1104. // contains all definitions.
  1105. //
  1106. // At join points in the CFG, the set is computed as the intersection of
  1107. // the incoming sets along each edge, E.g.
  1108. //
  1109. // { Context | VarDefinitions }
  1110. // int x = 0; { x -> x1 | x1 = 0 }
  1111. // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
  1112. // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
  1113. // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
  1114. // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
  1115. //
  1116. // This is essentially a simpler and more naive version of the standard SSA
  1117. // algorithm. Those definitions that remain in the intersection are from blocks
  1118. // that strictly dominate the current block. We do not bother to insert proper
  1119. // phi nodes, because they are not used in our analysis; instead, wherever
  1120. // a phi node would be required, we simply remove that definition from the
  1121. // context (E.g. x above).
  1122. //
  1123. // The initial traversal does not capture back-edges, so those need to be
  1124. // handled on a separate pass. Whenever the first pass encounters an
  1125. // incoming back edge, it duplicates the context, creating new definitions
  1126. // that refer back to the originals. (These correspond to places where SSA
  1127. // might have to insert a phi node.) On the second pass, these definitions are
  1128. // set to NULL if the variable has changed on the back-edge (i.e. a phi
  1129. // node was actually required.) E.g.
  1130. //
  1131. // { Context | VarDefinitions }
  1132. // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
  1133. // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
  1134. // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
  1135. // ... { y -> y1 | x3 = 2, x2 = 1, ... }
  1136. //
  1137. void LocalVariableMap::traverseCFG(CFG *CFGraph,
  1138. PostOrderCFGView *SortedGraph,
  1139. std::vector<CFGBlockInfo> &BlockInfo) {
  1140. PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
  1141. CtxIndices.resize(CFGraph->getNumBlockIDs());
  1142. for (PostOrderCFGView::iterator I = SortedGraph->begin(),
  1143. E = SortedGraph->end(); I!= E; ++I) {
  1144. const CFGBlock *CurrBlock = *I;
  1145. int CurrBlockID = CurrBlock->getBlockID();
  1146. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
  1147. VisitedBlocks.insert(CurrBlock);
  1148. // Calculate the entry context for the current block
  1149. bool HasBackEdges = false;
  1150. bool CtxInit = true;
  1151. for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  1152. PE = CurrBlock->pred_end(); PI != PE; ++PI) {
  1153. // if *PI -> CurrBlock is a back edge, so skip it
  1154. if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
  1155. HasBackEdges = true;
  1156. continue;
  1157. }
  1158. int PrevBlockID = (*PI)->getBlockID();
  1159. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  1160. if (CtxInit) {
  1161. CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
  1162. CtxInit = false;
  1163. }
  1164. else {
  1165. CurrBlockInfo->EntryContext =
  1166. intersectContexts(CurrBlockInfo->EntryContext,
  1167. PrevBlockInfo->ExitContext);
  1168. }
  1169. }
  1170. // Duplicate the context if we have back-edges, so we can call
  1171. // intersectBackEdges later.
  1172. if (HasBackEdges)
  1173. CurrBlockInfo->EntryContext =
  1174. createReferenceContext(CurrBlockInfo->EntryContext);
  1175. // Create a starting context index for the current block
  1176. saveContext(0, CurrBlockInfo->EntryContext);
  1177. CurrBlockInfo->EntryIndex = getContextIndex();
  1178. // Visit all the statements in the basic block.
  1179. VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
  1180. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  1181. BE = CurrBlock->end(); BI != BE; ++BI) {
  1182. switch (BI->getKind()) {
  1183. case CFGElement::Statement: {
  1184. const CFGStmt *CS = cast<CFGStmt>(&*BI);
  1185. VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
  1186. break;
  1187. }
  1188. default:
  1189. break;
  1190. }
  1191. }
  1192. CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
  1193. // Mark variables on back edges as "unknown" if they've been changed.
  1194. for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
  1195. SE = CurrBlock->succ_end(); SI != SE; ++SI) {
  1196. // if CurrBlock -> *SI is *not* a back edge
  1197. if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
  1198. continue;
  1199. CFGBlock *FirstLoopBlock = *SI;
  1200. Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
  1201. Context LoopEnd = CurrBlockInfo->ExitContext;
  1202. intersectBackEdge(LoopBegin, LoopEnd);
  1203. }
  1204. }
  1205. // Put an extra entry at the end of the indexed context array
  1206. unsigned exitID = CFGraph->getExit().getBlockID();
  1207. saveContext(0, BlockInfo[exitID].ExitContext);
  1208. }
  1209. /// Find the appropriate source locations to use when producing diagnostics for
  1210. /// each block in the CFG.
  1211. static void findBlockLocations(CFG *CFGraph,
  1212. PostOrderCFGView *SortedGraph,
  1213. std::vector<CFGBlockInfo> &BlockInfo) {
  1214. for (PostOrderCFGView::iterator I = SortedGraph->begin(),
  1215. E = SortedGraph->end(); I!= E; ++I) {
  1216. const CFGBlock *CurrBlock = *I;
  1217. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
  1218. // Find the source location of the last statement in the block, if the
  1219. // block is not empty.
  1220. if (const Stmt *S = CurrBlock->getTerminator()) {
  1221. CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
  1222. } else {
  1223. for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
  1224. BE = CurrBlock->rend(); BI != BE; ++BI) {
  1225. // FIXME: Handle other CFGElement kinds.
  1226. if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
  1227. CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
  1228. break;
  1229. }
  1230. }
  1231. }
  1232. if (!CurrBlockInfo->ExitLoc.isInvalid()) {
  1233. // This block contains at least one statement. Find the source location
  1234. // of the first statement in the block.
  1235. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  1236. BE = CurrBlock->end(); BI != BE; ++BI) {
  1237. // FIXME: Handle other CFGElement kinds.
  1238. if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
  1239. CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
  1240. break;
  1241. }
  1242. }
  1243. } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
  1244. CurrBlock != &CFGraph->getExit()) {
  1245. // The block is empty, and has a single predecessor. Use its exit
  1246. // location.
  1247. CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
  1248. BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
  1249. }
  1250. }
  1251. }
  1252. /// \brief Class which implements the core thread safety analysis routines.
  1253. class ThreadSafetyAnalyzer {
  1254. friend class BuildLockset;
  1255. ThreadSafetyHandler &Handler;
  1256. LocalVariableMap LocalVarMap;
  1257. FactManager FactMan;
  1258. std::vector<CFGBlockInfo> BlockInfo;
  1259. public:
  1260. ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
  1261. void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
  1262. void removeLock(FactSet &FSet, const SExpr &Mutex,
  1263. SourceLocation UnlockLoc, bool FullyRemove=false);
  1264. template <typename AttrType>
  1265. void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
  1266. const NamedDecl *D, VarDecl *SelfDecl=0);
  1267. template <class AttrType>
  1268. void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
  1269. const NamedDecl *D,
  1270. const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
  1271. Expr *BrE, bool Neg);
  1272. const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
  1273. bool &Negate);
  1274. void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
  1275. const CFGBlock* PredBlock,
  1276. const CFGBlock *CurrBlock);
  1277. void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
  1278. SourceLocation JoinLoc,
  1279. LockErrorKind LEK1, LockErrorKind LEK2,
  1280. bool Modify=true);
  1281. void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
  1282. SourceLocation JoinLoc, LockErrorKind LEK1,
  1283. bool Modify=true) {
  1284. intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
  1285. }
  1286. void runAnalysis(AnalysisDeclContext &AC);
  1287. };
  1288. /// \brief Add a new lock to the lockset, warning if the lock is already there.
  1289. /// \param Mutex -- the Mutex expression for the lock
  1290. /// \param LDat -- the LockData for the lock
  1291. void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
  1292. const LockData &LDat) {
  1293. // FIXME: deal with acquired before/after annotations.
  1294. // FIXME: Don't always warn when we have support for reentrant locks.
  1295. if (Mutex.shouldIgnore())
  1296. return;
  1297. if (FSet.findLock(FactMan, Mutex)) {
  1298. Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
  1299. } else {
  1300. FSet.addLock(FactMan, Mutex, LDat);
  1301. }
  1302. }
  1303. /// \brief Remove a lock from the lockset, warning if the lock is not there.
  1304. /// \param Mutex The lock expression corresponding to the lock to be removed
  1305. /// \param UnlockLoc The source location of the unlock (only used in error msg)
  1306. void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
  1307. const SExpr &Mutex,
  1308. SourceLocation UnlockLoc,
  1309. bool FullyRemove) {
  1310. if (Mutex.shouldIgnore())
  1311. return;
  1312. const LockData *LDat = FSet.findLock(FactMan, Mutex);
  1313. if (!LDat) {
  1314. Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
  1315. return;
  1316. }
  1317. if (LDat->UnderlyingMutex.isValid()) {
  1318. // This is scoped lockable object, which manages the real mutex.
  1319. if (FullyRemove) {
  1320. // We're destroying the managing object.
  1321. // Remove the underlying mutex if it exists; but don't warn.
  1322. if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
  1323. FSet.removeLock(FactMan, LDat->UnderlyingMutex);
  1324. } else {
  1325. // We're releasing the underlying mutex, but not destroying the
  1326. // managing object. Warn on dual release.
  1327. if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
  1328. Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
  1329. UnlockLoc);
  1330. }
  1331. FSet.removeLock(FactMan, LDat->UnderlyingMutex);
  1332. return;
  1333. }
  1334. }
  1335. FSet.removeLock(FactMan, Mutex);
  1336. }
  1337. /// \brief Extract the list of mutexIDs from the attribute on an expression,
  1338. /// and push them onto Mtxs, discarding any duplicates.
  1339. template <typename AttrType>
  1340. void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
  1341. Expr *Exp, const NamedDecl *D,
  1342. VarDecl *SelfDecl) {
  1343. typedef typename AttrType::args_iterator iterator_type;
  1344. if (Attr->args_size() == 0) {
  1345. // The mutex held is the "this" object.
  1346. SExpr Mu(0, Exp, D, SelfDecl);
  1347. if (!Mu.isValid())
  1348. SExpr::warnInvalidLock(Handler, 0, Exp, D);
  1349. else
  1350. Mtxs.push_back_nodup(Mu);
  1351. return;
  1352. }
  1353. for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
  1354. SExpr Mu(*I, Exp, D, SelfDecl);
  1355. if (!Mu.isValid())
  1356. SExpr::warnInvalidLock(Handler, *I, Exp, D);
  1357. else
  1358. Mtxs.push_back_nodup(Mu);
  1359. }
  1360. }
  1361. /// \brief Extract the list of mutexIDs from a trylock attribute. If the
  1362. /// trylock applies to the given edge, then push them onto Mtxs, discarding
  1363. /// any duplicates.
  1364. template <class AttrType>
  1365. void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
  1366. Expr *Exp, const NamedDecl *D,
  1367. const CFGBlock *PredBlock,
  1368. const CFGBlock *CurrBlock,
  1369. Expr *BrE, bool Neg) {
  1370. // Find out which branch has the lock
  1371. bool branch = 0;
  1372. if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
  1373. branch = BLE->getValue();
  1374. }
  1375. else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
  1376. branch = ILE->getValue().getBoolValue();
  1377. }
  1378. int branchnum = branch ? 0 : 1;
  1379. if (Neg) branchnum = !branchnum;
  1380. // If we've taken the trylock branch, then add the lock
  1381. int i = 0;
  1382. for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
  1383. SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
  1384. if (*SI == CurrBlock && i == branchnum) {
  1385. getMutexIDs(Mtxs, Attr, Exp, D);
  1386. }
  1387. }
  1388. }
  1389. bool getStaticBooleanValue(Expr* E, bool& TCond) {
  1390. if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
  1391. TCond = false;
  1392. return true;
  1393. } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
  1394. TCond = BLE->getValue();
  1395. return true;
  1396. } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
  1397. TCond = ILE->getValue().getBoolValue();
  1398. return true;
  1399. } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  1400. return getStaticBooleanValue(CE->getSubExpr(), TCond);
  1401. }
  1402. return false;
  1403. }
  1404. // If Cond can be traced back to a function call, return the call expression.
  1405. // The negate variable should be called with false, and will be set to true
  1406. // if the function call is negated, e.g. if (!mu.tryLock(...))
  1407. const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
  1408. LocalVarContext C,
  1409. bool &Negate) {
  1410. if (!Cond)
  1411. return 0;
  1412. if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
  1413. return CallExp;
  1414. }
  1415. else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
  1416. return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
  1417. }
  1418. else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
  1419. return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
  1420. }
  1421. else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
  1422. return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
  1423. }
  1424. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
  1425. const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
  1426. return getTrylockCallExpr(E, C, Negate);
  1427. }
  1428. else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
  1429. if (UOP->getOpcode() == UO_LNot) {
  1430. Negate = !Negate;
  1431. return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
  1432. }
  1433. return 0;
  1434. }
  1435. else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
  1436. if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
  1437. if (BOP->getOpcode() == BO_NE)
  1438. Negate = !Negate;
  1439. bool TCond = false;
  1440. if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
  1441. if (!TCond) Negate = !Negate;
  1442. return getTrylockCallExpr(BOP->getLHS(), C, Negate);
  1443. }
  1444. else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
  1445. if (!TCond) Negate = !Negate;
  1446. return getTrylockCallExpr(BOP->getRHS(), C, Negate);
  1447. }
  1448. return 0;
  1449. }
  1450. return 0;
  1451. }
  1452. // FIXME -- handle && and || as well.
  1453. return 0;
  1454. }
  1455. /// \brief Find the lockset that holds on the edge between PredBlock
  1456. /// and CurrBlock. The edge set is the exit set of PredBlock (passed
  1457. /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
  1458. void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
  1459. const FactSet &ExitSet,
  1460. const CFGBlock *PredBlock,
  1461. const CFGBlock *CurrBlock) {
  1462. Result = ExitSet;
  1463. if (!PredBlock->getTerminatorCondition())
  1464. return;
  1465. bool Negate = false;
  1466. const Stmt *Cond = PredBlock->getTerminatorCondition();
  1467. const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
  1468. const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
  1469. CallExpr *Exp =
  1470. const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
  1471. if (!Exp)
  1472. return;
  1473. NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
  1474. if(!FunDecl || !FunDecl->hasAttrs())
  1475. return;
  1476. MutexIDList ExclusiveLocksToAdd;
  1477. MutexIDList SharedLocksToAdd;
  1478. // If the condition is a call to a Trylock function, then grab the attributes
  1479. AttrVec &ArgAttrs = FunDecl->getAttrs();
  1480. for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
  1481. Attr *Attr = ArgAttrs[i];
  1482. switch (Attr->getKind()) {
  1483. case attr::ExclusiveTrylockFunction: {
  1484. ExclusiveTrylockFunctionAttr *A =
  1485. cast<ExclusiveTrylockFunctionAttr>(Attr);
  1486. getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
  1487. PredBlock, CurrBlock, A->getSuccessValue(), Negate);
  1488. break;
  1489. }
  1490. case attr::SharedTrylockFunction: {
  1491. SharedTrylockFunctionAttr *A =
  1492. cast<SharedTrylockFunctionAttr>(Attr);
  1493. getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
  1494. PredBlock, CurrBlock, A->getSuccessValue(), Negate);
  1495. break;
  1496. }
  1497. default:
  1498. break;
  1499. }
  1500. }
  1501. // Add and remove locks.
  1502. SourceLocation Loc = Exp->getExprLoc();
  1503. for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
  1504. addLock(Result, ExclusiveLocksToAdd[i],
  1505. LockData(Loc, LK_Exclusive));
  1506. }
  1507. for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
  1508. addLock(Result, SharedLocksToAdd[i],
  1509. LockData(Loc, LK_Shared));
  1510. }
  1511. }
  1512. /// \brief We use this class to visit different types of expressions in
  1513. /// CFGBlocks, and build up the lockset.
  1514. /// An expression may cause us to add or remove locks from the lockset, or else
  1515. /// output error messages related to missing locks.
  1516. /// FIXME: In future, we may be able to not inherit from a visitor.
  1517. class BuildLockset : public StmtVisitor<BuildLockset> {
  1518. friend class ThreadSafetyAnalyzer;
  1519. ThreadSafetyAnalyzer *Analyzer;
  1520. FactSet FSet;
  1521. LocalVariableMap::Context LVarCtx;
  1522. unsigned CtxIndex;
  1523. // Helper functions
  1524. const ValueDecl *getValueDecl(Expr *Exp);
  1525. void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
  1526. Expr *MutexExp, ProtectedOperationKind POK);
  1527. void warnIfMutexHeld(const NamedDecl *D, Expr *Exp, Expr *MutexExp);
  1528. void checkAccess(Expr *Exp, AccessKind AK);
  1529. void checkDereference(Expr *Exp, AccessKind AK);
  1530. void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
  1531. public:
  1532. BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
  1533. : StmtVisitor<BuildLockset>(),
  1534. Analyzer(Anlzr),
  1535. FSet(Info.EntrySet),
  1536. LVarCtx(Info.EntryContext),
  1537. CtxIndex(Info.EntryIndex)
  1538. {}
  1539. void VisitUnaryOperator(UnaryOperator *UO);
  1540. void VisitBinaryOperator(BinaryOperator *BO);
  1541. void VisitCastExpr(CastExpr *CE);
  1542. void VisitCallExpr(CallExpr *Exp);
  1543. void VisitCXXConstructExpr(CXXConstructExpr *Exp);
  1544. void VisitDeclStmt(DeclStmt *S);
  1545. };
  1546. /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
  1547. const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
  1548. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
  1549. return DR->getDecl();
  1550. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
  1551. return ME->getMemberDecl();
  1552. return 0;
  1553. }
  1554. /// \brief Warn if the LSet does not contain a lock sufficient to protect access
  1555. /// of at least the passed in AccessKind.
  1556. void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
  1557. AccessKind AK, Expr *MutexExp,
  1558. ProtectedOperationKind POK) {
  1559. LockKind LK = getLockKindFromAccessKind(AK);
  1560. SExpr Mutex(MutexExp, Exp, D);
  1561. if (!Mutex.isValid()) {
  1562. SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
  1563. return;
  1564. } else if (Mutex.shouldIgnore()) {
  1565. return;
  1566. }
  1567. LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
  1568. bool NoError = true;
  1569. if (!LDat) {
  1570. // No exact match found. Look for a partial match.
  1571. FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
  1572. if (FEntry) {
  1573. // Warn that there's no precise match.
  1574. LDat = &FEntry->LDat;
  1575. std::string PartMatchStr = FEntry->MutID.toString();
  1576. StringRef PartMatchName(PartMatchStr);
  1577. Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
  1578. Exp->getExprLoc(), &PartMatchName);
  1579. } else {
  1580. // Warn that there's no match at all.
  1581. Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
  1582. Exp->getExprLoc());
  1583. }
  1584. NoError = false;
  1585. }
  1586. // Make sure the mutex we found is the right kind.
  1587. if (NoError && LDat && !LDat->isAtLeast(LK))
  1588. Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
  1589. Exp->getExprLoc());
  1590. }
  1591. /// \brief Warn if the LSet contains the given lock.
  1592. void BuildLockset::warnIfMutexHeld(const NamedDecl *D, Expr* Exp,
  1593. Expr *MutexExp) {
  1594. SExpr Mutex(MutexExp, Exp, D);
  1595. if (!Mutex.isValid()) {
  1596. SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
  1597. return;
  1598. }
  1599. LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
  1600. if (LDat) {
  1601. std::string DeclName = D->getNameAsString();
  1602. StringRef DeclNameSR (DeclName);
  1603. Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(),
  1604. Exp->getExprLoc());
  1605. }
  1606. }
  1607. /// \brief This method identifies variable dereferences and checks pt_guarded_by
  1608. /// and pt_guarded_var annotations. Note that we only check these annotations
  1609. /// at the time a pointer is dereferenced.
  1610. /// FIXME: We need to check for other types of pointer dereferences
  1611. /// (e.g. [], ->) and deal with them here.
  1612. /// \param Exp An expression that has been read or written.
  1613. void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
  1614. UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
  1615. if (!UO || UO->getOpcode() != clang::UO_Deref)
  1616. return;
  1617. Exp = UO->getSubExpr()->IgnoreParenCasts();
  1618. const ValueDecl *D = getValueDecl(Exp);
  1619. if(!D || !D->hasAttrs())
  1620. return;
  1621. if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
  1622. Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
  1623. Exp->getExprLoc());
  1624. const AttrVec &ArgAttrs = D->getAttrs();
  1625. for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
  1626. if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
  1627. warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
  1628. }
  1629. /// \brief Checks guarded_by and guarded_var attributes.
  1630. /// Whenever we identify an access (read or write) of a DeclRefExpr or
  1631. /// MemberExpr, we need to check whether there are any guarded_by or
  1632. /// guarded_var attributes, and make sure we hold the appropriate mutexes.
  1633. void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
  1634. const ValueDecl *D = getValueDecl(Exp);
  1635. if(!D || !D->hasAttrs())
  1636. return;
  1637. if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
  1638. Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
  1639. Exp->getExprLoc());
  1640. const AttrVec &ArgAttrs = D->getAttrs();
  1641. for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
  1642. if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
  1643. warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
  1644. }
  1645. /// \brief Process a function call, method call, constructor call,
  1646. /// or destructor call. This involves looking at the attributes on the
  1647. /// corresponding function/method/constructor/destructor, issuing warnings,
  1648. /// and updating the locksets accordingly.
  1649. ///
  1650. /// FIXME: For classes annotated with one of the guarded annotations, we need
  1651. /// to treat const method calls as reads and non-const method calls as writes,
  1652. /// and check that the appropriate locks are held. Non-const method calls with
  1653. /// the same signature as const method calls can be also treated as reads.
  1654. ///
  1655. void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
  1656. const AttrVec &ArgAttrs = D->getAttrs();
  1657. MutexIDList ExclusiveLocksToAdd;
  1658. MutexIDList SharedLocksToAdd;
  1659. MutexIDList LocksToRemove;
  1660. for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
  1661. Attr *At = const_cast<Attr*>(ArgAttrs[i]);
  1662. switch (At->getKind()) {
  1663. // When we encounter an exclusive lock function, we need to add the lock
  1664. // to our lockset with kind exclusive.
  1665. case attr::ExclusiveLockFunction: {
  1666. ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
  1667. Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D, VD);
  1668. break;
  1669. }
  1670. // When we encounter a shared lock function, we need to add the lock
  1671. // to our lockset with kind shared.
  1672. case attr::SharedLockFunction: {
  1673. SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
  1674. Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D, VD);
  1675. break;
  1676. }
  1677. // When we encounter an unlock function, we need to remove unlocked
  1678. // mutexes from the lockset, and flag a warning if they are not there.
  1679. case attr::UnlockFunction: {
  1680. UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
  1681. Analyzer->getMutexIDs(LocksToRemove, A, Exp, D, VD);
  1682. break;
  1683. }
  1684. case attr::ExclusiveLocksRequired: {
  1685. ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
  1686. for (ExclusiveLocksRequiredAttr::args_iterator
  1687. I = A->args_begin(), E = A->args_end(); I != E; ++I)
  1688. warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
  1689. break;
  1690. }
  1691. case attr::SharedLocksRequired: {
  1692. SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
  1693. for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
  1694. E = A->args_end(); I != E; ++I)
  1695. warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
  1696. break;
  1697. }
  1698. case attr::LocksExcluded: {
  1699. LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
  1700. for (LocksExcludedAttr::args_iterator I = A->args_begin(),
  1701. E = A->args_end(); I != E; ++I) {
  1702. warnIfMutexHeld(D, Exp, *I);
  1703. }
  1704. break;
  1705. }
  1706. // Ignore other (non thread-safety) attributes
  1707. default:
  1708. break;
  1709. }
  1710. }
  1711. // Figure out if we're calling the constructor of scoped lockable class
  1712. bool isScopedVar = false;
  1713. if (VD) {
  1714. if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
  1715. const CXXRecordDecl* PD = CD->getParent();
  1716. if (PD && PD->getAttr<ScopedLockableAttr>())
  1717. isScopedVar = true;
  1718. }
  1719. }
  1720. // Add locks.
  1721. SourceLocation Loc = Exp->getExprLoc();
  1722. for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
  1723. Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
  1724. LockData(Loc, LK_Exclusive, isScopedVar));
  1725. }
  1726. for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
  1727. Analyzer->addLock(FSet, SharedLocksToAdd[i],
  1728. LockData(Loc, LK_Shared, isScopedVar));
  1729. }
  1730. // Add the managing object as a dummy mutex, mapped to the underlying mutex.
  1731. // FIXME -- this doesn't work if we acquire multiple locks.
  1732. if (isScopedVar) {
  1733. SourceLocation MLoc = VD->getLocation();
  1734. DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
  1735. SExpr SMutex(&DRE, 0, 0);
  1736. for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
  1737. Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
  1738. ExclusiveLocksToAdd[i]));
  1739. }
  1740. for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
  1741. Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
  1742. SharedLocksToAdd[i]));
  1743. }
  1744. }
  1745. // Remove locks.
  1746. // FIXME -- should only fully remove if the attribute refers to 'this'.
  1747. bool Dtor = isa<CXXDestructorDecl>(D);
  1748. for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
  1749. Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
  1750. }
  1751. }
  1752. /// \brief For unary operations which read and write a variable, we need to
  1753. /// check whether we hold any required mutexes. Reads are checked in
  1754. /// VisitCastExpr.
  1755. void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
  1756. switch (UO->getOpcode()) {
  1757. case clang::UO_PostDec:
  1758. case clang::UO_PostInc:
  1759. case clang::UO_PreDec:
  1760. case clang::UO_PreInc: {
  1761. Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
  1762. checkAccess(SubExp, AK_Written);
  1763. checkDereference(SubExp, AK_Written);
  1764. break;
  1765. }
  1766. default:
  1767. break;
  1768. }
  1769. }
  1770. /// For binary operations which assign to a variable (writes), we need to check
  1771. /// whether we hold any required mutexes.
  1772. /// FIXME: Deal with non-primitive types.
  1773. void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
  1774. if (!BO->isAssignmentOp())
  1775. return;
  1776. // adjust the context
  1777. LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
  1778. Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
  1779. checkAccess(LHSExp, AK_Written);
  1780. checkDereference(LHSExp, AK_Written);
  1781. }
  1782. /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
  1783. /// need to ensure we hold any required mutexes.
  1784. /// FIXME: Deal with non-primitive types.
  1785. void BuildLockset::VisitCastExpr(CastExpr *CE) {
  1786. if (CE->getCastKind() != CK_LValueToRValue)
  1787. return;
  1788. Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
  1789. checkAccess(SubExp, AK_Read);
  1790. checkDereference(SubExp, AK_Read);
  1791. }
  1792. void BuildLockset::VisitCallExpr(CallExpr *Exp) {
  1793. NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
  1794. if(!D || !D->hasAttrs())
  1795. return;
  1796. handleCall(Exp, D);
  1797. }
  1798. void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
  1799. // FIXME -- only handles constructors in DeclStmt below.
  1800. }
  1801. void BuildLockset::VisitDeclStmt(DeclStmt *S) {
  1802. // adjust the context
  1803. LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
  1804. DeclGroupRef DGrp = S->getDeclGroup();
  1805. for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
  1806. Decl *D = *I;
  1807. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
  1808. Expr *E = VD->getInit();
  1809. // handle constructors that involve temporaries
  1810. if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
  1811. E = EWC->getSubExpr();
  1812. if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
  1813. NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
  1814. if (!CtorD || !CtorD->hasAttrs())
  1815. return;
  1816. handleCall(CE, CtorD, VD);
  1817. }
  1818. }
  1819. }
  1820. }
  1821. /// \brief Compute the intersection of two locksets and issue warnings for any
  1822. /// locks in the symmetric difference.
  1823. ///
  1824. /// This function is used at a merge point in the CFG when comparing the lockset
  1825. /// of each branch being merged. For example, given the following sequence:
  1826. /// A; if () then B; else C; D; we need to check that the lockset after B and C
  1827. /// are the same. In the event of a difference, we use the intersection of these
  1828. /// two locksets at the start of D.
  1829. ///
  1830. /// \param FSet1 The first lockset.
  1831. /// \param FSet2 The second lockset.
  1832. /// \param JoinLoc The location of the join point for error reporting
  1833. /// \param LEK1 The error message to report if a mutex is missing from LSet1
  1834. /// \param LEK2 The error message to report if a mutex is missing from Lset2
  1835. void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
  1836. const FactSet &FSet2,
  1837. SourceLocation JoinLoc,
  1838. LockErrorKind LEK1,
  1839. LockErrorKind LEK2,
  1840. bool Modify) {
  1841. FactSet FSet1Orig = FSet1;
  1842. for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
  1843. I != E; ++I) {
  1844. const SExpr &FSet2Mutex = FactMan[*I].MutID;
  1845. const LockData &LDat2 = FactMan[*I].LDat;
  1846. if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
  1847. if (LDat1->LKind != LDat2.LKind) {
  1848. Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
  1849. LDat2.AcquireLoc,
  1850. LDat1->AcquireLoc);
  1851. if (Modify && LDat1->LKind != LK_Exclusive) {
  1852. FSet1.removeLock(FactMan, FSet2Mutex);
  1853. FSet1.addLock(FactMan, FSet2Mutex, LDat2);
  1854. }
  1855. }
  1856. } else {
  1857. if (LDat2.UnderlyingMutex.isValid()) {
  1858. if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
  1859. // If this is a scoped lock that manages another mutex, and if the
  1860. // underlying mutex is still held, then warn about the underlying
  1861. // mutex.
  1862. Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
  1863. LDat2.AcquireLoc,
  1864. JoinLoc, LEK1);
  1865. }
  1866. }
  1867. else if (!LDat2.Managed && !FSet2Mutex.isUniversal())
  1868. Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
  1869. LDat2.AcquireLoc,
  1870. JoinLoc, LEK1);
  1871. }
  1872. }
  1873. for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
  1874. I != E; ++I) {
  1875. const SExpr &FSet1Mutex = FactMan[*I].MutID;
  1876. const LockData &LDat1 = FactMan[*I].LDat;
  1877. if (!FSet2.findLock(FactMan, FSet1Mutex)) {
  1878. if (LDat1.UnderlyingMutex.isValid()) {
  1879. if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
  1880. // If this is a scoped lock that manages another mutex, and if the
  1881. // underlying mutex is still held, then warn about the underlying
  1882. // mutex.
  1883. Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
  1884. LDat1.AcquireLoc,
  1885. JoinLoc, LEK1);
  1886. }
  1887. }
  1888. else if (!LDat1.Managed && !FSet1Mutex.isUniversal())
  1889. Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
  1890. LDat1.AcquireLoc,
  1891. JoinLoc, LEK2);
  1892. if (Modify)
  1893. FSet1.removeLock(FactMan, FSet1Mutex);
  1894. }
  1895. }
  1896. }
  1897. /// \brief Check a function's CFG for thread-safety violations.
  1898. ///
  1899. /// We traverse the blocks in the CFG, compute the set of mutexes that are held
  1900. /// at the end of each block, and issue warnings for thread safety violations.
  1901. /// Each block in the CFG is traversed exactly once.
  1902. void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
  1903. CFG *CFGraph = AC.getCFG();
  1904. if (!CFGraph) return;
  1905. const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
  1906. // AC.dumpCFG(true);
  1907. if (!D)
  1908. return; // Ignore anonymous functions for now.
  1909. if (D->getAttr<NoThreadSafetyAnalysisAttr>())
  1910. return;
  1911. // FIXME: Do something a bit more intelligent inside constructor and
  1912. // destructor code. Constructors and destructors must assume unique access
  1913. // to 'this', so checks on member variable access is disabled, but we should
  1914. // still enable checks on other objects.
  1915. if (isa<CXXConstructorDecl>(D))
  1916. return; // Don't check inside constructors.
  1917. if (isa<CXXDestructorDecl>(D))
  1918. return; // Don't check inside destructors.
  1919. BlockInfo.resize(CFGraph->getNumBlockIDs(),
  1920. CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
  1921. // We need to explore the CFG via a "topological" ordering.
  1922. // That way, we will be guaranteed to have information about required
  1923. // predecessor locksets when exploring a new block.
  1924. PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
  1925. PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
  1926. // Mark entry block as reachable
  1927. BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
  1928. // Compute SSA names for local variables
  1929. LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
  1930. // Fill in source locations for all CFGBlocks.
  1931. findBlockLocations(CFGraph, SortedGraph, BlockInfo);
  1932. // Add locks from exclusive_locks_required and shared_locks_required
  1933. // to initial lockset. Also turn off checking for lock and unlock functions.
  1934. // FIXME: is there a more intelligent way to check lock/unlock functions?
  1935. if (!SortedGraph->empty() && D->hasAttrs()) {
  1936. const CFGBlock *FirstBlock = *SortedGraph->begin();
  1937. FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
  1938. const AttrVec &ArgAttrs = D->getAttrs();
  1939. MutexIDList ExclusiveLocksToAdd;
  1940. MutexIDList SharedLocksToAdd;
  1941. SourceLocation Loc = D->getLocation();
  1942. for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
  1943. Attr *Attr = ArgAttrs[i];
  1944. Loc = Attr->getLocation();
  1945. if (ExclusiveLocksRequiredAttr *A
  1946. = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
  1947. getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
  1948. } else if (SharedLocksRequiredAttr *A
  1949. = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
  1950. getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
  1951. } else if (isa<UnlockFunctionAttr>(Attr)) {
  1952. // Don't try to check unlock functions for now
  1953. return;
  1954. } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
  1955. // Don't try to check lock functions for now
  1956. return;
  1957. } else if (isa<SharedLockFunctionAttr>(Attr)) {
  1958. // Don't try to check lock functions for now
  1959. return;
  1960. } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
  1961. // Don't try to check trylock functions for now
  1962. return;
  1963. } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
  1964. // Don't try to check trylock functions for now
  1965. return;
  1966. }
  1967. }
  1968. // FIXME -- Loc can be wrong here.
  1969. for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
  1970. addLock(InitialLockset, ExclusiveLocksToAdd[i],
  1971. LockData(Loc, LK_Exclusive));
  1972. }
  1973. for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
  1974. addLock(InitialLockset, SharedLocksToAdd[i],
  1975. LockData(Loc, LK_Shared));
  1976. }
  1977. }
  1978. for (PostOrderCFGView::iterator I = SortedGraph->begin(),
  1979. E = SortedGraph->end(); I!= E; ++I) {
  1980. const CFGBlock *CurrBlock = *I;
  1981. int CurrBlockID = CurrBlock->getBlockID();
  1982. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
  1983. // Use the default initial lockset in case there are no predecessors.
  1984. VisitedBlocks.insert(CurrBlock);
  1985. // Iterate through the predecessor blocks and warn if the lockset for all
  1986. // predecessors is not the same. We take the entry lockset of the current
  1987. // block to be the intersection of all previous locksets.
  1988. // FIXME: By keeping the intersection, we may output more errors in future
  1989. // for a lock which is not in the intersection, but was in the union. We
  1990. // may want to also keep the union in future. As an example, let's say
  1991. // the intersection contains Mutex L, and the union contains L and M.
  1992. // Later we unlock M. At this point, we would output an error because we
  1993. // never locked M; although the real error is probably that we forgot to
  1994. // lock M on all code paths. Conversely, let's say that later we lock M.
  1995. // In this case, we should compare against the intersection instead of the
  1996. // union because the real error is probably that we forgot to unlock M on
  1997. // all code paths.
  1998. bool LocksetInitialized = false;
  1999. llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
  2000. for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  2001. PE = CurrBlock->pred_end(); PI != PE; ++PI) {
  2002. // if *PI -> CurrBlock is a back edge
  2003. if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
  2004. continue;
  2005. int PrevBlockID = (*PI)->getBlockID();
  2006. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  2007. // Ignore edges from blocks that can't return.
  2008. if ((*PI)->hasNoReturnElement() || !PrevBlockInfo->Reachable)
  2009. continue;
  2010. // Okay, we can reach this block from the entry.
  2011. CurrBlockInfo->Reachable = true;
  2012. // If the previous block ended in a 'continue' or 'break' statement, then
  2013. // a difference in locksets is probably due to a bug in that block, rather
  2014. // than in some other predecessor. In that case, keep the other
  2015. // predecessor's lockset.
  2016. if (const Stmt *Terminator = (*PI)->getTerminator()) {
  2017. if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
  2018. SpecialBlocks.push_back(*PI);
  2019. continue;
  2020. }
  2021. }
  2022. FactSet PrevLockset;
  2023. getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
  2024. if (!LocksetInitialized) {
  2025. CurrBlockInfo->EntrySet = PrevLockset;
  2026. LocksetInitialized = true;
  2027. } else {
  2028. intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
  2029. CurrBlockInfo->EntryLoc,
  2030. LEK_LockedSomePredecessors);
  2031. }
  2032. }
  2033. // Skip rest of block if it's not reachable.
  2034. if (!CurrBlockInfo->Reachable)
  2035. continue;
  2036. // Process continue and break blocks. Assume that the lockset for the
  2037. // resulting block is unaffected by any discrepancies in them.
  2038. for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
  2039. SpecialI < SpecialN; ++SpecialI) {
  2040. CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
  2041. int PrevBlockID = PrevBlock->getBlockID();
  2042. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  2043. if (!LocksetInitialized) {
  2044. CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
  2045. LocksetInitialized = true;
  2046. } else {
  2047. // Determine whether this edge is a loop terminator for diagnostic
  2048. // purposes. FIXME: A 'break' statement might be a loop terminator, but
  2049. // it might also be part of a switch. Also, a subsequent destructor
  2050. // might add to the lockset, in which case the real issue might be a
  2051. // double lock on the other path.
  2052. const Stmt *Terminator = PrevBlock->getTerminator();
  2053. bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
  2054. FactSet PrevLockset;
  2055. getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
  2056. PrevBlock, CurrBlock);
  2057. // Do not update EntrySet.
  2058. intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
  2059. PrevBlockInfo->ExitLoc,
  2060. IsLoop ? LEK_LockedSomeLoopIterations
  2061. : LEK_LockedSomePredecessors,
  2062. false);
  2063. }
  2064. }
  2065. BuildLockset LocksetBuilder(this, *CurrBlockInfo);
  2066. // Visit all the statements in the basic block.
  2067. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  2068. BE = CurrBlock->end(); BI != BE; ++BI) {
  2069. switch (BI->getKind()) {
  2070. case CFGElement::Statement: {
  2071. const CFGStmt *CS = cast<CFGStmt>(&*BI);
  2072. LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
  2073. break;
  2074. }
  2075. // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
  2076. case CFGElement::AutomaticObjectDtor: {
  2077. const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
  2078. CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
  2079. AD->getDestructorDecl(AC.getASTContext()));
  2080. if (!DD->hasAttrs())
  2081. break;
  2082. // Create a dummy expression,
  2083. VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
  2084. DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
  2085. AD->getTriggerStmt()->getLocEnd());
  2086. LocksetBuilder.handleCall(&DRE, DD);
  2087. break;
  2088. }
  2089. default:
  2090. break;
  2091. }
  2092. }
  2093. CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
  2094. // For every back edge from CurrBlock (the end of the loop) to another block
  2095. // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
  2096. // the one held at the beginning of FirstLoopBlock. We can look up the
  2097. // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
  2098. for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
  2099. SE = CurrBlock->succ_end(); SI != SE; ++SI) {
  2100. // if CurrBlock -> *SI is *not* a back edge
  2101. if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
  2102. continue;
  2103. CFGBlock *FirstLoopBlock = *SI;
  2104. CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
  2105. CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
  2106. intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
  2107. PreLoop->EntryLoc,
  2108. LEK_LockedSomeLoopIterations,
  2109. false);
  2110. }
  2111. }
  2112. CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
  2113. CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
  2114. // Skip the final check if the exit block is unreachable.
  2115. if (!Final->Reachable)
  2116. return;
  2117. // FIXME: Should we call this function for all blocks which exit the function?
  2118. intersectAndWarn(Initial->EntrySet, Final->ExitSet,
  2119. Final->ExitLoc,
  2120. LEK_LockedAtEndOfFunction,
  2121. LEK_NotLockedAtEndOfFunction,
  2122. false);
  2123. }
  2124. } // end anonymous namespace
  2125. namespace clang {
  2126. namespace thread_safety {
  2127. /// \brief Check a function's CFG for thread-safety violations.
  2128. ///
  2129. /// We traverse the blocks in the CFG, compute the set of mutexes that are held
  2130. /// at the end of each block, and issue warnings for thread safety violations.
  2131. /// Each block in the CFG is traversed exactly once.
  2132. void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
  2133. ThreadSafetyHandler &Handler) {
  2134. ThreadSafetyAnalyzer Analyzer(Handler);
  2135. Analyzer.runAnalysis(AC);
  2136. }
  2137. /// \brief Helper function that returns a LockKind required for the given level
  2138. /// of access.
  2139. LockKind getLockKindFromAccessKind(AccessKind AK) {
  2140. switch (AK) {
  2141. case AK_Read :
  2142. return LK_Shared;
  2143. case AK_Written :
  2144. return LK_Exclusive;
  2145. }
  2146. llvm_unreachable("Unknown AccessKind");
  2147. }
  2148. }} // end namespace clang::thread_safety