ThreadSafety.cpp 90 KB

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