ThreadSafety.cpp 92 KB

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