ThreadSafety.cpp 90 KB

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