ThreadSafety.cpp 85 KB

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