ThreadSafety.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. //===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // A intra-procedural analysis for thread safety (e.g. deadlocks and race
  11. // conditions), based off of an annotation system.
  12. //
  13. // See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
  14. // information.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/Analysis/Analyses/ThreadSafety.h"
  18. #include "clang/Analysis/Analyses/PostOrderCFGView.h"
  19. #include "clang/Analysis/AnalysisContext.h"
  20. #include "clang/Analysis/CFG.h"
  21. #include "clang/Analysis/CFGStmtMap.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/AST/StmtVisitor.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/SourceLocation.h"
  28. #include "llvm/ADT/BitVector.h"
  29. #include "llvm/ADT/FoldingSet.h"
  30. #include "llvm/ADT/ImmutableMap.h"
  31. #include "llvm/ADT/PostOrderIterator.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/StringRef.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <algorithm>
  36. #include <utility>
  37. #include <vector>
  38. using namespace clang;
  39. using namespace thread_safety;
  40. // Key method definition
  41. ThreadSafetyHandler::~ThreadSafetyHandler() {}
  42. namespace {
  43. /// \brief A MutexID object uniquely identifies a particular mutex, and
  44. /// is built from an Expr* (i.e. calling a lock function).
  45. ///
  46. /// Thread-safety analysis works by comparing lock expressions. Within the
  47. /// body of a function, an expression such as "x->foo->bar.mu" will resolve to
  48. /// a particular mutex object at run-time. Subsequent occurrences of the same
  49. /// expression (where "same" means syntactic equality) will refer to the same
  50. /// run-time object if three conditions hold:
  51. /// (1) Local variables in the expression, such as "x" have not changed.
  52. /// (2) Values on the heap that affect the expression have not changed.
  53. /// (3) The expression involves only pure function calls.
  54. ///
  55. /// The current implementation assumes, but does not verify, that multiple uses
  56. /// of the same lock expression satisfies these criteria.
  57. ///
  58. /// Clang introduces an additional wrinkle, which is that it is difficult to
  59. /// derive canonical expressions, or compare expressions directly for equality.
  60. /// Thus, we identify a mutex not by an Expr, but by the set of named
  61. /// declarations that are referenced by the Expr. In other words,
  62. /// x->foo->bar.mu will be a four element vector with the Decls for
  63. /// mu, bar, and foo, and x. The vector will uniquely identify the expression
  64. /// for all practical purposes.
  65. ///
  66. /// Note we will need to perform substitution on "this" and function parameter
  67. /// names when constructing a lock expression.
  68. ///
  69. /// For example:
  70. /// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
  71. /// void myFunc(C *X) { ... X->lock() ... }
  72. /// The original expression for the mutex acquired by myFunc is "this->Mu", but
  73. /// "X" is substituted for "this" so we get X->Mu();
  74. ///
  75. /// For another example:
  76. /// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
  77. /// MyList *MyL;
  78. /// foo(MyL); // requires lock MyL->Mu to be held
  79. class MutexID {
  80. SmallVector<NamedDecl*, 2> DeclSeq;
  81. /// Build a Decl sequence representing the lock from the given expression.
  82. /// Recursive function that terminates on DeclRefExpr.
  83. /// Note: this function merely creates a MutexID; it does not check to
  84. /// ensure that the original expression is a valid mutex expression.
  85. void buildMutexID(Expr *Exp, const NamedDecl *D, Expr *Parent,
  86. unsigned NumArgs, Expr **FunArgs) {
  87. if (!Exp) {
  88. DeclSeq.clear();
  89. return;
  90. }
  91. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
  92. NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  93. ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
  94. if (PV) {
  95. FunctionDecl *FD =
  96. cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
  97. unsigned i = PV->getFunctionScopeIndex();
  98. if (FunArgs && FD == D->getCanonicalDecl()) {
  99. // Substitute call arguments for references to function parameters
  100. assert(i < NumArgs);
  101. buildMutexID(FunArgs[i], D, 0, 0, 0);
  102. return;
  103. }
  104. // Map the param back to the param of the original function declaration.
  105. DeclSeq.push_back(FD->getParamDecl(i));
  106. return;
  107. }
  108. // Not a function parameter -- just store the reference.
  109. DeclSeq.push_back(ND);
  110. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
  111. NamedDecl *ND = ME->getMemberDecl();
  112. DeclSeq.push_back(ND);
  113. buildMutexID(ME->getBase(), D, Parent, NumArgs, FunArgs);
  114. } else if (isa<CXXThisExpr>(Exp)) {
  115. if (Parent)
  116. buildMutexID(Parent, D, 0, 0, 0);
  117. else
  118. return; // mutexID is still valid in this case
  119. } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp))
  120. buildMutexID(UOE->getSubExpr(), D, Parent, NumArgs, FunArgs);
  121. else if (CastExpr *CE = dyn_cast<CastExpr>(Exp))
  122. buildMutexID(CE->getSubExpr(), D, Parent, NumArgs, FunArgs);
  123. else
  124. DeclSeq.clear(); // Mark as invalid lock expression.
  125. }
  126. /// \brief Construct a MutexID from an expression.
  127. /// \param MutexExp The original mutex expression within an attribute
  128. /// \param DeclExp An expression involving the Decl on which the attribute
  129. /// occurs.
  130. /// \param D The declaration to which the lock/unlock attribute is attached.
  131. void buildMutexIDFromExp(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
  132. Expr *Parent = 0;
  133. unsigned NumArgs = 0;
  134. Expr **FunArgs = 0;
  135. // If we are processing a raw attribute expression, with no substitutions.
  136. if (DeclExp == 0) {
  137. buildMutexID(MutexExp, D, 0, 0, 0);
  138. return;
  139. }
  140. // Examine DeclExp to find Parent and FunArgs, which are used to substitute
  141. // for formal parameters when we call buildMutexID later.
  142. if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
  143. Parent = ME->getBase();
  144. } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
  145. Parent = CE->getImplicitObjectArgument();
  146. NumArgs = CE->getNumArgs();
  147. FunArgs = CE->getArgs();
  148. } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
  149. NumArgs = CE->getNumArgs();
  150. FunArgs = CE->getArgs();
  151. } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
  152. Parent = 0; // FIXME -- get the parent from DeclStmt
  153. NumArgs = CE->getNumArgs();
  154. FunArgs = CE->getArgs();
  155. } else if (D && isa<CXXDestructorDecl>(D)) {
  156. // There's no such thing as a "destructor call" in the AST.
  157. Parent = DeclExp;
  158. }
  159. // If the attribute has no arguments, then assume the argument is "this".
  160. if (MutexExp == 0) {
  161. buildMutexID(Parent, D, 0, 0, 0);
  162. return;
  163. }
  164. buildMutexID(MutexExp, D, Parent, NumArgs, FunArgs);
  165. }
  166. public:
  167. explicit MutexID(clang::Decl::EmptyShell e) {
  168. DeclSeq.clear();
  169. }
  170. /// \param MutexExp The original mutex expression within an attribute
  171. /// \param DeclExp An expression involving the Decl on which the attribute
  172. /// occurs.
  173. /// \param D The declaration to which the lock/unlock attribute is attached.
  174. /// Caller must check isValid() after construction.
  175. MutexID(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
  176. buildMutexIDFromExp(MutexExp, DeclExp, D);
  177. }
  178. /// Return true if this is a valid decl sequence.
  179. /// Caller must call this by hand after construction to handle errors.
  180. bool isValid() const {
  181. return !DeclSeq.empty();
  182. }
  183. /// Issue a warning about an invalid lock expression
  184. static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
  185. Expr *DeclExp, const NamedDecl* D) {
  186. SourceLocation Loc;
  187. if (DeclExp)
  188. Loc = DeclExp->getExprLoc();
  189. // FIXME: add a note about the attribute location in MutexExp or D
  190. if (Loc.isValid())
  191. Handler.handleInvalidLockExp(Loc);
  192. }
  193. bool operator==(const MutexID &other) const {
  194. return DeclSeq == other.DeclSeq;
  195. }
  196. bool operator!=(const MutexID &other) const {
  197. return !(*this == other);
  198. }
  199. // SmallVector overloads Operator< to do lexicographic ordering. Note that
  200. // we use pointer equality (and <) to compare NamedDecls. This means the order
  201. // of MutexIDs in a lockset is nondeterministic. In order to output
  202. // diagnostics in a deterministic ordering, we must order all diagnostics to
  203. // output by SourceLocation when iterating through this lockset.
  204. bool operator<(const MutexID &other) const {
  205. return DeclSeq < other.DeclSeq;
  206. }
  207. /// \brief Returns the name of the first Decl in the list for a given MutexID;
  208. /// e.g. the lock expression foo.bar() has name "bar".
  209. /// The caret will point unambiguously to the lock expression, so using this
  210. /// name in diagnostics is a way to get simple, and consistent, mutex names.
  211. /// We do not want to output the entire expression text for security reasons.
  212. StringRef getName() const {
  213. assert(isValid());
  214. return DeclSeq.front()->getName();
  215. }
  216. void Profile(llvm::FoldingSetNodeID &ID) const {
  217. for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
  218. E = DeclSeq.end(); I != E; ++I) {
  219. ID.AddPointer(*I);
  220. }
  221. }
  222. };
  223. /// \brief This is a helper class that stores info about the most recent
  224. /// accquire of a Lock.
  225. ///
  226. /// The main body of the analysis maps MutexIDs to LockDatas.
  227. struct LockData {
  228. SourceLocation AcquireLoc;
  229. /// \brief LKind stores whether a lock is held shared or exclusively.
  230. /// Note that this analysis does not currently support either re-entrant
  231. /// locking or lock "upgrading" and "downgrading" between exclusive and
  232. /// shared.
  233. ///
  234. /// FIXME: add support for re-entrant locking and lock up/downgrading
  235. LockKind LKind;
  236. MutexID UnderlyingMutex; // for ScopedLockable objects
  237. LockData(SourceLocation AcquireLoc, LockKind LKind)
  238. : AcquireLoc(AcquireLoc), LKind(LKind), UnderlyingMutex(Decl::EmptyShell())
  239. {}
  240. LockData(SourceLocation AcquireLoc, LockKind LKind, const MutexID &Mu)
  241. : AcquireLoc(AcquireLoc), LKind(LKind), UnderlyingMutex(Mu) {}
  242. bool operator==(const LockData &other) const {
  243. return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
  244. }
  245. bool operator!=(const LockData &other) const {
  246. return !(*this == other);
  247. }
  248. void Profile(llvm::FoldingSetNodeID &ID) const {
  249. ID.AddInteger(AcquireLoc.getRawEncoding());
  250. ID.AddInteger(LKind);
  251. }
  252. };
  253. /// A Lockset maps each MutexID (defined above) to information about how it has
  254. /// been locked.
  255. typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
  256. typedef llvm::ImmutableMap<NamedDecl*, unsigned> LocalVarContext;
  257. class LocalVariableMap;
  258. /// A side (entry or exit) of a CFG node.
  259. enum CFGBlockSide { CBS_Entry, CBS_Exit };
  260. /// CFGBlockInfo is a struct which contains all the information that is
  261. /// maintained for each block in the CFG. See LocalVariableMap for more
  262. /// information about the contexts.
  263. struct CFGBlockInfo {
  264. Lockset EntrySet; // Lockset held at entry to block
  265. Lockset ExitSet; // Lockset held at exit from block
  266. LocalVarContext EntryContext; // Context held at entry to block
  267. LocalVarContext ExitContext; // Context held at exit from block
  268. SourceLocation EntryLoc; // Location of first statement in block
  269. SourceLocation ExitLoc; // Location of last statement in block.
  270. unsigned EntryIndex; // Used to replay contexts later
  271. const Lockset &getSet(CFGBlockSide Side) const {
  272. return Side == CBS_Entry ? EntrySet : ExitSet;
  273. }
  274. SourceLocation getLocation(CFGBlockSide Side) const {
  275. return Side == CBS_Entry ? EntryLoc : ExitLoc;
  276. }
  277. private:
  278. CFGBlockInfo(Lockset EmptySet, LocalVarContext EmptyCtx)
  279. : EntrySet(EmptySet), ExitSet(EmptySet),
  280. EntryContext(EmptyCtx), ExitContext(EmptyCtx)
  281. { }
  282. public:
  283. static CFGBlockInfo getEmptyBlockInfo(Lockset::Factory &F,
  284. LocalVariableMap &M);
  285. };
  286. // A LocalVariableMap maintains a map from local variables to their currently
  287. // valid definitions. It provides SSA-like functionality when traversing the
  288. // CFG. Like SSA, each definition or assignment to a variable is assigned a
  289. // unique name (an integer), which acts as the SSA name for that definition.
  290. // The total set of names is shared among all CFG basic blocks.
  291. // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
  292. // with their SSA-names. Instead, we compute a Context for each point in the
  293. // code, which maps local variables to the appropriate SSA-name. This map
  294. // changes with each assignment.
  295. //
  296. // The map is computed in a single pass over the CFG. Subsequent analyses can
  297. // then query the map to find the appropriate Context for a statement, and use
  298. // that Context to look up the definitions of variables.
  299. class LocalVariableMap {
  300. public:
  301. typedef LocalVarContext Context;
  302. /// A VarDefinition consists of an expression, representing the value of the
  303. /// variable, along with the context in which that expression should be
  304. /// interpreted. A reference VarDefinition does not itself contain this
  305. /// information, but instead contains a pointer to a previous VarDefinition.
  306. struct VarDefinition {
  307. public:
  308. friend class LocalVariableMap;
  309. NamedDecl *Dec; // The original declaration for this variable.
  310. Expr *Exp; // The expression for this variable, OR
  311. unsigned Ref; // Reference to another VarDefinition
  312. Context Ctx; // The map with which Exp should be interpreted.
  313. bool isReference() { return !Exp; }
  314. private:
  315. // Create ordinary variable definition
  316. VarDefinition(NamedDecl *D, Expr *E, Context C)
  317. : Dec(D), Exp(E), Ref(0), Ctx(C)
  318. { }
  319. // Create reference to previous definition
  320. VarDefinition(NamedDecl *D, unsigned R, Context C)
  321. : Dec(D), Exp(0), Ref(R), Ctx(C)
  322. { }
  323. };
  324. private:
  325. Context::Factory ContextFactory;
  326. std::vector<VarDefinition> VarDefinitions;
  327. std::vector<unsigned> CtxIndices;
  328. std::vector<std::pair<Stmt*, Context> > SavedContexts;
  329. public:
  330. LocalVariableMap() {
  331. // index 0 is a placeholder for undefined variables (aka phi-nodes).
  332. VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
  333. }
  334. /// Look up a definition, within the given context.
  335. const VarDefinition* lookup(NamedDecl *D, Context Ctx) {
  336. const unsigned *i = Ctx.lookup(D);
  337. if (!i)
  338. return 0;
  339. assert(*i < VarDefinitions.size());
  340. return &VarDefinitions[*i];
  341. }
  342. /// Look up the definition for D within the given context. Returns
  343. /// NULL if the expression is not statically known. If successful, also
  344. /// modifies Ctx to hold the context of the return Expr.
  345. Expr* lookupExpr(NamedDecl *D, Context &Ctx) {
  346. const unsigned *P = Ctx.lookup(D);
  347. if (!P)
  348. return 0;
  349. unsigned i = *P;
  350. while (i > 0) {
  351. if (VarDefinitions[i].Exp) {
  352. Ctx = VarDefinitions[i].Ctx;
  353. return VarDefinitions[i].Exp;
  354. }
  355. i = VarDefinitions[i].Ref;
  356. }
  357. return 0;
  358. }
  359. Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
  360. /// Return the next context after processing S. This function is used by
  361. /// clients of the class to get the appropriate context when traversing the
  362. /// CFG. It must be called for every assignment or DeclStmt.
  363. Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
  364. if (SavedContexts[CtxIndex+1].first == S) {
  365. CtxIndex++;
  366. Context Result = SavedContexts[CtxIndex].second;
  367. return Result;
  368. }
  369. return C;
  370. }
  371. void dumpVarDefinitionName(unsigned i) {
  372. if (i == 0) {
  373. llvm::errs() << "Undefined";
  374. return;
  375. }
  376. NamedDecl *Dec = VarDefinitions[i].Dec;
  377. if (!Dec) {
  378. llvm::errs() << "<<NULL>>";
  379. return;
  380. }
  381. Dec->printName(llvm::errs());
  382. llvm::errs() << "." << i << " " << ((void*) Dec);
  383. }
  384. /// Dumps an ASCII representation of the variable map to llvm::errs()
  385. void dump() {
  386. for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
  387. Expr *Exp = VarDefinitions[i].Exp;
  388. unsigned Ref = VarDefinitions[i].Ref;
  389. dumpVarDefinitionName(i);
  390. llvm::errs() << " = ";
  391. if (Exp) Exp->dump();
  392. else {
  393. dumpVarDefinitionName(Ref);
  394. llvm::errs() << "\n";
  395. }
  396. }
  397. }
  398. /// Dumps an ASCII representation of a Context to llvm::errs()
  399. void dumpContext(Context C) {
  400. for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
  401. NamedDecl *D = I.getKey();
  402. D->printName(llvm::errs());
  403. const unsigned *i = C.lookup(D);
  404. llvm::errs() << " -> ";
  405. dumpVarDefinitionName(*i);
  406. llvm::errs() << "\n";
  407. }
  408. }
  409. /// Builds the variable map.
  410. void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
  411. std::vector<CFGBlockInfo> &BlockInfo);
  412. protected:
  413. // Get the current context index
  414. unsigned getContextIndex() { return SavedContexts.size()-1; }
  415. // Save the current context for later replay
  416. void saveContext(Stmt *S, Context C) {
  417. SavedContexts.push_back(std::make_pair(S,C));
  418. }
  419. // Adds a new definition to the given context, and returns a new context.
  420. // This method should be called when declaring a new variable.
  421. Context addDefinition(NamedDecl *D, Expr *Exp, Context Ctx) {
  422. assert(!Ctx.contains(D));
  423. unsigned newID = VarDefinitions.size();
  424. Context NewCtx = ContextFactory.add(Ctx, D, newID);
  425. VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
  426. return NewCtx;
  427. }
  428. // Add a new reference to an existing definition.
  429. Context addReference(NamedDecl *D, unsigned i, Context Ctx) {
  430. unsigned newID = VarDefinitions.size();
  431. Context NewCtx = ContextFactory.add(Ctx, D, newID);
  432. VarDefinitions.push_back(VarDefinition(D, i, Ctx));
  433. return NewCtx;
  434. }
  435. // Updates a definition only if that definition is already in the map.
  436. // This method should be called when assigning to an existing variable.
  437. Context updateDefinition(NamedDecl *D, Expr *Exp, Context Ctx) {
  438. if (Ctx.contains(D)) {
  439. unsigned newID = VarDefinitions.size();
  440. Context NewCtx = ContextFactory.remove(Ctx, D);
  441. NewCtx = ContextFactory.add(NewCtx, D, newID);
  442. VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
  443. return NewCtx;
  444. }
  445. return Ctx;
  446. }
  447. // Removes a definition from the context, but keeps the variable name
  448. // as a valid variable. The index 0 is a placeholder for cleared definitions.
  449. Context clearDefinition(NamedDecl *D, Context Ctx) {
  450. Context NewCtx = Ctx;
  451. if (NewCtx.contains(D)) {
  452. NewCtx = ContextFactory.remove(NewCtx, D);
  453. NewCtx = ContextFactory.add(NewCtx, D, 0);
  454. }
  455. return NewCtx;
  456. }
  457. // Remove a definition entirely frmo the context.
  458. Context removeDefinition(NamedDecl *D, Context Ctx) {
  459. Context NewCtx = Ctx;
  460. if (NewCtx.contains(D)) {
  461. NewCtx = ContextFactory.remove(NewCtx, D);
  462. }
  463. return NewCtx;
  464. }
  465. Context intersectContexts(Context C1, Context C2);
  466. Context createReferenceContext(Context C);
  467. void intersectBackEdge(Context C1, Context C2);
  468. friend class VarMapBuilder;
  469. };
  470. // This has to be defined after LocalVariableMap.
  471. CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(Lockset::Factory &F,
  472. LocalVariableMap &M) {
  473. return CFGBlockInfo(F.getEmptyMap(), M.getEmptyContext());
  474. }
  475. /// Visitor which builds a LocalVariableMap
  476. class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
  477. public:
  478. LocalVariableMap* VMap;
  479. LocalVariableMap::Context Ctx;
  480. VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
  481. : VMap(VM), Ctx(C) {}
  482. void VisitDeclStmt(DeclStmt *S);
  483. void VisitBinaryOperator(BinaryOperator *BO);
  484. };
  485. // Add new local variables to the variable map
  486. void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
  487. bool modifiedCtx = false;
  488. DeclGroupRef DGrp = S->getDeclGroup();
  489. for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
  490. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
  491. Expr *E = VD->getInit();
  492. // Add local variables with trivial type to the variable map
  493. QualType T = VD->getType();
  494. if (T.isTrivialType(VD->getASTContext())) {
  495. Ctx = VMap->addDefinition(VD, E, Ctx);
  496. modifiedCtx = true;
  497. }
  498. }
  499. }
  500. if (modifiedCtx)
  501. VMap->saveContext(S, Ctx);
  502. }
  503. // Update local variable definitions in variable map
  504. void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
  505. if (!BO->isAssignmentOp())
  506. return;
  507. Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
  508. // Update the variable map and current context.
  509. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
  510. ValueDecl *VDec = DRE->getDecl();
  511. if (Ctx.lookup(VDec)) {
  512. if (BO->getOpcode() == BO_Assign)
  513. Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
  514. else
  515. // FIXME -- handle compound assignment operators
  516. Ctx = VMap->clearDefinition(VDec, Ctx);
  517. VMap->saveContext(BO, Ctx);
  518. }
  519. }
  520. }
  521. // Computes the intersection of two contexts. The intersection is the
  522. // set of variables which have the same definition in both contexts;
  523. // variables with different definitions are discarded.
  524. LocalVariableMap::Context
  525. LocalVariableMap::intersectContexts(Context C1, Context C2) {
  526. Context Result = C1;
  527. for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
  528. NamedDecl *Dec = I.getKey();
  529. unsigned i1 = I.getData();
  530. const unsigned *i2 = C2.lookup(Dec);
  531. if (!i2) // variable doesn't exist on second path
  532. Result = removeDefinition(Dec, Result);
  533. else if (*i2 != i1) // variable exists, but has different definition
  534. Result = clearDefinition(Dec, Result);
  535. }
  536. return Result;
  537. }
  538. // For every variable in C, create a new variable that refers to the
  539. // definition in C. Return a new context that contains these new variables.
  540. // (We use this for a naive implementation of SSA on loop back-edges.)
  541. LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
  542. Context Result = getEmptyContext();
  543. for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
  544. NamedDecl *Dec = I.getKey();
  545. unsigned i = I.getData();
  546. Result = addReference(Dec, i, Result);
  547. }
  548. return Result;
  549. }
  550. // This routine also takes the intersection of C1 and C2, but it does so by
  551. // altering the VarDefinitions. C1 must be the result of an earlier call to
  552. // createReferenceContext.
  553. void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
  554. for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
  555. NamedDecl *Dec = I.getKey();
  556. unsigned i1 = I.getData();
  557. VarDefinition *VDef = &VarDefinitions[i1];
  558. assert(VDef->isReference());
  559. const unsigned *i2 = C2.lookup(Dec);
  560. if (!i2 || (*i2 != i1))
  561. VDef->Ref = 0; // Mark this variable as undefined
  562. }
  563. }
  564. // Traverse the CFG in topological order, so all predecessors of a block
  565. // (excluding back-edges) are visited before the block itself. At
  566. // each point in the code, we calculate a Context, which holds the set of
  567. // variable definitions which are visible at that point in execution.
  568. // Visible variables are mapped to their definitions using an array that
  569. // contains all definitions.
  570. //
  571. // At join points in the CFG, the set is computed as the intersection of
  572. // the incoming sets along each edge, E.g.
  573. //
  574. // { Context | VarDefinitions }
  575. // int x = 0; { x -> x1 | x1 = 0 }
  576. // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
  577. // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
  578. // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
  579. // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
  580. //
  581. // This is essentially a simpler and more naive version of the standard SSA
  582. // algorithm. Those definitions that remain in the intersection are from blocks
  583. // that strictly dominate the current block. We do not bother to insert proper
  584. // phi nodes, because they are not used in our analysis; instead, wherever
  585. // a phi node would be required, we simply remove that definition from the
  586. // context (E.g. x above).
  587. //
  588. // The initial traversal does not capture back-edges, so those need to be
  589. // handled on a separate pass. Whenever the first pass encounters an
  590. // incoming back edge, it duplicates the context, creating new definitions
  591. // that refer back to the originals. (These correspond to places where SSA
  592. // might have to insert a phi node.) On the second pass, these definitions are
  593. // set to NULL if the the variable has changed on the back-edge (i.e. a phi
  594. // node was actually required.) E.g.
  595. //
  596. // { Context | VarDefinitions }
  597. // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
  598. // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
  599. // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
  600. // ... { y -> y1 | x3 = 2, x2 = 1, ... }
  601. //
  602. void LocalVariableMap::traverseCFG(CFG *CFGraph,
  603. PostOrderCFGView *SortedGraph,
  604. std::vector<CFGBlockInfo> &BlockInfo) {
  605. PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
  606. CtxIndices.resize(CFGraph->getNumBlockIDs());
  607. for (PostOrderCFGView::iterator I = SortedGraph->begin(),
  608. E = SortedGraph->end(); I!= E; ++I) {
  609. const CFGBlock *CurrBlock = *I;
  610. int CurrBlockID = CurrBlock->getBlockID();
  611. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
  612. VisitedBlocks.insert(CurrBlock);
  613. // Calculate the entry context for the current block
  614. bool HasBackEdges = false;
  615. bool CtxInit = true;
  616. for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  617. PE = CurrBlock->pred_end(); PI != PE; ++PI) {
  618. // if *PI -> CurrBlock is a back edge, so skip it
  619. if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
  620. HasBackEdges = true;
  621. continue;
  622. }
  623. int PrevBlockID = (*PI)->getBlockID();
  624. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  625. if (CtxInit) {
  626. CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
  627. CtxInit = false;
  628. }
  629. else {
  630. CurrBlockInfo->EntryContext =
  631. intersectContexts(CurrBlockInfo->EntryContext,
  632. PrevBlockInfo->ExitContext);
  633. }
  634. }
  635. // Duplicate the context if we have back-edges, so we can call
  636. // intersectBackEdges later.
  637. if (HasBackEdges)
  638. CurrBlockInfo->EntryContext =
  639. createReferenceContext(CurrBlockInfo->EntryContext);
  640. // Create a starting context index for the current block
  641. saveContext(0, CurrBlockInfo->EntryContext);
  642. CurrBlockInfo->EntryIndex = getContextIndex();
  643. // Visit all the statements in the basic block.
  644. VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
  645. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  646. BE = CurrBlock->end(); BI != BE; ++BI) {
  647. switch (BI->getKind()) {
  648. case CFGElement::Statement: {
  649. const CFGStmt *CS = cast<CFGStmt>(&*BI);
  650. VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
  651. break;
  652. }
  653. default:
  654. break;
  655. }
  656. }
  657. CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
  658. // Mark variables on back edges as "unknown" if they've been changed.
  659. for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
  660. SE = CurrBlock->succ_end(); SI != SE; ++SI) {
  661. // if CurrBlock -> *SI is *not* a back edge
  662. if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
  663. continue;
  664. CFGBlock *FirstLoopBlock = *SI;
  665. Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
  666. Context LoopEnd = CurrBlockInfo->ExitContext;
  667. intersectBackEdge(LoopBegin, LoopEnd);
  668. }
  669. }
  670. // Put an extra entry at the end of the indexed context array
  671. unsigned exitID = CFGraph->getExit().getBlockID();
  672. saveContext(0, BlockInfo[exitID].ExitContext);
  673. }
  674. /// Find the appropriate source locations to use when producing diagnostics for
  675. /// each block in the CFG.
  676. static void findBlockLocations(CFG *CFGraph,
  677. PostOrderCFGView *SortedGraph,
  678. std::vector<CFGBlockInfo> &BlockInfo) {
  679. for (PostOrderCFGView::iterator I = SortedGraph->begin(),
  680. E = SortedGraph->end(); I!= E; ++I) {
  681. const CFGBlock *CurrBlock = *I;
  682. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
  683. // Find the source location of the last statement in the block, if the
  684. // block is not empty.
  685. if (const Stmt *S = CurrBlock->getTerminator()) {
  686. CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
  687. } else {
  688. for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
  689. BE = CurrBlock->rend(); BI != BE; ++BI) {
  690. // FIXME: Handle other CFGElement kinds.
  691. if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
  692. CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
  693. break;
  694. }
  695. }
  696. }
  697. if (!CurrBlockInfo->ExitLoc.isInvalid()) {
  698. // This block contains at least one statement. Find the source location
  699. // of the first statement in the block.
  700. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  701. BE = CurrBlock->end(); BI != BE; ++BI) {
  702. // FIXME: Handle other CFGElement kinds.
  703. if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
  704. CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
  705. break;
  706. }
  707. }
  708. } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
  709. CurrBlock != &CFGraph->getExit()) {
  710. // The block is empty, and has a single predecessor. Use its exit
  711. // location.
  712. CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
  713. BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
  714. }
  715. }
  716. }
  717. /// \brief Class which implements the core thread safety analysis routines.
  718. class ThreadSafetyAnalyzer {
  719. friend class BuildLockset;
  720. ThreadSafetyHandler &Handler;
  721. Lockset::Factory LocksetFactory;
  722. LocalVariableMap LocalVarMap;
  723. public:
  724. ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
  725. Lockset intersectAndWarn(const CFGBlockInfo &Block1, CFGBlockSide Side1,
  726. const CFGBlockInfo &Block2, CFGBlockSide Side2,
  727. LockErrorKind LEK);
  728. Lockset addLock(Lockset &LSet, Expr *MutexExp, const NamedDecl *D,
  729. LockKind LK, SourceLocation Loc);
  730. void runAnalysis(AnalysisDeclContext &AC);
  731. };
  732. /// \brief We use this class to visit different types of expressions in
  733. /// CFGBlocks, and build up the lockset.
  734. /// An expression may cause us to add or remove locks from the lockset, or else
  735. /// output error messages related to missing locks.
  736. /// FIXME: In future, we may be able to not inherit from a visitor.
  737. class BuildLockset : public StmtVisitor<BuildLockset> {
  738. friend class ThreadSafetyAnalyzer;
  739. ThreadSafetyHandler &Handler;
  740. Lockset::Factory &LocksetFactory;
  741. LocalVariableMap &LocalVarMap;
  742. Lockset LSet;
  743. LocalVariableMap::Context LVarCtx;
  744. unsigned CtxIndex;
  745. // Helper functions
  746. void addLock(const MutexID &Mutex, const LockData &LDat);
  747. void removeLock(const MutexID &Mutex, SourceLocation UnlockLoc);
  748. template <class AttrType>
  749. void addLocksToSet(LockKind LK, AttrType *Attr,
  750. Expr *Exp, NamedDecl *D, VarDecl *VD = 0);
  751. void removeLocksFromSet(UnlockFunctionAttr *Attr,
  752. Expr *Exp, NamedDecl* FunDecl);
  753. const ValueDecl *getValueDecl(Expr *Exp);
  754. void warnIfMutexNotHeld (const NamedDecl *D, Expr *Exp, AccessKind AK,
  755. Expr *MutexExp, ProtectedOperationKind POK);
  756. void checkAccess(Expr *Exp, AccessKind AK);
  757. void checkDereference(Expr *Exp, AccessKind AK);
  758. void handleCall(Expr *Exp, NamedDecl *D, VarDecl *VD = 0);
  759. template <class AttrType>
  760. void addTrylock(LockKind LK, AttrType *Attr, Expr *Exp, NamedDecl *FunDecl,
  761. const CFGBlock* PredBlock, const CFGBlock *CurrBlock,
  762. Expr *BrE, bool Neg);
  763. CallExpr* getTrylockCallExpr(Stmt *Cond, LocalVariableMap::Context C,
  764. bool &Negate);
  765. void handleTrylock(Stmt *Cond, const CFGBlock* PredBlock,
  766. const CFGBlock *CurrBlock);
  767. /// \brief Returns true if the lockset contains a lock, regardless of whether
  768. /// the lock is held exclusively or shared.
  769. bool locksetContains(const MutexID &Lock) const {
  770. return LSet.lookup(Lock);
  771. }
  772. /// \brief Returns true if the lockset contains a lock with the passed in
  773. /// locktype.
  774. bool locksetContains(const MutexID &Lock, LockKind KindRequested) const {
  775. const LockData *LockHeld = LSet.lookup(Lock);
  776. return (LockHeld && KindRequested == LockHeld->LKind);
  777. }
  778. /// \brief Returns true if the lockset contains a lock with at least the
  779. /// passed in locktype. So for example, if we pass in LK_Shared, this function
  780. /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
  781. /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
  782. bool locksetContainsAtLeast(const MutexID &Lock,
  783. LockKind KindRequested) const {
  784. switch (KindRequested) {
  785. case LK_Shared:
  786. return locksetContains(Lock);
  787. case LK_Exclusive:
  788. return locksetContains(Lock, KindRequested);
  789. }
  790. llvm_unreachable("Unknown LockKind");
  791. }
  792. public:
  793. BuildLockset(ThreadSafetyAnalyzer *analyzer, CFGBlockInfo &Info)
  794. : StmtVisitor<BuildLockset>(),
  795. Handler(analyzer->Handler),
  796. LocksetFactory(analyzer->LocksetFactory),
  797. LocalVarMap(analyzer->LocalVarMap),
  798. LSet(Info.EntrySet),
  799. LVarCtx(Info.EntryContext),
  800. CtxIndex(Info.EntryIndex)
  801. {}
  802. void VisitUnaryOperator(UnaryOperator *UO);
  803. void VisitBinaryOperator(BinaryOperator *BO);
  804. void VisitCastExpr(CastExpr *CE);
  805. void VisitCallExpr(CallExpr *Exp);
  806. void VisitCXXConstructExpr(CXXConstructExpr *Exp);
  807. void VisitDeclStmt(DeclStmt *S);
  808. };
  809. /// \brief Add a new lock to the lockset, warning if the lock is already there.
  810. /// \param Mutex -- the Mutex expression for the lock
  811. /// \param LDat -- the LockData for the lock
  812. void BuildLockset::addLock(const MutexID &Mutex, const LockData& LDat) {
  813. // FIXME: deal with acquired before/after annotations.
  814. // FIXME: Don't always warn when we have support for reentrant locks.
  815. if (locksetContains(Mutex))
  816. Handler.handleDoubleLock(Mutex.getName(), LDat.AcquireLoc);
  817. else
  818. LSet = LocksetFactory.add(LSet, Mutex, LDat);
  819. }
  820. /// \brief Remove a lock from the lockset, warning if the lock is not there.
  821. /// \param LockExp The lock expression corresponding to the lock to be removed
  822. /// \param UnlockLoc The source location of the unlock (only used in error msg)
  823. void BuildLockset::removeLock(const MutexID &Mutex, SourceLocation UnlockLoc) {
  824. const LockData *LDat = LSet.lookup(Mutex);
  825. if (!LDat)
  826. Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
  827. else {
  828. // For scoped-lockable vars, remove the mutex associated with this var.
  829. if (LDat->UnderlyingMutex.isValid())
  830. removeLock(LDat->UnderlyingMutex, UnlockLoc);
  831. LSet = LocksetFactory.remove(LSet, Mutex);
  832. }
  833. }
  834. /// \brief This function, parameterized by an attribute type, is used to add a
  835. /// set of locks specified as attribute arguments to the lockset.
  836. template <typename AttrType>
  837. void BuildLockset::addLocksToSet(LockKind LK, AttrType *Attr,
  838. Expr *Exp, NamedDecl* FunDecl, VarDecl *VD) {
  839. typedef typename AttrType::args_iterator iterator_type;
  840. SourceLocation ExpLocation = Exp->getExprLoc();
  841. // Figure out if we're calling the constructor of scoped lockable class
  842. bool isScopedVar = false;
  843. if (VD) {
  844. if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FunDecl)) {
  845. CXXRecordDecl* PD = CD->getParent();
  846. if (PD && PD->getAttr<ScopedLockableAttr>())
  847. isScopedVar = true;
  848. }
  849. }
  850. if (Attr->args_size() == 0) {
  851. // The mutex held is the "this" object.
  852. MutexID Mutex(0, Exp, FunDecl);
  853. if (!Mutex.isValid())
  854. MutexID::warnInvalidLock(Handler, 0, Exp, FunDecl);
  855. else
  856. addLock(Mutex, LockData(ExpLocation, LK));
  857. return;
  858. }
  859. for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
  860. MutexID Mutex(*I, Exp, FunDecl);
  861. if (!Mutex.isValid())
  862. MutexID::warnInvalidLock(Handler, *I, Exp, FunDecl);
  863. else {
  864. addLock(Mutex, LockData(ExpLocation, LK));
  865. if (isScopedVar) {
  866. // For scoped lockable vars, map this var to its underlying mutex.
  867. DeclRefExpr DRE(VD, VD->getType(), VK_LValue, VD->getLocation());
  868. MutexID SMutex(&DRE, 0, 0);
  869. addLock(SMutex, LockData(VD->getLocation(), LK, Mutex));
  870. }
  871. }
  872. }
  873. }
  874. /// \brief This function removes a set of locks specified as attribute
  875. /// arguments from the lockset.
  876. void BuildLockset::removeLocksFromSet(UnlockFunctionAttr *Attr,
  877. Expr *Exp, NamedDecl* FunDecl) {
  878. SourceLocation ExpLocation;
  879. if (Exp) ExpLocation = Exp->getExprLoc();
  880. if (Attr->args_size() == 0) {
  881. // The mutex held is the "this" object.
  882. MutexID Mu(0, Exp, FunDecl);
  883. if (!Mu.isValid())
  884. MutexID::warnInvalidLock(Handler, 0, Exp, FunDecl);
  885. else
  886. removeLock(Mu, ExpLocation);
  887. return;
  888. }
  889. for (UnlockFunctionAttr::args_iterator I = Attr->args_begin(),
  890. E = Attr->args_end(); I != E; ++I) {
  891. MutexID Mutex(*I, Exp, FunDecl);
  892. if (!Mutex.isValid())
  893. MutexID::warnInvalidLock(Handler, *I, Exp, FunDecl);
  894. else
  895. removeLock(Mutex, ExpLocation);
  896. }
  897. }
  898. /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
  899. const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
  900. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
  901. return DR->getDecl();
  902. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
  903. return ME->getMemberDecl();
  904. return 0;
  905. }
  906. /// \brief Warn if the LSet does not contain a lock sufficient to protect access
  907. /// of at least the passed in AccessKind.
  908. void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
  909. AccessKind AK, Expr *MutexExp,
  910. ProtectedOperationKind POK) {
  911. LockKind LK = getLockKindFromAccessKind(AK);
  912. MutexID Mutex(MutexExp, Exp, D);
  913. if (!Mutex.isValid())
  914. MutexID::warnInvalidLock(Handler, MutexExp, Exp, D);
  915. else if (!locksetContainsAtLeast(Mutex, LK))
  916. Handler.handleMutexNotHeld(D, POK, Mutex.getName(), LK, Exp->getExprLoc());
  917. }
  918. /// \brief This method identifies variable dereferences and checks pt_guarded_by
  919. /// and pt_guarded_var annotations. Note that we only check these annotations
  920. /// at the time a pointer is dereferenced.
  921. /// FIXME: We need to check for other types of pointer dereferences
  922. /// (e.g. [], ->) and deal with them here.
  923. /// \param Exp An expression that has been read or written.
  924. void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
  925. UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
  926. if (!UO || UO->getOpcode() != clang::UO_Deref)
  927. return;
  928. Exp = UO->getSubExpr()->IgnoreParenCasts();
  929. const ValueDecl *D = getValueDecl(Exp);
  930. if(!D || !D->hasAttrs())
  931. return;
  932. if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
  933. Handler.handleNoMutexHeld(D, POK_VarDereference, AK, Exp->getExprLoc());
  934. const AttrVec &ArgAttrs = D->getAttrs();
  935. for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
  936. if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
  937. warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
  938. }
  939. /// \brief Checks guarded_by and guarded_var attributes.
  940. /// Whenever we identify an access (read or write) of a DeclRefExpr or
  941. /// MemberExpr, we need to check whether there are any guarded_by or
  942. /// guarded_var attributes, and make sure we hold the appropriate mutexes.
  943. void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
  944. const ValueDecl *D = getValueDecl(Exp);
  945. if(!D || !D->hasAttrs())
  946. return;
  947. if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
  948. Handler.handleNoMutexHeld(D, POK_VarAccess, AK, Exp->getExprLoc());
  949. const AttrVec &ArgAttrs = D->getAttrs();
  950. for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
  951. if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
  952. warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
  953. }
  954. /// \brief Process a function call, method call, constructor call,
  955. /// or destructor call. This involves looking at the attributes on the
  956. /// corresponding function/method/constructor/destructor, issuing warnings,
  957. /// and updating the locksets accordingly.
  958. ///
  959. /// FIXME: For classes annotated with one of the guarded annotations, we need
  960. /// to treat const method calls as reads and non-const method calls as writes,
  961. /// and check that the appropriate locks are held. Non-const method calls with
  962. /// the same signature as const method calls can be also treated as reads.
  963. ///
  964. /// FIXME: We need to also visit CallExprs to catch/check global functions.
  965. ///
  966. /// FIXME: Do not flag an error for member variables accessed in constructors/
  967. /// destructors
  968. void BuildLockset::handleCall(Expr *Exp, NamedDecl *D, VarDecl *VD) {
  969. AttrVec &ArgAttrs = D->getAttrs();
  970. for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
  971. Attr *Attr = ArgAttrs[i];
  972. switch (Attr->getKind()) {
  973. // When we encounter an exclusive lock function, we need to add the lock
  974. // to our lockset with kind exclusive.
  975. case attr::ExclusiveLockFunction: {
  976. ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(Attr);
  977. addLocksToSet(LK_Exclusive, A, Exp, D, VD);
  978. break;
  979. }
  980. // When we encounter a shared lock function, we need to add the lock
  981. // to our lockset with kind shared.
  982. case attr::SharedLockFunction: {
  983. SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(Attr);
  984. addLocksToSet(LK_Shared, A, Exp, D, VD);
  985. break;
  986. }
  987. // When we encounter an unlock function, we need to remove unlocked
  988. // mutexes from the lockset, and flag a warning if they are not there.
  989. case attr::UnlockFunction: {
  990. UnlockFunctionAttr *UFAttr = cast<UnlockFunctionAttr>(Attr);
  991. removeLocksFromSet(UFAttr, Exp, D);
  992. break;
  993. }
  994. case attr::ExclusiveLocksRequired: {
  995. ExclusiveLocksRequiredAttr *ELRAttr =
  996. cast<ExclusiveLocksRequiredAttr>(Attr);
  997. for (ExclusiveLocksRequiredAttr::args_iterator
  998. I = ELRAttr->args_begin(), E = ELRAttr->args_end(); I != E; ++I)
  999. warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
  1000. break;
  1001. }
  1002. case attr::SharedLocksRequired: {
  1003. SharedLocksRequiredAttr *SLRAttr = cast<SharedLocksRequiredAttr>(Attr);
  1004. for (SharedLocksRequiredAttr::args_iterator I = SLRAttr->args_begin(),
  1005. E = SLRAttr->args_end(); I != E; ++I)
  1006. warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
  1007. break;
  1008. }
  1009. case attr::LocksExcluded: {
  1010. LocksExcludedAttr *LEAttr = cast<LocksExcludedAttr>(Attr);
  1011. for (LocksExcludedAttr::args_iterator I = LEAttr->args_begin(),
  1012. E = LEAttr->args_end(); I != E; ++I) {
  1013. MutexID Mutex(*I, Exp, D);
  1014. if (!Mutex.isValid())
  1015. MutexID::warnInvalidLock(Handler, *I, Exp, D);
  1016. else if (locksetContains(Mutex))
  1017. Handler.handleFunExcludesLock(D->getName(), Mutex.getName(),
  1018. Exp->getExprLoc());
  1019. }
  1020. break;
  1021. }
  1022. // Ignore other (non thread-safety) attributes
  1023. default:
  1024. break;
  1025. }
  1026. }
  1027. }
  1028. /// \brief Add lock to set, if the current block is in the taken branch of a
  1029. /// trylock.
  1030. template <class AttrType>
  1031. void BuildLockset::addTrylock(LockKind LK, AttrType *Attr, Expr *Exp,
  1032. NamedDecl *FunDecl, const CFGBlock *PredBlock,
  1033. const CFGBlock *CurrBlock, Expr *BrE, bool Neg) {
  1034. // Find out which branch has the lock
  1035. bool branch = 0;
  1036. if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
  1037. branch = BLE->getValue();
  1038. }
  1039. else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
  1040. branch = ILE->getValue().getBoolValue();
  1041. }
  1042. int branchnum = branch ? 0 : 1;
  1043. if (Neg) branchnum = !branchnum;
  1044. // If we've taken the trylock branch, then add the lock
  1045. int i = 0;
  1046. for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
  1047. SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
  1048. if (*SI == CurrBlock && i == branchnum) {
  1049. addLocksToSet(LK, Attr, Exp, FunDecl, 0);
  1050. }
  1051. }
  1052. }
  1053. // If Cond can be traced back to a function call, return the call expression.
  1054. // The negate variable should be called with false, and will be set to true
  1055. // if the function call is negated, e.g. if (!mu.tryLock(...))
  1056. CallExpr* BuildLockset::getTrylockCallExpr(Stmt *Cond,
  1057. LocalVariableMap::Context C,
  1058. bool &Negate) {
  1059. if (!Cond)
  1060. return 0;
  1061. if (CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
  1062. return CallExp;
  1063. }
  1064. else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
  1065. return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
  1066. }
  1067. else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
  1068. Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
  1069. return getTrylockCallExpr(E, C, Negate);
  1070. }
  1071. else if (UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
  1072. if (UOP->getOpcode() == UO_LNot) {
  1073. Negate = !Negate;
  1074. return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
  1075. }
  1076. }
  1077. // FIXME -- handle && and || as well.
  1078. return NULL;
  1079. }
  1080. /// \brief Process a conditional branch from a previous block to the current
  1081. /// block, looking for trylock calls.
  1082. void BuildLockset::handleTrylock(Stmt *Cond, const CFGBlock *PredBlock,
  1083. const CFGBlock *CurrBlock) {
  1084. bool Negate = false;
  1085. CallExpr *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
  1086. if (!Exp)
  1087. return;
  1088. NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
  1089. if(!FunDecl || !FunDecl->hasAttrs())
  1090. return;
  1091. // If the condition is a call to a Trylock function, then grab the attributes
  1092. AttrVec &ArgAttrs = FunDecl->getAttrs();
  1093. for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
  1094. Attr *Attr = ArgAttrs[i];
  1095. switch (Attr->getKind()) {
  1096. case attr::ExclusiveTrylockFunction: {
  1097. ExclusiveTrylockFunctionAttr *A =
  1098. cast<ExclusiveTrylockFunctionAttr>(Attr);
  1099. addTrylock(LK_Exclusive, A, Exp, FunDecl, PredBlock, CurrBlock,
  1100. A->getSuccessValue(), Negate);
  1101. break;
  1102. }
  1103. case attr::SharedTrylockFunction: {
  1104. SharedTrylockFunctionAttr *A =
  1105. cast<SharedTrylockFunctionAttr>(Attr);
  1106. addTrylock(LK_Shared, A, Exp, FunDecl, PredBlock, CurrBlock,
  1107. A->getSuccessValue(), Negate);
  1108. break;
  1109. }
  1110. default:
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. /// \brief For unary operations which read and write a variable, we need to
  1116. /// check whether we hold any required mutexes. Reads are checked in
  1117. /// VisitCastExpr.
  1118. void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
  1119. switch (UO->getOpcode()) {
  1120. case clang::UO_PostDec:
  1121. case clang::UO_PostInc:
  1122. case clang::UO_PreDec:
  1123. case clang::UO_PreInc: {
  1124. Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
  1125. checkAccess(SubExp, AK_Written);
  1126. checkDereference(SubExp, AK_Written);
  1127. break;
  1128. }
  1129. default:
  1130. break;
  1131. }
  1132. }
  1133. /// For binary operations which assign to a variable (writes), we need to check
  1134. /// whether we hold any required mutexes.
  1135. /// FIXME: Deal with non-primitive types.
  1136. void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
  1137. if (!BO->isAssignmentOp())
  1138. return;
  1139. // adjust the context
  1140. LVarCtx = LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
  1141. Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
  1142. checkAccess(LHSExp, AK_Written);
  1143. checkDereference(LHSExp, AK_Written);
  1144. }
  1145. /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
  1146. /// need to ensure we hold any required mutexes.
  1147. /// FIXME: Deal with non-primitive types.
  1148. void BuildLockset::VisitCastExpr(CastExpr *CE) {
  1149. if (CE->getCastKind() != CK_LValueToRValue)
  1150. return;
  1151. Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
  1152. checkAccess(SubExp, AK_Read);
  1153. checkDereference(SubExp, AK_Read);
  1154. }
  1155. void BuildLockset::VisitCallExpr(CallExpr *Exp) {
  1156. NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
  1157. if(!D || !D->hasAttrs())
  1158. return;
  1159. handleCall(Exp, D);
  1160. }
  1161. void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
  1162. // FIXME -- only handles constructors in DeclStmt below.
  1163. }
  1164. void BuildLockset::VisitDeclStmt(DeclStmt *S) {
  1165. // adjust the context
  1166. LVarCtx = LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
  1167. DeclGroupRef DGrp = S->getDeclGroup();
  1168. for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
  1169. Decl *D = *I;
  1170. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
  1171. Expr *E = VD->getInit();
  1172. if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
  1173. NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
  1174. if (!CtorD || !CtorD->hasAttrs())
  1175. return;
  1176. handleCall(CE, CtorD, VD);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. /// \brief Compute the intersection of two locksets and issue warnings for any
  1182. /// locks in the symmetric difference.
  1183. ///
  1184. /// This function is used at a merge point in the CFG when comparing the lockset
  1185. /// of each branch being merged. For example, given the following sequence:
  1186. /// A; if () then B; else C; D; we need to check that the lockset after B and C
  1187. /// are the same. In the event of a difference, we use the intersection of these
  1188. /// two locksets at the start of D.
  1189. Lockset ThreadSafetyAnalyzer::intersectAndWarn(const CFGBlockInfo &Block1,
  1190. CFGBlockSide Side1,
  1191. const CFGBlockInfo &Block2,
  1192. CFGBlockSide Side2,
  1193. LockErrorKind LEK) {
  1194. Lockset LSet1 = Block1.getSet(Side1);
  1195. Lockset LSet2 = Block2.getSet(Side2);
  1196. Lockset Intersection = LSet1;
  1197. for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
  1198. const MutexID &LSet2Mutex = I.getKey();
  1199. const LockData &LSet2LockData = I.getData();
  1200. if (const LockData *LD = LSet1.lookup(LSet2Mutex)) {
  1201. if (LD->LKind != LSet2LockData.LKind) {
  1202. Handler.handleExclusiveAndShared(LSet2Mutex.getName(),
  1203. LSet2LockData.AcquireLoc,
  1204. LD->AcquireLoc);
  1205. if (LD->LKind != LK_Exclusive)
  1206. Intersection = LocksetFactory.add(Intersection, LSet2Mutex,
  1207. LSet2LockData);
  1208. }
  1209. } else {
  1210. Handler.handleMutexHeldEndOfScope(LSet2Mutex.getName(),
  1211. LSet2LockData.AcquireLoc,
  1212. Block1.getLocation(Side1), LEK);
  1213. }
  1214. }
  1215. for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
  1216. if (!LSet2.contains(I.getKey())) {
  1217. const MutexID &Mutex = I.getKey();
  1218. const LockData &MissingLock = I.getData();
  1219. Handler.handleMutexHeldEndOfScope(Mutex.getName(),
  1220. MissingLock.AcquireLoc,
  1221. Block2.getLocation(Side2), LEK);
  1222. Intersection = LocksetFactory.remove(Intersection, Mutex);
  1223. }
  1224. }
  1225. return Intersection;
  1226. }
  1227. Lockset ThreadSafetyAnalyzer::addLock(Lockset &LSet, Expr *MutexExp,
  1228. const NamedDecl *D,
  1229. LockKind LK, SourceLocation Loc) {
  1230. MutexID Mutex(MutexExp, 0, D);
  1231. if (!Mutex.isValid()) {
  1232. MutexID::warnInvalidLock(Handler, MutexExp, 0, D);
  1233. return LSet;
  1234. }
  1235. LockData NewLock(Loc, LK);
  1236. return LocksetFactory.add(LSet, Mutex, NewLock);
  1237. }
  1238. /// \brief Check a function's CFG for thread-safety violations.
  1239. ///
  1240. /// We traverse the blocks in the CFG, compute the set of mutexes that are held
  1241. /// at the end of each block, and issue warnings for thread safety violations.
  1242. /// Each block in the CFG is traversed exactly once.
  1243. void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
  1244. CFG *CFGraph = AC.getCFG();
  1245. if (!CFGraph) return;
  1246. const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
  1247. if (!D)
  1248. return; // Ignore anonymous functions for now.
  1249. if (D->getAttr<NoThreadSafetyAnalysisAttr>())
  1250. return;
  1251. std::vector<CFGBlockInfo> BlockInfo(CFGraph->getNumBlockIDs(),
  1252. CFGBlockInfo::getEmptyBlockInfo(LocksetFactory, LocalVarMap));
  1253. // We need to explore the CFG via a "topological" ordering.
  1254. // That way, we will be guaranteed to have information about required
  1255. // predecessor locksets when exploring a new block.
  1256. PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
  1257. PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
  1258. // Compute SSA names for local variables
  1259. LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
  1260. // Fill in source locations for all CFGBlocks.
  1261. findBlockLocations(CFGraph, SortedGraph, BlockInfo);
  1262. // Add locks from exclusive_locks_required and shared_locks_required
  1263. // to initial lockset.
  1264. if (!SortedGraph->empty() && D->hasAttrs()) {
  1265. const CFGBlock *FirstBlock = *SortedGraph->begin();
  1266. Lockset &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
  1267. const AttrVec &ArgAttrs = D->getAttrs();
  1268. for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
  1269. Attr *Attr = ArgAttrs[i];
  1270. SourceLocation AttrLoc = Attr->getLocation();
  1271. if (SharedLocksRequiredAttr *SLRAttr
  1272. = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
  1273. for (SharedLocksRequiredAttr::args_iterator
  1274. SLRIter = SLRAttr->args_begin(),
  1275. SLREnd = SLRAttr->args_end(); SLRIter != SLREnd; ++SLRIter)
  1276. InitialLockset = addLock(InitialLockset,
  1277. *SLRIter, D, LK_Shared,
  1278. AttrLoc);
  1279. } else if (ExclusiveLocksRequiredAttr *ELRAttr
  1280. = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
  1281. for (ExclusiveLocksRequiredAttr::args_iterator
  1282. ELRIter = ELRAttr->args_begin(),
  1283. ELREnd = ELRAttr->args_end(); ELRIter != ELREnd; ++ELRIter)
  1284. InitialLockset = addLock(InitialLockset,
  1285. *ELRIter, D, LK_Exclusive,
  1286. AttrLoc);
  1287. }
  1288. }
  1289. }
  1290. for (PostOrderCFGView::iterator I = SortedGraph->begin(),
  1291. E = SortedGraph->end(); I!= E; ++I) {
  1292. const CFGBlock *CurrBlock = *I;
  1293. int CurrBlockID = CurrBlock->getBlockID();
  1294. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
  1295. // Use the default initial lockset in case there are no predecessors.
  1296. VisitedBlocks.insert(CurrBlock);
  1297. // Iterate through the predecessor blocks and warn if the lockset for all
  1298. // predecessors is not the same. We take the entry lockset of the current
  1299. // block to be the intersection of all previous locksets.
  1300. // FIXME: By keeping the intersection, we may output more errors in future
  1301. // for a lock which is not in the intersection, but was in the union. We
  1302. // may want to also keep the union in future. As an example, let's say
  1303. // the intersection contains Mutex L, and the union contains L and M.
  1304. // Later we unlock M. At this point, we would output an error because we
  1305. // never locked M; although the real error is probably that we forgot to
  1306. // lock M on all code paths. Conversely, let's say that later we lock M.
  1307. // In this case, we should compare against the intersection instead of the
  1308. // union because the real error is probably that we forgot to unlock M on
  1309. // all code paths.
  1310. bool LocksetInitialized = false;
  1311. llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
  1312. for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  1313. PE = CurrBlock->pred_end(); PI != PE; ++PI) {
  1314. // if *PI -> CurrBlock is a back edge
  1315. if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
  1316. continue;
  1317. // If the previous block ended in a 'continue' or 'break' statement, then
  1318. // a difference in locksets is probably due to a bug in that block, rather
  1319. // than in some other predecessor. In that case, keep the other
  1320. // predecessor's lockset.
  1321. if (const Stmt *Terminator = (*PI)->getTerminator()) {
  1322. if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
  1323. SpecialBlocks.push_back(*PI);
  1324. continue;
  1325. }
  1326. }
  1327. int PrevBlockID = (*PI)->getBlockID();
  1328. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  1329. if (!LocksetInitialized) {
  1330. CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
  1331. LocksetInitialized = true;
  1332. } else {
  1333. CurrBlockInfo->EntrySet =
  1334. intersectAndWarn(*CurrBlockInfo, CBS_Entry,
  1335. *PrevBlockInfo, CBS_Exit,
  1336. LEK_LockedSomePredecessors);
  1337. }
  1338. }
  1339. // Process continue and break blocks. Assume that the lockset for the
  1340. // resulting block is unaffected by any discrepancies in them.
  1341. for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
  1342. SpecialI < SpecialN; ++SpecialI) {
  1343. CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
  1344. int PrevBlockID = PrevBlock->getBlockID();
  1345. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  1346. if (!LocksetInitialized) {
  1347. CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
  1348. LocksetInitialized = true;
  1349. } else {
  1350. // Determine whether this edge is a loop terminator for diagnostic
  1351. // purposes. FIXME: A 'break' statement might be a loop terminator, but
  1352. // it might also be part of a switch. Also, a subsequent destructor
  1353. // might add to the lockset, in which case the real issue might be a
  1354. // double lock on the other path.
  1355. const Stmt *Terminator = PrevBlock->getTerminator();
  1356. bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
  1357. // Do not update EntrySet.
  1358. intersectAndWarn(*CurrBlockInfo, CBS_Entry, *PrevBlockInfo, CBS_Exit,
  1359. IsLoop ? LEK_LockedSomeLoopIterations
  1360. : LEK_LockedSomePredecessors);
  1361. }
  1362. }
  1363. BuildLockset LocksetBuilder(this, *CurrBlockInfo);
  1364. CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  1365. PE = CurrBlock->pred_end();
  1366. if (PI != PE) {
  1367. // If the predecessor ended in a branch, then process any trylocks.
  1368. // FIXME -- check to make sure there's only one predecessor.
  1369. if (Stmt *TCE = (*PI)->getTerminatorCondition()) {
  1370. LocksetBuilder.handleTrylock(TCE, *PI, CurrBlock);
  1371. }
  1372. }
  1373. // Visit all the statements in the basic block.
  1374. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  1375. BE = CurrBlock->end(); BI != BE; ++BI) {
  1376. switch (BI->getKind()) {
  1377. case CFGElement::Statement: {
  1378. const CFGStmt *CS = cast<CFGStmt>(&*BI);
  1379. LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
  1380. break;
  1381. }
  1382. // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
  1383. case CFGElement::AutomaticObjectDtor: {
  1384. const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
  1385. CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
  1386. AD->getDestructorDecl(AC.getASTContext()));
  1387. if (!DD->hasAttrs())
  1388. break;
  1389. // Create a dummy expression,
  1390. VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
  1391. DeclRefExpr DRE(VD, VD->getType(), VK_LValue,
  1392. AD->getTriggerStmt()->getLocEnd());
  1393. LocksetBuilder.handleCall(&DRE, DD);
  1394. break;
  1395. }
  1396. default:
  1397. break;
  1398. }
  1399. }
  1400. CurrBlockInfo->ExitSet = LocksetBuilder.LSet;
  1401. // For every back edge from CurrBlock (the end of the loop) to another block
  1402. // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
  1403. // the one held at the beginning of FirstLoopBlock. We can look up the
  1404. // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
  1405. for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
  1406. SE = CurrBlock->succ_end(); SI != SE; ++SI) {
  1407. // if CurrBlock -> *SI is *not* a back edge
  1408. if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
  1409. continue;
  1410. CFGBlock *FirstLoopBlock = *SI;
  1411. CFGBlockInfo &PreLoop = BlockInfo[FirstLoopBlock->getBlockID()];
  1412. CFGBlockInfo &LoopEnd = BlockInfo[CurrBlockID];
  1413. intersectAndWarn(LoopEnd, CBS_Exit, PreLoop, CBS_Entry,
  1414. LEK_LockedSomeLoopIterations);
  1415. }
  1416. }
  1417. CFGBlockInfo &Initial = BlockInfo[CFGraph->getEntry().getBlockID()];
  1418. CFGBlockInfo &Final = BlockInfo[CFGraph->getExit().getBlockID()];
  1419. // FIXME: Should we call this function for all blocks which exit the function?
  1420. intersectAndWarn(Initial, CBS_Entry, Final, CBS_Exit,
  1421. LEK_LockedAtEndOfFunction);
  1422. }
  1423. } // end anonymous namespace
  1424. namespace clang {
  1425. namespace thread_safety {
  1426. /// \brief Check a function's CFG for thread-safety violations.
  1427. ///
  1428. /// We traverse the blocks in the CFG, compute the set of mutexes that are held
  1429. /// at the end of each block, and issue warnings for thread safety violations.
  1430. /// Each block in the CFG is traversed exactly once.
  1431. void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
  1432. ThreadSafetyHandler &Handler) {
  1433. ThreadSafetyAnalyzer Analyzer(Handler);
  1434. Analyzer.runAnalysis(AC);
  1435. }
  1436. /// \brief Helper function that returns a LockKind required for the given level
  1437. /// of access.
  1438. LockKind getLockKindFromAccessKind(AccessKind AK) {
  1439. switch (AK) {
  1440. case AK_Read :
  1441. return LK_Shared;
  1442. case AK_Written :
  1443. return LK_Exclusive;
  1444. }
  1445. llvm_unreachable("Unknown AccessKind");
  1446. }
  1447. }} // end namespace clang::thread_safety