ExprEngine.cpp 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232
  1. //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines a meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  16. #include "PrettyStackTraceLocationContext.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ParentMap.h"
  26. #include "clang/AST/PrettyPrinter.h"
  27. #include "clang/AST/Stmt.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/StmtObjC.h"
  30. #include "clang/AST/Type.h"
  31. #include "clang/Analysis/AnalysisDeclContext.h"
  32. #include "clang/Analysis/CFG.h"
  33. #include "clang/Analysis/ConstructionContext.h"
  34. #include "clang/Analysis/ProgramPoint.h"
  35. #include "clang/Basic/IdentifierTable.h"
  36. #include "clang/Basic/LLVM.h"
  37. #include "clang/Basic/LangOptions.h"
  38. #include "clang/Basic/PrettyStackTrace.h"
  39. #include "clang/Basic/SourceLocation.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/Specifiers.h"
  42. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  43. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  44. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  45. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  47. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  48. #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
  49. #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
  50. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  51. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
  52. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
  53. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  54. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  55. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  56. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  57. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  58. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  59. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  60. #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
  61. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  62. #include "llvm/ADT/APSInt.h"
  63. #include "llvm/ADT/DenseMap.h"
  64. #include "llvm/ADT/ImmutableMap.h"
  65. #include "llvm/ADT/ImmutableSet.h"
  66. #include "llvm/ADT/Optional.h"
  67. #include "llvm/ADT/SmallVector.h"
  68. #include "llvm/ADT/Statistic.h"
  69. #include "llvm/Support/Casting.h"
  70. #include "llvm/Support/Compiler.h"
  71. #include "llvm/Support/DOTGraphTraits.h"
  72. #include "llvm/Support/ErrorHandling.h"
  73. #include "llvm/Support/GraphWriter.h"
  74. #include "llvm/Support/SaveAndRestore.h"
  75. #include "llvm/Support/raw_ostream.h"
  76. #include <cassert>
  77. #include <cstdint>
  78. #include <memory>
  79. #include <string>
  80. #include <tuple>
  81. #include <utility>
  82. #include <vector>
  83. using namespace clang;
  84. using namespace ento;
  85. #define DEBUG_TYPE "ExprEngine"
  86. STATISTIC(NumRemoveDeadBindings,
  87. "The # of times RemoveDeadBindings is called");
  88. STATISTIC(NumMaxBlockCountReached,
  89. "The # of aborted paths due to reaching the maximum block count in "
  90. "a top level function");
  91. STATISTIC(NumMaxBlockCountReachedInInlined,
  92. "The # of aborted paths due to reaching the maximum block count in "
  93. "an inlined function");
  94. STATISTIC(NumTimesRetriedWithoutInlining,
  95. "The # of times we re-evaluated a call without inlining");
  96. //===----------------------------------------------------------------------===//
  97. // Internal program state traits.
  98. //===----------------------------------------------------------------------===//
  99. // When modeling a C++ constructor, for a variety of reasons we need to track
  100. // the location of the object for the duration of its ConstructionContext.
  101. // ObjectsUnderConstruction maps statements within the construction context
  102. // to the object's location, so that on every such statement the location
  103. // could have been retrieved.
  104. /// ConstructedObjectKey is used for being able to find the path-sensitive
  105. /// memory region of a freshly constructed object while modeling the AST node
  106. /// that syntactically represents the object that is being constructed.
  107. /// Semantics of such nodes may sometimes require access to the region that's
  108. /// not otherwise present in the program state, or to the very fact that
  109. /// the construction context was present and contained references to these
  110. /// AST nodes.
  111. class ConstructedObjectKey {
  112. typedef std::pair<
  113. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *>,
  114. const LocationContext *> ConstructedObjectKeyImpl;
  115. ConstructedObjectKeyImpl Impl;
  116. const void *getAnyASTNodePtr() const {
  117. if (const Stmt *S = getStmt())
  118. return S;
  119. else
  120. return getCXXCtorInitializer();
  121. }
  122. public:
  123. ConstructedObjectKey(
  124. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  125. const LocationContext *LC)
  126. : Impl(P, LC) {
  127. // This is the full list of statements that require additional actions when
  128. // encountered. This list may be expanded when new actions are implemented.
  129. assert(getCXXCtorInitializer() || isa<DeclStmt>(getStmt()) ||
  130. isa<CXXNewExpr>(getStmt()) || isa<CXXBindTemporaryExpr>(getStmt()) ||
  131. isa<MaterializeTemporaryExpr>(getStmt()) ||
  132. isa<CXXConstructExpr>(getStmt()));
  133. }
  134. const Stmt *getStmt() const {
  135. return Impl.first.dyn_cast<const Stmt *>();
  136. }
  137. const CXXCtorInitializer *getCXXCtorInitializer() const {
  138. return Impl.first.dyn_cast<const CXXCtorInitializer *>();
  139. }
  140. const LocationContext *getLocationContext() const {
  141. return Impl.second;
  142. }
  143. void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
  144. OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ") ";
  145. if (const Stmt *S = getStmt()) {
  146. S->printPretty(OS, Helper, PP);
  147. } else {
  148. const CXXCtorInitializer *I = getCXXCtorInitializer();
  149. OS << I->getAnyMember()->getNameAsString();
  150. }
  151. }
  152. void Profile(llvm::FoldingSetNodeID &ID) const {
  153. ID.AddPointer(Impl.first.getOpaqueValue());
  154. ID.AddPointer(Impl.second);
  155. }
  156. bool operator==(const ConstructedObjectKey &RHS) const {
  157. return Impl == RHS.Impl;
  158. }
  159. bool operator<(const ConstructedObjectKey &RHS) const {
  160. return Impl < RHS.Impl;
  161. }
  162. };
  163. typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
  164. ObjectsUnderConstructionMap;
  165. REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
  166. ObjectsUnderConstructionMap)
  167. // Additionally, track a set of destructors that correspond to elided
  168. // constructors when copy elision occurs.
  169. typedef std::pair<const CXXBindTemporaryExpr *, const LocationContext *>
  170. ElidedDestructorItem;
  171. typedef llvm::ImmutableSet<ElidedDestructorItem>
  172. ElidedDestructorSet;
  173. REGISTER_TRAIT_WITH_PROGRAMSTATE(ElidedDestructors,
  174. ElidedDestructorSet);
  175. //===----------------------------------------------------------------------===//
  176. // Engine construction and deletion.
  177. //===----------------------------------------------------------------------===//
  178. static const char* TagProviderName = "ExprEngine";
  179. ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
  180. AnalysisManager &mgr, bool gcEnabled,
  181. SetOfConstDecls *VisitedCalleesIn,
  182. FunctionSummariesTy *FS,
  183. InliningModes HowToInlineIn)
  184. : CTU(CTU), AMgr(mgr),
  185. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  186. Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
  187. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  188. mgr.getConstraintManagerCreator(), G.getAllocator(),
  189. this),
  190. SymMgr(StateMgr.getSymbolManager()),
  191. svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
  192. ObjCGCEnabled(gcEnabled), BR(mgr, *this),
  193. VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
  194. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  195. if (TrimInterval != 0) {
  196. // Enable eager node reclaimation when constructing the ExplodedGraph.
  197. G.enableNodeReclamation(TrimInterval);
  198. }
  199. }
  200. ExprEngine::~ExprEngine() {
  201. BR.FlushReports();
  202. }
  203. //===----------------------------------------------------------------------===//
  204. // Utility methods.
  205. //===----------------------------------------------------------------------===//
  206. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  207. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  208. const Decl *D = InitLoc->getDecl();
  209. // Preconditions.
  210. // FIXME: It would be nice if we had a more general mechanism to add
  211. // such preconditions. Some day.
  212. do {
  213. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  214. // Precondition: the first argument of 'main' is an integer guaranteed
  215. // to be > 0.
  216. const IdentifierInfo *II = FD->getIdentifier();
  217. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  218. break;
  219. const ParmVarDecl *PD = FD->getParamDecl(0);
  220. QualType T = PD->getType();
  221. const auto *BT = dyn_cast<BuiltinType>(T);
  222. if (!BT || !BT->isInteger())
  223. break;
  224. const MemRegion *R = state->getRegion(PD, InitLoc);
  225. if (!R)
  226. break;
  227. SVal V = state->getSVal(loc::MemRegionVal(R));
  228. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  229. svalBuilder.makeZeroVal(T),
  230. svalBuilder.getConditionType());
  231. Optional<DefinedOrUnknownSVal> Constraint =
  232. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  233. if (!Constraint)
  234. break;
  235. if (ProgramStateRef newState = state->assume(*Constraint, true))
  236. state = newState;
  237. }
  238. break;
  239. }
  240. while (false);
  241. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  242. // Precondition: 'self' is always non-null upon entry to an Objective-C
  243. // method.
  244. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  245. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  246. SVal V = state->getSVal(loc::MemRegionVal(R));
  247. if (Optional<Loc> LV = V.getAs<Loc>()) {
  248. // Assume that the pointer value in 'self' is non-null.
  249. state = state->assume(*LV, true);
  250. assert(state && "'self' cannot be null");
  251. }
  252. }
  253. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  254. if (!MD->isStatic()) {
  255. // Precondition: 'this' is always non-null upon entry to the
  256. // top-level function. This is our starting assumption for
  257. // analyzing an "open" program.
  258. const StackFrameContext *SFC = InitLoc->getStackFrame();
  259. if (SFC->getParent() == nullptr) {
  260. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  261. SVal V = state->getSVal(L);
  262. if (Optional<Loc> LV = V.getAs<Loc>()) {
  263. state = state->assume(*LV, true);
  264. assert(state && "'this' cannot be null");
  265. }
  266. }
  267. }
  268. }
  269. return state;
  270. }
  271. ProgramStateRef
  272. ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
  273. const LocationContext *LC,
  274. const Expr *InitWithAdjustments,
  275. const Expr *Result) {
  276. // FIXME: This function is a hack that works around the quirky AST
  277. // we're often having with respect to C++ temporaries. If only we modelled
  278. // the actual execution order of statements properly in the CFG,
  279. // all the hassle with adjustments would not be necessary,
  280. // and perhaps the whole function would be removed.
  281. SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
  282. if (!Result) {
  283. // If we don't have an explicit result expression, we're in "if needed"
  284. // mode. Only create a region if the current value is a NonLoc.
  285. if (!InitValWithAdjustments.getAs<NonLoc>())
  286. return State;
  287. Result = InitWithAdjustments;
  288. } else {
  289. // We need to create a region no matter what. For sanity, make sure we don't
  290. // try to stuff a Loc into a non-pointer temporary region.
  291. assert(!InitValWithAdjustments.getAs<Loc>() ||
  292. Loc::isLocType(Result->getType()) ||
  293. Result->getType()->isMemberPointerType());
  294. }
  295. ProgramStateManager &StateMgr = State->getStateManager();
  296. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  297. StoreManager &StoreMgr = StateMgr.getStoreManager();
  298. // MaterializeTemporaryExpr may appear out of place, after a few field and
  299. // base-class accesses have been made to the object, even though semantically
  300. // it is the whole object that gets materialized and lifetime-extended.
  301. //
  302. // For example:
  303. //
  304. // `-MaterializeTemporaryExpr
  305. // `-MemberExpr
  306. // `-CXXTemporaryObjectExpr
  307. //
  308. // instead of the more natural
  309. //
  310. // `-MemberExpr
  311. // `-MaterializeTemporaryExpr
  312. // `-CXXTemporaryObjectExpr
  313. //
  314. // Use the usual methods for obtaining the expression of the base object,
  315. // and record the adjustments that we need to make to obtain the sub-object
  316. // that the whole expression 'Ex' refers to. This trick is usual,
  317. // in the sense that CodeGen takes a similar route.
  318. SmallVector<const Expr *, 2> CommaLHSs;
  319. SmallVector<SubobjectAdjustment, 2> Adjustments;
  320. const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
  321. CommaLHSs, Adjustments);
  322. // Take the region for Init, i.e. for the whole object. If we do not remember
  323. // the region in which the object originally was constructed, come up with
  324. // a new temporary region out of thin air and copy the contents of the object
  325. // (which are currently present in the Environment, because Init is an rvalue)
  326. // into that region. This is not correct, but it is better than nothing.
  327. const TypedValueRegion *TR = nullptr;
  328. if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
  329. if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
  330. State = finishObjectConstruction(State, MT, LC);
  331. State = State->BindExpr(Result, LC, *V);
  332. return State;
  333. } else {
  334. StorageDuration SD = MT->getStorageDuration();
  335. // If this object is bound to a reference with static storage duration, we
  336. // put it in a different region to prevent "address leakage" warnings.
  337. if (SD == SD_Static || SD == SD_Thread) {
  338. TR = MRMgr.getCXXStaticTempObjectRegion(Init);
  339. } else {
  340. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  341. }
  342. }
  343. } else {
  344. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  345. }
  346. SVal Reg = loc::MemRegionVal(TR);
  347. SVal BaseReg = Reg;
  348. // Make the necessary adjustments to obtain the sub-object.
  349. for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
  350. const SubobjectAdjustment &Adj = *I;
  351. switch (Adj.Kind) {
  352. case SubobjectAdjustment::DerivedToBaseAdjustment:
  353. Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
  354. break;
  355. case SubobjectAdjustment::FieldAdjustment:
  356. Reg = StoreMgr.getLValueField(Adj.Field, Reg);
  357. break;
  358. case SubobjectAdjustment::MemberPointerAdjustment:
  359. // FIXME: Unimplemented.
  360. State = State->invalidateRegions(Reg, InitWithAdjustments,
  361. currBldrCtx->blockCount(), LC, true,
  362. nullptr, nullptr, nullptr);
  363. return State;
  364. }
  365. }
  366. // What remains is to copy the value of the object to the new region.
  367. // FIXME: In other words, what we should always do is copy value of the
  368. // Init expression (which corresponds to the bigger object) to the whole
  369. // temporary region TR. However, this value is often no longer present
  370. // in the Environment. If it has disappeared, we instead invalidate TR.
  371. // Still, what we can do is assign the value of expression Ex (which
  372. // corresponds to the sub-object) to the TR's sub-region Reg. At least,
  373. // values inside Reg would be correct.
  374. SVal InitVal = State->getSVal(Init, LC);
  375. if (InitVal.isUnknown()) {
  376. InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
  377. currBldrCtx->blockCount());
  378. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  379. // Then we'd need to take the value that certainly exists and bind it
  380. // over.
  381. if (InitValWithAdjustments.isUnknown()) {
  382. // Try to recover some path sensitivity in case we couldn't
  383. // compute the value.
  384. InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
  385. Result, LC, InitWithAdjustments->getType(),
  386. currBldrCtx->blockCount());
  387. }
  388. State =
  389. State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
  390. } else {
  391. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  392. }
  393. // The result expression would now point to the correct sub-region of the
  394. // newly created temporary region. Do this last in order to getSVal of Init
  395. // correctly in case (Result == Init).
  396. State = State->BindExpr(Result, LC, Reg);
  397. // Notify checkers once for two bindLoc()s.
  398. State = processRegionChange(State, TR, LC);
  399. return State;
  400. }
  401. ProgramStateRef ExprEngine::addObjectUnderConstruction(
  402. ProgramStateRef State,
  403. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  404. const LocationContext *LC, SVal V) {
  405. ConstructedObjectKey Key(P, LC->getStackFrame());
  406. // FIXME: Currently the state might already contain the marker due to
  407. // incorrect handling of temporaries bound to default parameters.
  408. assert(!State->get<ObjectsUnderConstruction>(Key) ||
  409. isa<CXXBindTemporaryExpr>(Key.getStmt()));
  410. return State->set<ObjectsUnderConstruction>(Key, V);
  411. }
  412. Optional<SVal> ExprEngine::getObjectUnderConstruction(
  413. ProgramStateRef State,
  414. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  415. const LocationContext *LC) {
  416. ConstructedObjectKey Key(P, LC->getStackFrame());
  417. return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
  418. }
  419. ProgramStateRef ExprEngine::finishObjectConstruction(
  420. ProgramStateRef State,
  421. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  422. const LocationContext *LC) {
  423. ConstructedObjectKey Key(P, LC->getStackFrame());
  424. assert(State->contains<ObjectsUnderConstruction>(Key));
  425. return State->remove<ObjectsUnderConstruction>(Key);
  426. }
  427. ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
  428. const CXXBindTemporaryExpr *BTE,
  429. const LocationContext *LC) {
  430. ElidedDestructorItem I(BTE, LC);
  431. assert(!State->contains<ElidedDestructors>(I));
  432. return State->add<ElidedDestructors>(I);
  433. }
  434. ProgramStateRef
  435. ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
  436. const CXXBindTemporaryExpr *BTE,
  437. const LocationContext *LC) {
  438. ElidedDestructorItem I(BTE, LC);
  439. assert(State->contains<ElidedDestructors>(I));
  440. return State->remove<ElidedDestructors>(I);
  441. }
  442. bool ExprEngine::isDestructorElided(ProgramStateRef State,
  443. const CXXBindTemporaryExpr *BTE,
  444. const LocationContext *LC) {
  445. ElidedDestructorItem I(BTE, LC);
  446. return State->contains<ElidedDestructors>(I);
  447. }
  448. bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
  449. const LocationContext *FromLC,
  450. const LocationContext *ToLC) {
  451. const LocationContext *LC = FromLC;
  452. while (LC != ToLC) {
  453. assert(LC && "ToLC must be a parent of FromLC!");
  454. for (auto I : State->get<ObjectsUnderConstruction>())
  455. if (I.first.getLocationContext() == LC)
  456. return false;
  457. for (auto I: State->get<ElidedDestructors>())
  458. if (I.second == LC)
  459. return false;
  460. LC = LC->getParent();
  461. }
  462. return true;
  463. }
  464. //===----------------------------------------------------------------------===//
  465. // Top-level transfer function logic (Dispatcher).
  466. //===----------------------------------------------------------------------===//
  467. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  468. /// logic for handling assumptions on symbolic values.
  469. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  470. SVal cond, bool assumption) {
  471. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  472. }
  473. ProgramStateRef
  474. ExprEngine::processRegionChanges(ProgramStateRef state,
  475. const InvalidatedSymbols *invalidated,
  476. ArrayRef<const MemRegion *> Explicits,
  477. ArrayRef<const MemRegion *> Regions,
  478. const LocationContext *LCtx,
  479. const CallEvent *Call) {
  480. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  481. Explicits, Regions,
  482. LCtx, Call);
  483. }
  484. static void printObjectsUnderConstructionForContext(raw_ostream &Out,
  485. ProgramStateRef State,
  486. const char *NL,
  487. const char *Sep,
  488. const LocationContext *LC) {
  489. PrintingPolicy PP =
  490. LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
  491. for (auto I : State->get<ObjectsUnderConstruction>()) {
  492. ConstructedObjectKey Key = I.first;
  493. SVal Value = I.second;
  494. if (Key.getLocationContext() != LC)
  495. continue;
  496. Key.print(Out, nullptr, PP);
  497. Out << " : " << Value << NL;
  498. }
  499. for (auto I : State->get<ElidedDestructors>()) {
  500. if (I.second != LC)
  501. continue;
  502. Out << '(' << I.second << ',' << (const void *)I.first << ") ";
  503. I.first->printPretty(Out, nullptr, PP);
  504. Out << " : (constructor elided)" << NL;
  505. }
  506. }
  507. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  508. const char *NL, const char *Sep,
  509. const LocationContext *LCtx) {
  510. if (LCtx) {
  511. if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
  512. Out << Sep << "Objects under construction:" << NL;
  513. LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
  514. printObjectsUnderConstructionForContext(Out, State, NL, Sep, LC);
  515. });
  516. }
  517. }
  518. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  519. }
  520. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  521. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  522. }
  523. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  524. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  525. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  526. currStmtIdx = StmtIdx;
  527. currBldrCtx = Ctx;
  528. switch (E.getKind()) {
  529. case CFGElement::Statement:
  530. case CFGElement::Constructor:
  531. case CFGElement::CXXRecordTypedCall:
  532. ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
  533. return;
  534. case CFGElement::Initializer:
  535. ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
  536. return;
  537. case CFGElement::NewAllocator:
  538. ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
  539. Pred);
  540. return;
  541. case CFGElement::AutomaticObjectDtor:
  542. case CFGElement::DeleteDtor:
  543. case CFGElement::BaseDtor:
  544. case CFGElement::MemberDtor:
  545. case CFGElement::TemporaryDtor:
  546. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  547. return;
  548. case CFGElement::LoopExit:
  549. ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
  550. return;
  551. case CFGElement::LifetimeEnds:
  552. case CFGElement::ScopeBegin:
  553. case CFGElement::ScopeEnd:
  554. return;
  555. }
  556. }
  557. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  558. const Stmt *S,
  559. const ExplodedNode *Pred,
  560. const LocationContext *LC) {
  561. // Are we never purging state values?
  562. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  563. return false;
  564. // Is this the beginning of a basic block?
  565. if (Pred->getLocation().getAs<BlockEntrance>())
  566. return true;
  567. // Is this on a non-expression?
  568. if (!isa<Expr>(S))
  569. return true;
  570. // Run before processing a call.
  571. if (CallEvent::isCallStmt(S))
  572. return true;
  573. // Is this an expression that is consumed by another expression? If so,
  574. // postpone cleaning out the state.
  575. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  576. return !PM.isConsumedExpr(cast<Expr>(S));
  577. }
  578. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  579. const Stmt *ReferenceStmt,
  580. const LocationContext *LC,
  581. const Stmt *DiagnosticStmt,
  582. ProgramPoint::Kind K) {
  583. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  584. ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
  585. && "PostStmt is not generally supported by the SymbolReaper yet");
  586. assert(LC && "Must pass the current (or expiring) LocationContext");
  587. if (!DiagnosticStmt) {
  588. DiagnosticStmt = ReferenceStmt;
  589. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  590. }
  591. NumRemoveDeadBindings++;
  592. ProgramStateRef CleanedState = Pred->getState();
  593. // LC is the location context being destroyed, but SymbolReaper wants a
  594. // location context that is still live. (If this is the top-level stack
  595. // frame, this will be null.)
  596. if (!ReferenceStmt) {
  597. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  598. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  599. LC = LC->getParent();
  600. }
  601. const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
  602. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  603. for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
  604. if (SymbolRef Sym = I.second.getAsSymbol())
  605. SymReaper.markLive(Sym);
  606. if (const MemRegion *MR = I.second.getAsRegion())
  607. SymReaper.markLive(MR);
  608. }
  609. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  610. // Create a state in which dead bindings are removed from the environment
  611. // and the store. TODO: The function should just return new env and store,
  612. // not a new state.
  613. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  614. // Process any special transfer function for dead symbols.
  615. // A tag to track convenience transitions, which can be removed at cleanup.
  616. static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
  617. if (!SymReaper.hasDeadSymbols()) {
  618. // Generate a CleanedNode that has the environment and store cleaned
  619. // up. Since no symbols are dead, we can optimize and not clean out
  620. // the constraint manager.
  621. StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
  622. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
  623. } else {
  624. // Call checkers with the non-cleaned state so that they could query the
  625. // values of the soon to be dead symbols.
  626. ExplodedNodeSet CheckedSet;
  627. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  628. DiagnosticStmt, *this, K);
  629. // For each node in CheckedSet, generate CleanedNodes that have the
  630. // environment, the store, and the constraints cleaned up but have the
  631. // user-supplied states as the predecessors.
  632. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  633. for (const auto I : CheckedSet) {
  634. ProgramStateRef CheckerState = I->getState();
  635. // The constraint manager has not been cleaned up yet, so clean up now.
  636. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  637. SymReaper);
  638. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  639. "Checkers are not allowed to modify the Environment as a part of "
  640. "checkDeadSymbols processing.");
  641. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  642. "Checkers are not allowed to modify the Store as a part of "
  643. "checkDeadSymbols processing.");
  644. // Create a state based on CleanedState with CheckerState GDM and
  645. // generate a transition to that state.
  646. ProgramStateRef CleanedCheckerSt =
  647. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  648. Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
  649. }
  650. }
  651. }
  652. void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
  653. // Reclaim any unnecessary nodes in the ExplodedGraph.
  654. G.reclaimRecentlyAllocatedNodes();
  655. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  656. currStmt->getLocStart(),
  657. "Error evaluating statement");
  658. // Remove dead bindings and symbols.
  659. ExplodedNodeSet CleanedStates;
  660. if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
  661. Pred->getLocationContext())) {
  662. removeDead(Pred, CleanedStates, currStmt,
  663. Pred->getLocationContext());
  664. } else
  665. CleanedStates.Add(Pred);
  666. // Visit the statement.
  667. ExplodedNodeSet Dst;
  668. for (const auto I : CleanedStates) {
  669. ExplodedNodeSet DstI;
  670. // Visit the statement.
  671. Visit(currStmt, I, DstI);
  672. Dst.insert(DstI);
  673. }
  674. // Enqueue the new nodes onto the work list.
  675. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  676. }
  677. void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
  678. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  679. S->getLocStart(),
  680. "Error evaluating end of the loop");
  681. ExplodedNodeSet Dst;
  682. Dst.Add(Pred);
  683. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  684. ProgramStateRef NewState = Pred->getState();
  685. if(AMgr.options.shouldUnrollLoops())
  686. NewState = processLoopEnd(S, NewState);
  687. LoopExit PP(S, Pred->getLocationContext());
  688. Bldr.generateNode(PP, NewState, Pred);
  689. // Enqueue the new nodes onto the work list.
  690. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  691. }
  692. void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
  693. ExplodedNode *Pred) {
  694. const CXXCtorInitializer *BMI = CFGInit.getInitializer();
  695. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  696. const LocationContext *LC = Pred->getLocationContext();
  697. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  698. BMI->getSourceLocation(),
  699. "Error evaluating initializer");
  700. // We don't clean up dead bindings here.
  701. const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
  702. const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
  703. ProgramStateRef State = Pred->getState();
  704. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  705. ExplodedNodeSet Tmp;
  706. SVal FieldLoc;
  707. // Evaluate the initializer, if necessary
  708. if (BMI->isAnyMemberInitializer()) {
  709. // Constructors build the object directly in the field,
  710. // but non-objects must be copied in from the initializer.
  711. if (getObjectUnderConstruction(State, BMI, LC)) {
  712. // The field was directly constructed, so there is no need to bind.
  713. // But we still need to stop tracking the object under construction.
  714. State = finishObjectConstruction(State, BMI, LC);
  715. NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  716. PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
  717. Bldr.generateNode(PS, State, Pred);
  718. } else {
  719. const ValueDecl *Field;
  720. if (BMI->isIndirectMemberInitializer()) {
  721. Field = BMI->getIndirectMember();
  722. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  723. } else {
  724. Field = BMI->getMember();
  725. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  726. }
  727. SVal InitVal;
  728. if (Init->getType()->isArrayType()) {
  729. // Handle arrays of trivial type. We can represent this with a
  730. // primitive load/copy from the base array region.
  731. const ArraySubscriptExpr *ASE;
  732. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  733. Init = ASE->getBase()->IgnoreImplicit();
  734. SVal LValue = State->getSVal(Init, stackFrame);
  735. if (!Field->getType()->isReferenceType())
  736. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  737. InitVal = State->getSVal(*LValueLoc);
  738. // If we fail to get the value for some reason, use a symbolic value.
  739. if (InitVal.isUnknownOrUndef()) {
  740. SValBuilder &SVB = getSValBuilder();
  741. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  742. Field->getType(),
  743. currBldrCtx->blockCount());
  744. }
  745. } else {
  746. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  747. }
  748. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  749. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  750. }
  751. } else {
  752. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  753. Tmp.insert(Pred);
  754. // We already did all the work when visiting the CXXConstructExpr.
  755. }
  756. // Construct PostInitializer nodes whether the state changed or not,
  757. // so that the diagnostics don't get confused.
  758. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  759. ExplodedNodeSet Dst;
  760. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  761. for (const auto I : Tmp) {
  762. ProgramStateRef State = I->getState();
  763. Bldr.generateNode(PP, State, I);
  764. }
  765. // Enqueue the new nodes onto the work list.
  766. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  767. }
  768. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  769. ExplodedNode *Pred) {
  770. ExplodedNodeSet Dst;
  771. switch (D.getKind()) {
  772. case CFGElement::AutomaticObjectDtor:
  773. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  774. break;
  775. case CFGElement::BaseDtor:
  776. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  777. break;
  778. case CFGElement::MemberDtor:
  779. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  780. break;
  781. case CFGElement::TemporaryDtor:
  782. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  783. break;
  784. case CFGElement::DeleteDtor:
  785. ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
  786. break;
  787. default:
  788. llvm_unreachable("Unexpected dtor kind.");
  789. }
  790. // Enqueue the new nodes onto the work list.
  791. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  792. }
  793. void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
  794. ExplodedNode *Pred) {
  795. ExplodedNodeSet Dst;
  796. AnalysisManager &AMgr = getAnalysisManager();
  797. AnalyzerOptions &Opts = AMgr.options;
  798. // TODO: We're not evaluating allocators for all cases just yet as
  799. // we're not handling the return value correctly, which causes false
  800. // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
  801. if (Opts.mayInlineCXXAllocator())
  802. VisitCXXNewAllocatorCall(NE, Pred, Dst);
  803. else {
  804. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  805. const LocationContext *LCtx = Pred->getLocationContext();
  806. PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
  807. Bldr.generateNode(PP, Pred->getState(), Pred);
  808. }
  809. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  810. }
  811. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  812. ExplodedNode *Pred,
  813. ExplodedNodeSet &Dst) {
  814. const VarDecl *varDecl = Dtor.getVarDecl();
  815. QualType varType = varDecl->getType();
  816. ProgramStateRef state = Pred->getState();
  817. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  818. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  819. if (varType->isReferenceType()) {
  820. const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
  821. if (!ValueRegion) {
  822. // FIXME: This should not happen. The language guarantees a presence
  823. // of a valid initializer here, so the reference shall not be undefined.
  824. // It seems that we're calling destructors over variables that
  825. // were not initialized yet.
  826. return;
  827. }
  828. Region = ValueRegion->getBaseRegion();
  829. varType = cast<TypedValueRegion>(Region)->getValueType();
  830. }
  831. // FIXME: We need to run the same destructor on every element of the array.
  832. // This workaround will just run the first destructor (which will still
  833. // invalidate the entire array).
  834. EvalCallOptions CallOpts;
  835. Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
  836. CallOpts.IsArrayCtorOrDtor).getAsRegion();
  837. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  838. Pred, Dst, CallOpts);
  839. }
  840. void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
  841. ExplodedNode *Pred,
  842. ExplodedNodeSet &Dst) {
  843. ProgramStateRef State = Pred->getState();
  844. const LocationContext *LCtx = Pred->getLocationContext();
  845. const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
  846. const Stmt *Arg = DE->getArgument();
  847. QualType DTy = DE->getDestroyedType();
  848. SVal ArgVal = State->getSVal(Arg, LCtx);
  849. // If the argument to delete is known to be a null value,
  850. // don't run destructor.
  851. if (State->isNull(ArgVal).isConstrainedTrue()) {
  852. QualType BTy = getContext().getBaseElementType(DTy);
  853. const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
  854. const CXXDestructorDecl *Dtor = RD->getDestructor();
  855. PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
  856. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  857. Bldr.generateNode(PP, Pred->getState(), Pred);
  858. return;
  859. }
  860. EvalCallOptions CallOpts;
  861. const MemRegion *ArgR = ArgVal.getAsRegion();
  862. if (DE->isArrayForm()) {
  863. // FIXME: We need to run the same destructor on every element of the array.
  864. // This workaround will just run the first destructor (which will still
  865. // invalidate the entire array).
  866. CallOpts.IsArrayCtorOrDtor = true;
  867. // Yes, it may even be a multi-dimensional array.
  868. while (const auto *AT = getContext().getAsArrayType(DTy))
  869. DTy = AT->getElementType();
  870. if (ArgR)
  871. ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
  872. }
  873. VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
  874. }
  875. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  876. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  877. const LocationContext *LCtx = Pred->getLocationContext();
  878. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  879. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  880. LCtx->getStackFrame());
  881. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  882. // Create the base object region.
  883. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  884. QualType BaseTy = Base->getType();
  885. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  886. Base->isVirtual());
  887. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  888. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
  889. }
  890. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  891. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  892. const FieldDecl *Member = D.getFieldDecl();
  893. QualType T = Member->getType();
  894. ProgramStateRef State = Pred->getState();
  895. const LocationContext *LCtx = Pred->getLocationContext();
  896. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  897. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  898. LCtx->getStackFrame());
  899. SVal FieldVal =
  900. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  901. // FIXME: We need to run the same destructor on every element of the array.
  902. // This workaround will just run the first destructor (which will still
  903. // invalidate the entire array).
  904. EvalCallOptions CallOpts;
  905. FieldVal = makeZeroElementRegion(State, FieldVal, T,
  906. CallOpts.IsArrayCtorOrDtor);
  907. VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  908. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
  909. }
  910. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  911. ExplodedNode *Pred,
  912. ExplodedNodeSet &Dst) {
  913. const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
  914. ProgramStateRef State = Pred->getState();
  915. const LocationContext *LC = Pred->getLocationContext();
  916. const MemRegion *MR = nullptr;
  917. if (Optional<SVal> V =
  918. getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
  919. Pred->getLocationContext())) {
  920. // FIXME: Currently we insert temporary destructors for default parameters,
  921. // but we don't insert the constructors, so the entry in
  922. // ObjectsUnderConstruction may be missing.
  923. State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
  924. Pred->getLocationContext());
  925. MR = V->getAsRegion();
  926. }
  927. // If copy elision has occured, and the constructor corresponding to the
  928. // destructor was elided, we need to skip the destructor as well.
  929. if (isDestructorElided(State, BTE, LC)) {
  930. State = cleanupElidedDestructor(State, BTE, LC);
  931. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  932. PostImplicitCall PP(D.getDestructorDecl(getContext()),
  933. D.getBindTemporaryExpr()->getLocStart(),
  934. Pred->getLocationContext());
  935. Bldr.generateNode(PP, State, Pred);
  936. return;
  937. }
  938. ExplodedNodeSet CleanDtorState;
  939. StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
  940. StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
  941. QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
  942. // FIXME: Currently CleanDtorState can be empty here due to temporaries being
  943. // bound to default parameters.
  944. assert(CleanDtorState.size() <= 1);
  945. ExplodedNode *CleanPred =
  946. CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
  947. EvalCallOptions CallOpts;
  948. CallOpts.IsTemporaryCtorOrDtor = true;
  949. if (!MR) {
  950. CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
  951. // If we have no MR, we still need to unwrap the array to avoid destroying
  952. // the whole array at once. Regardless, we'd eventually need to model array
  953. // destructors properly, element-by-element.
  954. while (const ArrayType *AT = getContext().getAsArrayType(T)) {
  955. T = AT->getElementType();
  956. CallOpts.IsArrayCtorOrDtor = true;
  957. }
  958. } else {
  959. // We'd eventually need to makeZeroElementRegion() trick here,
  960. // but for now we don't have the respective construction contexts,
  961. // so MR would always be null in this case. Do nothing for now.
  962. }
  963. VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
  964. /*IsBase=*/false, CleanPred, Dst, CallOpts);
  965. }
  966. void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
  967. NodeBuilderContext &BldCtx,
  968. ExplodedNode *Pred,
  969. ExplodedNodeSet &Dst,
  970. const CFGBlock *DstT,
  971. const CFGBlock *DstF) {
  972. BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
  973. ProgramStateRef State = Pred->getState();
  974. const LocationContext *LC = Pred->getLocationContext();
  975. if (getObjectUnderConstruction(State, BTE, LC)) {
  976. TempDtorBuilder.markInfeasible(false);
  977. TempDtorBuilder.generateNode(State, true, Pred);
  978. } else {
  979. TempDtorBuilder.markInfeasible(true);
  980. TempDtorBuilder.generateNode(State, false, Pred);
  981. }
  982. }
  983. void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
  984. ExplodedNodeSet &PreVisit,
  985. ExplodedNodeSet &Dst) {
  986. // This is a fallback solution in case we didn't have a construction
  987. // context when we were constructing the temporary. Otherwise the map should
  988. // have been populated there.
  989. if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
  990. // In case we don't have temporary destructors in the CFG, do not mark
  991. // the initialization - we would otherwise never clean it up.
  992. Dst = PreVisit;
  993. return;
  994. }
  995. StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
  996. for (ExplodedNode *Node : PreVisit) {
  997. ProgramStateRef State = Node->getState();
  998. const LocationContext *LC = Node->getLocationContext();
  999. if (!getObjectUnderConstruction(State, BTE, LC)) {
  1000. // FIXME: Currently the state might also already contain the marker due to
  1001. // incorrect handling of temporaries bound to default parameters; for
  1002. // those, we currently skip the CXXBindTemporaryExpr but rely on adding
  1003. // temporary destructor nodes.
  1004. State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
  1005. }
  1006. StmtBldr.generateNode(BTE, Node, State);
  1007. }
  1008. }
  1009. ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
  1010. PointerEscapeKind K) const {
  1011. class CollectReachableSymbolsCallback final : public SymbolVisitor {
  1012. InvalidatedSymbols Symbols;
  1013. public:
  1014. explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
  1015. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  1016. bool VisitSymbol(SymbolRef Sym) override {
  1017. Symbols.insert(Sym);
  1018. return true;
  1019. }
  1020. };
  1021. const CollectReachableSymbolsCallback &Scanner =
  1022. State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
  1023. return getCheckerManager().runCheckersForPointerEscape(
  1024. State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
  1025. }
  1026. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  1027. ExplodedNodeSet &DstTop) {
  1028. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1029. S->getLocStart(),
  1030. "Error evaluating statement");
  1031. ExplodedNodeSet Dst;
  1032. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  1033. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  1034. switch (S->getStmtClass()) {
  1035. // C++, OpenMP and ARC stuff we don't support yet.
  1036. case Expr::ObjCIndirectCopyRestoreExprClass:
  1037. case Stmt::CXXDependentScopeMemberExprClass:
  1038. case Stmt::CXXInheritedCtorInitExprClass:
  1039. case Stmt::CXXTryStmtClass:
  1040. case Stmt::CXXTypeidExprClass:
  1041. case Stmt::CXXUuidofExprClass:
  1042. case Stmt::CXXFoldExprClass:
  1043. case Stmt::MSPropertyRefExprClass:
  1044. case Stmt::MSPropertySubscriptExprClass:
  1045. case Stmt::CXXUnresolvedConstructExprClass:
  1046. case Stmt::DependentScopeDeclRefExprClass:
  1047. case Stmt::ArrayTypeTraitExprClass:
  1048. case Stmt::ExpressionTraitExprClass:
  1049. case Stmt::UnresolvedLookupExprClass:
  1050. case Stmt::UnresolvedMemberExprClass:
  1051. case Stmt::TypoExprClass:
  1052. case Stmt::CXXNoexceptExprClass:
  1053. case Stmt::PackExpansionExprClass:
  1054. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  1055. case Stmt::FunctionParmPackExprClass:
  1056. case Stmt::CoroutineBodyStmtClass:
  1057. case Stmt::CoawaitExprClass:
  1058. case Stmt::DependentCoawaitExprClass:
  1059. case Stmt::CoreturnStmtClass:
  1060. case Stmt::CoyieldExprClass:
  1061. case Stmt::SEHTryStmtClass:
  1062. case Stmt::SEHExceptStmtClass:
  1063. case Stmt::SEHLeaveStmtClass:
  1064. case Stmt::SEHFinallyStmtClass:
  1065. case Stmt::OMPParallelDirectiveClass:
  1066. case Stmt::OMPSimdDirectiveClass:
  1067. case Stmt::OMPForDirectiveClass:
  1068. case Stmt::OMPForSimdDirectiveClass:
  1069. case Stmt::OMPSectionsDirectiveClass:
  1070. case Stmt::OMPSectionDirectiveClass:
  1071. case Stmt::OMPSingleDirectiveClass:
  1072. case Stmt::OMPMasterDirectiveClass:
  1073. case Stmt::OMPCriticalDirectiveClass:
  1074. case Stmt::OMPParallelForDirectiveClass:
  1075. case Stmt::OMPParallelForSimdDirectiveClass:
  1076. case Stmt::OMPParallelSectionsDirectiveClass:
  1077. case Stmt::OMPTaskDirectiveClass:
  1078. case Stmt::OMPTaskyieldDirectiveClass:
  1079. case Stmt::OMPBarrierDirectiveClass:
  1080. case Stmt::OMPTaskwaitDirectiveClass:
  1081. case Stmt::OMPTaskgroupDirectiveClass:
  1082. case Stmt::OMPFlushDirectiveClass:
  1083. case Stmt::OMPOrderedDirectiveClass:
  1084. case Stmt::OMPAtomicDirectiveClass:
  1085. case Stmt::OMPTargetDirectiveClass:
  1086. case Stmt::OMPTargetDataDirectiveClass:
  1087. case Stmt::OMPTargetEnterDataDirectiveClass:
  1088. case Stmt::OMPTargetExitDataDirectiveClass:
  1089. case Stmt::OMPTargetParallelDirectiveClass:
  1090. case Stmt::OMPTargetParallelForDirectiveClass:
  1091. case Stmt::OMPTargetUpdateDirectiveClass:
  1092. case Stmt::OMPTeamsDirectiveClass:
  1093. case Stmt::OMPCancellationPointDirectiveClass:
  1094. case Stmt::OMPCancelDirectiveClass:
  1095. case Stmt::OMPTaskLoopDirectiveClass:
  1096. case Stmt::OMPTaskLoopSimdDirectiveClass:
  1097. case Stmt::OMPDistributeDirectiveClass:
  1098. case Stmt::OMPDistributeParallelForDirectiveClass:
  1099. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  1100. case Stmt::OMPDistributeSimdDirectiveClass:
  1101. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  1102. case Stmt::OMPTargetSimdDirectiveClass:
  1103. case Stmt::OMPTeamsDistributeDirectiveClass:
  1104. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  1105. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  1106. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  1107. case Stmt::OMPTargetTeamsDirectiveClass:
  1108. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  1109. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  1110. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  1111. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  1112. case Stmt::CapturedStmtClass: {
  1113. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1114. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1115. break;
  1116. }
  1117. case Stmt::ParenExprClass:
  1118. llvm_unreachable("ParenExprs already handled.");
  1119. case Stmt::GenericSelectionExprClass:
  1120. llvm_unreachable("GenericSelectionExprs already handled.");
  1121. // Cases that should never be evaluated simply because they shouldn't
  1122. // appear in the CFG.
  1123. case Stmt::BreakStmtClass:
  1124. case Stmt::CaseStmtClass:
  1125. case Stmt::CompoundStmtClass:
  1126. case Stmt::ContinueStmtClass:
  1127. case Stmt::CXXForRangeStmtClass:
  1128. case Stmt::DefaultStmtClass:
  1129. case Stmt::DoStmtClass:
  1130. case Stmt::ForStmtClass:
  1131. case Stmt::GotoStmtClass:
  1132. case Stmt::IfStmtClass:
  1133. case Stmt::IndirectGotoStmtClass:
  1134. case Stmt::LabelStmtClass:
  1135. case Stmt::NoStmtClass:
  1136. case Stmt::NullStmtClass:
  1137. case Stmt::SwitchStmtClass:
  1138. case Stmt::WhileStmtClass:
  1139. case Expr::MSDependentExistsStmtClass:
  1140. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  1141. case Stmt::ObjCSubscriptRefExprClass:
  1142. case Stmt::ObjCPropertyRefExprClass:
  1143. llvm_unreachable("These are handled by PseudoObjectExpr");
  1144. case Stmt::GNUNullExprClass: {
  1145. // GNU __null is a pointer-width integer, not an actual pointer.
  1146. ProgramStateRef state = Pred->getState();
  1147. state = state->BindExpr(S, Pred->getLocationContext(),
  1148. svalBuilder.makeIntValWithPtrWidth(0, false));
  1149. Bldr.generateNode(S, Pred, state);
  1150. break;
  1151. }
  1152. case Stmt::ObjCAtSynchronizedStmtClass:
  1153. Bldr.takeNodes(Pred);
  1154. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  1155. Bldr.addNodes(Dst);
  1156. break;
  1157. case Stmt::ExprWithCleanupsClass:
  1158. // Handled due to fully linearised CFG.
  1159. break;
  1160. case Stmt::CXXBindTemporaryExprClass: {
  1161. Bldr.takeNodes(Pred);
  1162. ExplodedNodeSet PreVisit;
  1163. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1164. ExplodedNodeSet Next;
  1165. VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
  1166. getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
  1167. Bldr.addNodes(Dst);
  1168. break;
  1169. }
  1170. // Cases not handled yet; but will handle some day.
  1171. case Stmt::DesignatedInitExprClass:
  1172. case Stmt::DesignatedInitUpdateExprClass:
  1173. case Stmt::ArrayInitLoopExprClass:
  1174. case Stmt::ArrayInitIndexExprClass:
  1175. case Stmt::ExtVectorElementExprClass:
  1176. case Stmt::ImaginaryLiteralClass:
  1177. case Stmt::ObjCAtCatchStmtClass:
  1178. case Stmt::ObjCAtFinallyStmtClass:
  1179. case Stmt::ObjCAtTryStmtClass:
  1180. case Stmt::ObjCAutoreleasePoolStmtClass:
  1181. case Stmt::ObjCEncodeExprClass:
  1182. case Stmt::ObjCIsaExprClass:
  1183. case Stmt::ObjCProtocolExprClass:
  1184. case Stmt::ObjCSelectorExprClass:
  1185. case Stmt::ParenListExprClass:
  1186. case Stmt::ShuffleVectorExprClass:
  1187. case Stmt::ConvertVectorExprClass:
  1188. case Stmt::VAArgExprClass:
  1189. case Stmt::CUDAKernelCallExprClass:
  1190. case Stmt::OpaqueValueExprClass:
  1191. case Stmt::AsTypeExprClass:
  1192. // Fall through.
  1193. // Cases we intentionally don't evaluate, since they don't need
  1194. // to be explicitly evaluated.
  1195. case Stmt::PredefinedExprClass:
  1196. case Stmt::AddrLabelExprClass:
  1197. case Stmt::AttributedStmtClass:
  1198. case Stmt::IntegerLiteralClass:
  1199. case Stmt::FixedPointLiteralClass:
  1200. case Stmt::CharacterLiteralClass:
  1201. case Stmt::ImplicitValueInitExprClass:
  1202. case Stmt::CXXScalarValueInitExprClass:
  1203. case Stmt::CXXBoolLiteralExprClass:
  1204. case Stmt::ObjCBoolLiteralExprClass:
  1205. case Stmt::ObjCAvailabilityCheckExprClass:
  1206. case Stmt::FloatingLiteralClass:
  1207. case Stmt::NoInitExprClass:
  1208. case Stmt::SizeOfPackExprClass:
  1209. case Stmt::StringLiteralClass:
  1210. case Stmt::ObjCStringLiteralClass:
  1211. case Stmt::CXXPseudoDestructorExprClass:
  1212. case Stmt::SubstNonTypeTemplateParmExprClass:
  1213. case Stmt::CXXNullPtrLiteralExprClass:
  1214. case Stmt::OMPArraySectionExprClass:
  1215. case Stmt::TypeTraitExprClass: {
  1216. Bldr.takeNodes(Pred);
  1217. ExplodedNodeSet preVisit;
  1218. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1219. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  1220. Bldr.addNodes(Dst);
  1221. break;
  1222. }
  1223. case Stmt::CXXDefaultArgExprClass:
  1224. case Stmt::CXXDefaultInitExprClass: {
  1225. Bldr.takeNodes(Pred);
  1226. ExplodedNodeSet PreVisit;
  1227. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1228. ExplodedNodeSet Tmp;
  1229. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  1230. const Expr *ArgE;
  1231. if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  1232. ArgE = DefE->getExpr();
  1233. else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  1234. ArgE = DefE->getExpr();
  1235. else
  1236. llvm_unreachable("unknown constant wrapper kind");
  1237. bool IsTemporary = false;
  1238. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  1239. ArgE = MTE->GetTemporaryExpr();
  1240. IsTemporary = true;
  1241. }
  1242. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  1243. if (!ConstantVal)
  1244. ConstantVal = UnknownVal();
  1245. const LocationContext *LCtx = Pred->getLocationContext();
  1246. for (const auto I : PreVisit) {
  1247. ProgramStateRef State = I->getState();
  1248. State = State->BindExpr(S, LCtx, *ConstantVal);
  1249. if (IsTemporary)
  1250. State = createTemporaryRegionIfNeeded(State, LCtx,
  1251. cast<Expr>(S),
  1252. cast<Expr>(S));
  1253. Bldr2.generateNode(S, I, State);
  1254. }
  1255. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1256. Bldr.addNodes(Dst);
  1257. break;
  1258. }
  1259. // Cases we evaluate as opaque expressions, conjuring a symbol.
  1260. case Stmt::CXXStdInitializerListExprClass:
  1261. case Expr::ObjCArrayLiteralClass:
  1262. case Expr::ObjCDictionaryLiteralClass:
  1263. case Expr::ObjCBoxedExprClass: {
  1264. Bldr.takeNodes(Pred);
  1265. ExplodedNodeSet preVisit;
  1266. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1267. ExplodedNodeSet Tmp;
  1268. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  1269. const auto *Ex = cast<Expr>(S);
  1270. QualType resultType = Ex->getType();
  1271. for (const auto N : preVisit) {
  1272. const LocationContext *LCtx = N->getLocationContext();
  1273. SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  1274. resultType,
  1275. currBldrCtx->blockCount());
  1276. ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
  1277. // Escape pointers passed into the list, unless it's an ObjC boxed
  1278. // expression which is not a boxable C structure.
  1279. if (!(isa<ObjCBoxedExpr>(Ex) &&
  1280. !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
  1281. ->getType()->isRecordType()))
  1282. for (auto Child : Ex->children()) {
  1283. assert(Child);
  1284. SVal Val = State->getSVal(Child, LCtx);
  1285. State = escapeValue(State, Val, PSK_EscapeOther);
  1286. }
  1287. Bldr2.generateNode(S, N, State);
  1288. }
  1289. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1290. Bldr.addNodes(Dst);
  1291. break;
  1292. }
  1293. case Stmt::ArraySubscriptExprClass:
  1294. Bldr.takeNodes(Pred);
  1295. VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  1296. Bldr.addNodes(Dst);
  1297. break;
  1298. case Stmt::GCCAsmStmtClass:
  1299. Bldr.takeNodes(Pred);
  1300. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  1301. Bldr.addNodes(Dst);
  1302. break;
  1303. case Stmt::MSAsmStmtClass:
  1304. Bldr.takeNodes(Pred);
  1305. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  1306. Bldr.addNodes(Dst);
  1307. break;
  1308. case Stmt::BlockExprClass:
  1309. Bldr.takeNodes(Pred);
  1310. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  1311. Bldr.addNodes(Dst);
  1312. break;
  1313. case Stmt::LambdaExprClass:
  1314. if (AMgr.options.shouldInlineLambdas()) {
  1315. Bldr.takeNodes(Pred);
  1316. VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
  1317. Bldr.addNodes(Dst);
  1318. } else {
  1319. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1320. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1321. }
  1322. break;
  1323. case Stmt::BinaryOperatorClass: {
  1324. const auto *B = cast<BinaryOperator>(S);
  1325. if (B->isLogicalOp()) {
  1326. Bldr.takeNodes(Pred);
  1327. VisitLogicalExpr(B, Pred, Dst);
  1328. Bldr.addNodes(Dst);
  1329. break;
  1330. }
  1331. else if (B->getOpcode() == BO_Comma) {
  1332. ProgramStateRef state = Pred->getState();
  1333. Bldr.generateNode(B, Pred,
  1334. state->BindExpr(B, Pred->getLocationContext(),
  1335. state->getSVal(B->getRHS(),
  1336. Pred->getLocationContext())));
  1337. break;
  1338. }
  1339. Bldr.takeNodes(Pred);
  1340. if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
  1341. (B->isRelationalOp() || B->isEqualityOp())) {
  1342. ExplodedNodeSet Tmp;
  1343. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  1344. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  1345. }
  1346. else
  1347. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1348. Bldr.addNodes(Dst);
  1349. break;
  1350. }
  1351. case Stmt::CXXOperatorCallExprClass: {
  1352. const auto *OCE = cast<CXXOperatorCallExpr>(S);
  1353. // For instance method operators, make sure the 'this' argument has a
  1354. // valid region.
  1355. const Decl *Callee = OCE->getCalleeDecl();
  1356. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  1357. if (MD->isInstance()) {
  1358. ProgramStateRef State = Pred->getState();
  1359. const LocationContext *LCtx = Pred->getLocationContext();
  1360. ProgramStateRef NewState =
  1361. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  1362. if (NewState != State) {
  1363. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
  1364. ProgramPoint::PreStmtKind);
  1365. // Did we cache out?
  1366. if (!Pred)
  1367. break;
  1368. }
  1369. }
  1370. }
  1371. // FALLTHROUGH
  1372. LLVM_FALLTHROUGH;
  1373. }
  1374. case Stmt::CallExprClass:
  1375. case Stmt::CXXMemberCallExprClass:
  1376. case Stmt::UserDefinedLiteralClass:
  1377. Bldr.takeNodes(Pred);
  1378. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  1379. Bldr.addNodes(Dst);
  1380. break;
  1381. case Stmt::CXXCatchStmtClass:
  1382. Bldr.takeNodes(Pred);
  1383. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  1384. Bldr.addNodes(Dst);
  1385. break;
  1386. case Stmt::CXXTemporaryObjectExprClass:
  1387. case Stmt::CXXConstructExprClass:
  1388. Bldr.takeNodes(Pred);
  1389. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  1390. Bldr.addNodes(Dst);
  1391. break;
  1392. case Stmt::CXXNewExprClass: {
  1393. Bldr.takeNodes(Pred);
  1394. ExplodedNodeSet PreVisit;
  1395. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1396. ExplodedNodeSet PostVisit;
  1397. for (const auto i : PreVisit)
  1398. VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
  1399. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1400. Bldr.addNodes(Dst);
  1401. break;
  1402. }
  1403. case Stmt::CXXDeleteExprClass: {
  1404. Bldr.takeNodes(Pred);
  1405. ExplodedNodeSet PreVisit;
  1406. const auto *CDE = cast<CXXDeleteExpr>(S);
  1407. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1408. for (const auto i : PreVisit)
  1409. VisitCXXDeleteExpr(CDE, i, Dst);
  1410. Bldr.addNodes(Dst);
  1411. break;
  1412. }
  1413. // FIXME: ChooseExpr is really a constant. We need to fix
  1414. // the CFG do not model them as explicit control-flow.
  1415. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  1416. Bldr.takeNodes(Pred);
  1417. const auto *C = cast<ChooseExpr>(S);
  1418. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  1419. Bldr.addNodes(Dst);
  1420. break;
  1421. }
  1422. case Stmt::CompoundAssignOperatorClass:
  1423. Bldr.takeNodes(Pred);
  1424. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1425. Bldr.addNodes(Dst);
  1426. break;
  1427. case Stmt::CompoundLiteralExprClass:
  1428. Bldr.takeNodes(Pred);
  1429. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  1430. Bldr.addNodes(Dst);
  1431. break;
  1432. case Stmt::BinaryConditionalOperatorClass:
  1433. case Stmt::ConditionalOperatorClass: { // '?' operator
  1434. Bldr.takeNodes(Pred);
  1435. const auto *C = cast<AbstractConditionalOperator>(S);
  1436. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  1437. Bldr.addNodes(Dst);
  1438. break;
  1439. }
  1440. case Stmt::CXXThisExprClass:
  1441. Bldr.takeNodes(Pred);
  1442. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  1443. Bldr.addNodes(Dst);
  1444. break;
  1445. case Stmt::DeclRefExprClass: {
  1446. Bldr.takeNodes(Pred);
  1447. const auto *DE = cast<DeclRefExpr>(S);
  1448. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  1449. Bldr.addNodes(Dst);
  1450. break;
  1451. }
  1452. case Stmt::DeclStmtClass:
  1453. Bldr.takeNodes(Pred);
  1454. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  1455. Bldr.addNodes(Dst);
  1456. break;
  1457. case Stmt::ImplicitCastExprClass:
  1458. case Stmt::CStyleCastExprClass:
  1459. case Stmt::CXXStaticCastExprClass:
  1460. case Stmt::CXXDynamicCastExprClass:
  1461. case Stmt::CXXReinterpretCastExprClass:
  1462. case Stmt::CXXConstCastExprClass:
  1463. case Stmt::CXXFunctionalCastExprClass:
  1464. case Stmt::ObjCBridgedCastExprClass: {
  1465. Bldr.takeNodes(Pred);
  1466. const auto *C = cast<CastExpr>(S);
  1467. ExplodedNodeSet dstExpr;
  1468. VisitCast(C, C->getSubExpr(), Pred, dstExpr);
  1469. // Handle the postvisit checks.
  1470. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  1471. Bldr.addNodes(Dst);
  1472. break;
  1473. }
  1474. case Expr::MaterializeTemporaryExprClass: {
  1475. Bldr.takeNodes(Pred);
  1476. const auto *MTE = cast<MaterializeTemporaryExpr>(S);
  1477. ExplodedNodeSet dstPrevisit;
  1478. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
  1479. ExplodedNodeSet dstExpr;
  1480. for (const auto i : dstPrevisit)
  1481. CreateCXXTemporaryObject(MTE, i, dstExpr);
  1482. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
  1483. Bldr.addNodes(Dst);
  1484. break;
  1485. }
  1486. case Stmt::InitListExprClass:
  1487. Bldr.takeNodes(Pred);
  1488. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  1489. Bldr.addNodes(Dst);
  1490. break;
  1491. case Stmt::MemberExprClass:
  1492. Bldr.takeNodes(Pred);
  1493. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  1494. Bldr.addNodes(Dst);
  1495. break;
  1496. case Stmt::AtomicExprClass:
  1497. Bldr.takeNodes(Pred);
  1498. VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
  1499. Bldr.addNodes(Dst);
  1500. break;
  1501. case Stmt::ObjCIvarRefExprClass:
  1502. Bldr.takeNodes(Pred);
  1503. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  1504. Bldr.addNodes(Dst);
  1505. break;
  1506. case Stmt::ObjCForCollectionStmtClass:
  1507. Bldr.takeNodes(Pred);
  1508. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  1509. Bldr.addNodes(Dst);
  1510. break;
  1511. case Stmt::ObjCMessageExprClass:
  1512. Bldr.takeNodes(Pred);
  1513. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  1514. Bldr.addNodes(Dst);
  1515. break;
  1516. case Stmt::ObjCAtThrowStmtClass:
  1517. case Stmt::CXXThrowExprClass:
  1518. // FIXME: This is not complete. We basically treat @throw as
  1519. // an abort.
  1520. Bldr.generateSink(S, Pred, Pred->getState());
  1521. break;
  1522. case Stmt::ReturnStmtClass:
  1523. Bldr.takeNodes(Pred);
  1524. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  1525. Bldr.addNodes(Dst);
  1526. break;
  1527. case Stmt::OffsetOfExprClass: {
  1528. Bldr.takeNodes(Pred);
  1529. ExplodedNodeSet PreVisit;
  1530. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1531. ExplodedNodeSet PostVisit;
  1532. for (const auto Node : PreVisit)
  1533. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
  1534. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1535. Bldr.addNodes(Dst);
  1536. break;
  1537. }
  1538. case Stmt::UnaryExprOrTypeTraitExprClass:
  1539. Bldr.takeNodes(Pred);
  1540. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1541. Pred, Dst);
  1542. Bldr.addNodes(Dst);
  1543. break;
  1544. case Stmt::StmtExprClass: {
  1545. const auto *SE = cast<StmtExpr>(S);
  1546. if (SE->getSubStmt()->body_empty()) {
  1547. // Empty statement expression.
  1548. assert(SE->getType() == getContext().VoidTy
  1549. && "Empty statement expression must have void type.");
  1550. break;
  1551. }
  1552. if (const auto *LastExpr =
  1553. dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  1554. ProgramStateRef state = Pred->getState();
  1555. Bldr.generateNode(SE, Pred,
  1556. state->BindExpr(SE, Pred->getLocationContext(),
  1557. state->getSVal(LastExpr,
  1558. Pred->getLocationContext())));
  1559. }
  1560. break;
  1561. }
  1562. case Stmt::UnaryOperatorClass: {
  1563. Bldr.takeNodes(Pred);
  1564. const auto *U = cast<UnaryOperator>(S);
  1565. if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
  1566. ExplodedNodeSet Tmp;
  1567. VisitUnaryOperator(U, Pred, Tmp);
  1568. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  1569. }
  1570. else
  1571. VisitUnaryOperator(U, Pred, Dst);
  1572. Bldr.addNodes(Dst);
  1573. break;
  1574. }
  1575. case Stmt::PseudoObjectExprClass: {
  1576. Bldr.takeNodes(Pred);
  1577. ProgramStateRef state = Pred->getState();
  1578. const auto *PE = cast<PseudoObjectExpr>(S);
  1579. if (const Expr *Result = PE->getResultExpr()) {
  1580. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1581. Bldr.generateNode(S, Pred,
  1582. state->BindExpr(S, Pred->getLocationContext(), V));
  1583. }
  1584. else
  1585. Bldr.generateNode(S, Pred,
  1586. state->BindExpr(S, Pred->getLocationContext(),
  1587. UnknownVal()));
  1588. Bldr.addNodes(Dst);
  1589. break;
  1590. }
  1591. }
  1592. }
  1593. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1594. const LocationContext *CalleeLC) {
  1595. const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
  1596. const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
  1597. assert(CalleeSF && CallerSF);
  1598. ExplodedNode *BeforeProcessingCall = nullptr;
  1599. const Stmt *CE = CalleeSF->getCallSite();
  1600. // Find the first node before we started processing the call expression.
  1601. while (N) {
  1602. ProgramPoint L = N->getLocation();
  1603. BeforeProcessingCall = N;
  1604. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1605. // Skip the nodes corresponding to the inlined code.
  1606. if (L.getStackFrame() != CallerSF)
  1607. continue;
  1608. // We reached the caller. Find the node right before we started
  1609. // processing the call.
  1610. if (L.isPurgeKind())
  1611. continue;
  1612. if (L.getAs<PreImplicitCall>())
  1613. continue;
  1614. if (L.getAs<CallEnter>())
  1615. continue;
  1616. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1617. if (SP->getStmt() == CE)
  1618. continue;
  1619. break;
  1620. }
  1621. if (!BeforeProcessingCall)
  1622. return false;
  1623. // TODO: Clean up the unneeded nodes.
  1624. // Build an Epsilon node from which we will restart the analyzes.
  1625. // Note that CE is permitted to be NULL!
  1626. ProgramPoint NewNodeLoc =
  1627. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1628. // Add the special flag to GDM to signal retrying with no inlining.
  1629. // Note, changing the state ensures that we are not going to cache out.
  1630. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1631. NewNodeState =
  1632. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1633. // Make the new node a successor of BeforeProcessingCall.
  1634. bool IsNew = false;
  1635. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1636. // We cached out at this point. Caching out is common due to us backtracking
  1637. // from the inlined function, which might spawn several paths.
  1638. if (!IsNew)
  1639. return true;
  1640. NewNode->addPredecessor(BeforeProcessingCall, G);
  1641. // Add the new node to the work list.
  1642. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1643. CalleeSF->getIndex());
  1644. NumTimesRetriedWithoutInlining++;
  1645. return true;
  1646. }
  1647. /// Block entrance. (Update counters).
  1648. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1649. NodeBuilderWithSinks &nodeBuilder,
  1650. ExplodedNode *Pred) {
  1651. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1652. // If we reach a loop which has a known bound (and meets
  1653. // other constraints) then consider completely unrolling it.
  1654. if(AMgr.options.shouldUnrollLoops()) {
  1655. unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
  1656. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1657. if (Term) {
  1658. ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
  1659. Pred, maxBlockVisitOnPath);
  1660. if (NewState != Pred->getState()) {
  1661. ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
  1662. if (!UpdatedNode)
  1663. return;
  1664. Pred = UpdatedNode;
  1665. }
  1666. }
  1667. // Is we are inside an unrolled loop then no need the check the counters.
  1668. if(isUnrolledState(Pred->getState()))
  1669. return;
  1670. }
  1671. // If this block is terminated by a loop and it has already been visited the
  1672. // maximum number of times, widen the loop.
  1673. unsigned int BlockCount = nodeBuilder.getContext().blockCount();
  1674. if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
  1675. AMgr.options.shouldWidenLoops()) {
  1676. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1677. if (!(Term &&
  1678. (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
  1679. return;
  1680. // Widen.
  1681. const LocationContext *LCtx = Pred->getLocationContext();
  1682. ProgramStateRef WidenedState =
  1683. getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
  1684. nodeBuilder.generateNode(WidenedState, Pred);
  1685. return;
  1686. }
  1687. // FIXME: Refactor this into a checker.
  1688. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
  1689. static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
  1690. const ExplodedNode *Sink =
  1691. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1692. // Check if we stopped at the top level function or not.
  1693. // Root node should have the location context of the top most function.
  1694. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1695. const LocationContext *CalleeSF = CalleeLC->getStackFrame();
  1696. const LocationContext *RootLC =
  1697. (*G.roots_begin())->getLocation().getLocationContext();
  1698. if (RootLC->getStackFrame() != CalleeSF) {
  1699. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1700. // Re-run the call evaluation without inlining it, by storing the
  1701. // no-inlining policy in the state and enqueuing the new work item on
  1702. // the list. Replay should almost never fail. Use the stats to catch it
  1703. // if it does.
  1704. if ((!AMgr.options.NoRetryExhausted &&
  1705. replayWithoutInlining(Pred, CalleeLC)))
  1706. return;
  1707. NumMaxBlockCountReachedInInlined++;
  1708. } else
  1709. NumMaxBlockCountReached++;
  1710. // Make sink nodes as exhausted(for stats) only if retry failed.
  1711. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1712. }
  1713. }
  1714. //===----------------------------------------------------------------------===//
  1715. // Branch processing.
  1716. //===----------------------------------------------------------------------===//
  1717. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1718. /// to try to recover some path-sensitivity for casts of symbolic
  1719. /// integers that promote their values (which are currently not tracked well).
  1720. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1721. // cast(s) did was sign-extend the original value.
  1722. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  1723. ProgramStateRef state,
  1724. const Stmt *Condition,
  1725. const LocationContext *LCtx,
  1726. ASTContext &Ctx) {
  1727. const auto *Ex = dyn_cast<Expr>(Condition);
  1728. if (!Ex)
  1729. return UnknownVal();
  1730. uint64_t bits = 0;
  1731. bool bitsInit = false;
  1732. while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
  1733. QualType T = CE->getType();
  1734. if (!T->isIntegralOrEnumerationType())
  1735. return UnknownVal();
  1736. uint64_t newBits = Ctx.getTypeSize(T);
  1737. if (!bitsInit || newBits < bits) {
  1738. bitsInit = true;
  1739. bits = newBits;
  1740. }
  1741. Ex = CE->getSubExpr();
  1742. }
  1743. // We reached a non-cast. Is it a symbolic value?
  1744. QualType T = Ex->getType();
  1745. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1746. Ctx.getTypeSize(T) > bits)
  1747. return UnknownVal();
  1748. return state->getSVal(Ex, LCtx);
  1749. }
  1750. #ifndef NDEBUG
  1751. static const Stmt *getRightmostLeaf(const Stmt *Condition) {
  1752. while (Condition) {
  1753. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1754. if (!BO || !BO->isLogicalOp()) {
  1755. return Condition;
  1756. }
  1757. Condition = BO->getRHS()->IgnoreParens();
  1758. }
  1759. return nullptr;
  1760. }
  1761. #endif
  1762. // Returns the condition the branch at the end of 'B' depends on and whose value
  1763. // has been evaluated within 'B'.
  1764. // In most cases, the terminator condition of 'B' will be evaluated fully in
  1765. // the last statement of 'B'; in those cases, the resolved condition is the
  1766. // given 'Condition'.
  1767. // If the condition of the branch is a logical binary operator tree, the CFG is
  1768. // optimized: in that case, we know that the expression formed by all but the
  1769. // rightmost leaf of the logical binary operator tree must be true, and thus
  1770. // the branch condition is at this point equivalent to the truth value of that
  1771. // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
  1772. // expression in its final statement. As the full condition in that case was
  1773. // not evaluated, and is thus not in the SVal cache, we need to use that leaf
  1774. // expression to evaluate the truth value of the condition in the current state
  1775. // space.
  1776. static const Stmt *ResolveCondition(const Stmt *Condition,
  1777. const CFGBlock *B) {
  1778. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1779. Condition = Ex->IgnoreParens();
  1780. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1781. if (!BO || !BO->isLogicalOp())
  1782. return Condition;
  1783. assert(!B->getTerminator().isTemporaryDtorsBranch() &&
  1784. "Temporary destructor branches handled by processBindTemporary.");
  1785. // For logical operations, we still have the case where some branches
  1786. // use the traditional "merge" approach and others sink the branch
  1787. // directly into the basic blocks representing the logical operation.
  1788. // We need to distinguish between those two cases here.
  1789. // The invariants are still shifting, but it is possible that the
  1790. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1791. // CFGStmt as the value of the condition.
  1792. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1793. for (; I != E; ++I) {
  1794. CFGElement Elem = *I;
  1795. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1796. if (!CS)
  1797. continue;
  1798. const Stmt *LastStmt = CS->getStmt();
  1799. assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
  1800. return LastStmt;
  1801. }
  1802. llvm_unreachable("could not resolve condition");
  1803. }
  1804. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1805. NodeBuilderContext& BldCtx,
  1806. ExplodedNode *Pred,
  1807. ExplodedNodeSet &Dst,
  1808. const CFGBlock *DstT,
  1809. const CFGBlock *DstF) {
  1810. assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
  1811. "CXXBindTemporaryExprs are handled by processBindTemporary.");
  1812. const LocationContext *LCtx = Pred->getLocationContext();
  1813. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1814. currBldrCtx = &BldCtx;
  1815. // Check for NULL conditions; e.g. "for(;;)"
  1816. if (!Condition) {
  1817. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1818. NullCondBldr.markInfeasible(false);
  1819. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1820. return;
  1821. }
  1822. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1823. Condition = Ex->IgnoreParens();
  1824. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1825. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1826. Condition->getLocStart(),
  1827. "Error evaluating branch");
  1828. ExplodedNodeSet CheckersOutSet;
  1829. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1830. Pred, *this);
  1831. // We generated only sinks.
  1832. if (CheckersOutSet.empty())
  1833. return;
  1834. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1835. for (const auto PredI : CheckersOutSet) {
  1836. if (PredI->isSink())
  1837. continue;
  1838. ProgramStateRef PrevState = PredI->getState();
  1839. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1840. if (X.isUnknownOrUndef()) {
  1841. // Give it a chance to recover from unknown.
  1842. if (const auto *Ex = dyn_cast<Expr>(Condition)) {
  1843. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1844. // Try to recover some path-sensitivity. Right now casts of symbolic
  1845. // integers that promote their values are currently not tracked well.
  1846. // If 'Condition' is such an expression, try and recover the
  1847. // underlying value and use that instead.
  1848. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1849. PrevState, Condition,
  1850. PredI->getLocationContext(),
  1851. getContext());
  1852. if (!recovered.isUnknown()) {
  1853. X = recovered;
  1854. }
  1855. }
  1856. }
  1857. }
  1858. // If the condition is still unknown, give up.
  1859. if (X.isUnknownOrUndef()) {
  1860. builder.generateNode(PrevState, true, PredI);
  1861. builder.generateNode(PrevState, false, PredI);
  1862. continue;
  1863. }
  1864. DefinedSVal V = X.castAs<DefinedSVal>();
  1865. ProgramStateRef StTrue, StFalse;
  1866. std::tie(StTrue, StFalse) = PrevState->assume(V);
  1867. // Process the true branch.
  1868. if (builder.isFeasible(true)) {
  1869. if (StTrue)
  1870. builder.generateNode(StTrue, true, PredI);
  1871. else
  1872. builder.markInfeasible(true);
  1873. }
  1874. // Process the false branch.
  1875. if (builder.isFeasible(false)) {
  1876. if (StFalse)
  1877. builder.generateNode(StFalse, false, PredI);
  1878. else
  1879. builder.markInfeasible(false);
  1880. }
  1881. }
  1882. currBldrCtx = nullptr;
  1883. }
  1884. /// The GDM component containing the set of global variables which have been
  1885. /// previously initialized with explicit initializers.
  1886. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1887. llvm::ImmutableSet<const VarDecl *>)
  1888. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1889. NodeBuilderContext &BuilderCtx,
  1890. ExplodedNode *Pred,
  1891. ExplodedNodeSet &Dst,
  1892. const CFGBlock *DstT,
  1893. const CFGBlock *DstF) {
  1894. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1895. currBldrCtx = &BuilderCtx;
  1896. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  1897. ProgramStateRef state = Pred->getState();
  1898. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1899. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1900. if (!initHasRun) {
  1901. state = state->add<InitializedGlobalsSet>(VD);
  1902. }
  1903. builder.generateNode(state, initHasRun, Pred);
  1904. builder.markInfeasible(!initHasRun);
  1905. currBldrCtx = nullptr;
  1906. }
  1907. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1908. /// nodes by processing the 'effects' of a computed goto jump.
  1909. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1910. ProgramStateRef state = builder.getState();
  1911. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1912. // Three possibilities:
  1913. //
  1914. // (1) We know the computed label.
  1915. // (2) The label is NULL (or some other constant), or Undefined.
  1916. // (3) We have no clue about the label. Dispatch to all targets.
  1917. //
  1918. using iterator = IndirectGotoNodeBuilder::iterator;
  1919. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1920. const LabelDecl *L = LV->getLabel();
  1921. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1922. if (I.getLabel() == L) {
  1923. builder.generateNode(I, state);
  1924. return;
  1925. }
  1926. }
  1927. llvm_unreachable("No block with label.");
  1928. }
  1929. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1930. // Dispatch to the first target and mark it as a sink.
  1931. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1932. // FIXME: add checker visit.
  1933. // UndefBranches.insert(N);
  1934. return;
  1935. }
  1936. // This is really a catch-all. We don't support symbolics yet.
  1937. // FIXME: Implement dispatch for symbolic pointers.
  1938. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
  1939. builder.generateNode(I, state);
  1940. }
  1941. void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
  1942. ExplodedNode *Pred,
  1943. ExplodedNodeSet &Dst,
  1944. const BlockEdge &L) {
  1945. SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
  1946. getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
  1947. }
  1948. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1949. /// nodes when the control reaches the end of a function.
  1950. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1951. ExplodedNode *Pred,
  1952. const ReturnStmt *RS) {
  1953. // FIXME: We currently cannot assert that temporaries are clear, because
  1954. // lifetime extended temporaries are not always modelled correctly. In some
  1955. // cases when we materialize the temporary, we do
  1956. // createTemporaryRegionIfNeeded(), and the region changes, and also the
  1957. // respective destructor becomes automatic from temporary. So for now clean up
  1958. // the state manually before asserting. Ideally, the code above the assertion
  1959. // should go away, but the assertion should remain.
  1960. {
  1961. ExplodedNodeSet CleanUpObjects;
  1962. NodeBuilder Bldr(Pred, CleanUpObjects, BC);
  1963. ProgramStateRef State = Pred->getState();
  1964. const LocationContext *FromLC = Pred->getLocationContext();
  1965. const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
  1966. const LocationContext *LC = FromLC;
  1967. while (LC != ToLC) {
  1968. assert(LC && "ToLC must be a parent of FromLC!");
  1969. for (auto I : State->get<ObjectsUnderConstruction>())
  1970. if (I.first.getLocationContext() == LC) {
  1971. // The comment above only pardons us for not cleaning up a
  1972. // CXXBindTemporaryExpr. If any other statements are found here,
  1973. // it must be a separate problem.
  1974. assert(isa<CXXBindTemporaryExpr>(I.first.getStmt()));
  1975. State = State->remove<ObjectsUnderConstruction>(I.first);
  1976. // Also cleanup the elided destructor info.
  1977. ElidedDestructorItem Item(
  1978. cast<CXXBindTemporaryExpr>(I.first.getStmt()),
  1979. I.first.getLocationContext());
  1980. State = State->remove<ElidedDestructors>(Item);
  1981. }
  1982. // Also suppress the assertion for elided destructors when temporary
  1983. // destructors are not provided at all by the CFG, because there's no
  1984. // good place to clean them up.
  1985. if (!AMgr.getAnalyzerOptions().includeTemporaryDtorsInCFG())
  1986. for (auto I : State->get<ElidedDestructors>())
  1987. if (I.second == LC)
  1988. State = State->remove<ElidedDestructors>(I);
  1989. LC = LC->getParent();
  1990. }
  1991. if (State != Pred->getState()) {
  1992. Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
  1993. if (!Pred) {
  1994. // The node with clean temporaries already exists. We might have reached
  1995. // it on a path on which we initialize different temporaries.
  1996. return;
  1997. }
  1998. }
  1999. }
  2000. assert(areAllObjectsFullyConstructed(Pred->getState(),
  2001. Pred->getLocationContext(),
  2002. Pred->getStackFrame()->getParent()));
  2003. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  2004. StateMgr.EndPath(Pred->getState());
  2005. ExplodedNodeSet Dst;
  2006. if (Pred->getLocationContext()->inTopFrame()) {
  2007. // Remove dead symbols.
  2008. ExplodedNodeSet AfterRemovedDead;
  2009. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  2010. // Notify checkers.
  2011. for (const auto I : AfterRemovedDead)
  2012. getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this);
  2013. } else {
  2014. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
  2015. }
  2016. Engine.enqueueEndOfFunction(Dst, RS);
  2017. }
  2018. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  2019. /// nodes by processing the 'effects' of a switch statement.
  2020. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  2021. using iterator = SwitchNodeBuilder::iterator;
  2022. ProgramStateRef state = builder.getState();
  2023. const Expr *CondE = builder.getCondition();
  2024. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  2025. if (CondV_untested.isUndef()) {
  2026. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  2027. // FIXME: add checker
  2028. //UndefBranches.insert(N);
  2029. return;
  2030. }
  2031. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  2032. ProgramStateRef DefaultSt = state;
  2033. iterator I = builder.begin(), EI = builder.end();
  2034. bool defaultIsFeasible = I == EI;
  2035. for ( ; I != EI; ++I) {
  2036. // Successor may be pruned out during CFG construction.
  2037. if (!I.getBlock())
  2038. continue;
  2039. const CaseStmt *Case = I.getCase();
  2040. // Evaluate the LHS of the case value.
  2041. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  2042. assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
  2043. // Get the RHS of the case, if it exists.
  2044. llvm::APSInt V2;
  2045. if (const Expr *E = Case->getRHS())
  2046. V2 = E->EvaluateKnownConstInt(getContext());
  2047. else
  2048. V2 = V1;
  2049. ProgramStateRef StateCase;
  2050. if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
  2051. std::tie(StateCase, DefaultSt) =
  2052. DefaultSt->assumeInclusiveRange(*NL, V1, V2);
  2053. else // UnknownVal
  2054. StateCase = DefaultSt;
  2055. if (StateCase)
  2056. builder.generateCaseStmtNode(I, StateCase);
  2057. // Now "assume" that the case doesn't match. Add this state
  2058. // to the default state (if it is feasible).
  2059. if (DefaultSt)
  2060. defaultIsFeasible = true;
  2061. else {
  2062. defaultIsFeasible = false;
  2063. break;
  2064. }
  2065. }
  2066. if (!defaultIsFeasible)
  2067. return;
  2068. // If we have switch(enum value), the default branch is not
  2069. // feasible if all of the enum constants not covered by 'case:' statements
  2070. // are not feasible values for the switch condition.
  2071. //
  2072. // Note that this isn't as accurate as it could be. Even if there isn't
  2073. // a case for a particular enum value as long as that enum value isn't
  2074. // feasible then it shouldn't be considered for making 'default:' reachable.
  2075. const SwitchStmt *SS = builder.getSwitch();
  2076. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  2077. if (CondExpr->getType()->getAs<EnumType>()) {
  2078. if (SS->isAllEnumCasesCovered())
  2079. return;
  2080. }
  2081. builder.generateDefaultCaseNode(DefaultSt);
  2082. }
  2083. //===----------------------------------------------------------------------===//
  2084. // Transfer functions: Loads and stores.
  2085. //===----------------------------------------------------------------------===//
  2086. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  2087. ExplodedNode *Pred,
  2088. ExplodedNodeSet &Dst) {
  2089. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2090. ProgramStateRef state = Pred->getState();
  2091. const LocationContext *LCtx = Pred->getLocationContext();
  2092. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2093. // C permits "extern void v", and if you cast the address to a valid type,
  2094. // you can even do things with it. We simply pretend
  2095. assert(Ex->isGLValue() || VD->getType()->isVoidType());
  2096. const LocationContext *LocCtxt = Pred->getLocationContext();
  2097. const Decl *D = LocCtxt->getDecl();
  2098. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  2099. const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
  2100. Optional<std::pair<SVal, QualType>> VInfo;
  2101. if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
  2102. DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
  2103. MD->getParent()->isLambda()) {
  2104. // Lookup the field of the lambda.
  2105. const CXXRecordDecl *CXXRec = MD->getParent();
  2106. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  2107. FieldDecl *LambdaThisCaptureField;
  2108. CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
  2109. // Sema follows a sequence of complex rules to determine whether the
  2110. // variable should be captured.
  2111. if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
  2112. Loc CXXThis =
  2113. svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
  2114. SVal CXXThisVal = state->getSVal(CXXThis);
  2115. VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
  2116. }
  2117. }
  2118. if (!VInfo)
  2119. VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
  2120. SVal V = VInfo->first;
  2121. bool IsReference = VInfo->second->isReferenceType();
  2122. // For references, the 'lvalue' is the pointer address stored in the
  2123. // reference region.
  2124. if (IsReference) {
  2125. if (const MemRegion *R = V.getAsRegion())
  2126. V = state->getSVal(R);
  2127. else
  2128. V = UnknownVal();
  2129. }
  2130. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2131. ProgramPoint::PostLValueKind);
  2132. return;
  2133. }
  2134. if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
  2135. assert(!Ex->isGLValue());
  2136. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  2137. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  2138. return;
  2139. }
  2140. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2141. SVal V = svalBuilder.getFunctionPointer(FD);
  2142. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2143. ProgramPoint::PostLValueKind);
  2144. return;
  2145. }
  2146. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
  2147. // FIXME: Compute lvalue of field pointers-to-member.
  2148. // Right now we just use a non-null void pointer, so that it gives proper
  2149. // results in boolean contexts.
  2150. // FIXME: Maybe delegate this to the surrounding operator&.
  2151. // Note how this expression is lvalue, however pointer-to-member is NonLoc.
  2152. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  2153. currBldrCtx->blockCount());
  2154. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  2155. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2156. ProgramPoint::PostLValueKind);
  2157. return;
  2158. }
  2159. if (isa<BindingDecl>(D)) {
  2160. // FIXME: proper support for bound declarations.
  2161. // For now, let's just prevent crashing.
  2162. return;
  2163. }
  2164. llvm_unreachable("Support for this Decl not implemented.");
  2165. }
  2166. /// VisitArraySubscriptExpr - Transfer function for array accesses
  2167. void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
  2168. ExplodedNode *Pred,
  2169. ExplodedNodeSet &Dst){
  2170. const Expr *Base = A->getBase()->IgnoreParens();
  2171. const Expr *Idx = A->getIdx()->IgnoreParens();
  2172. ExplodedNodeSet CheckerPreStmt;
  2173. getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
  2174. ExplodedNodeSet EvalSet;
  2175. StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
  2176. bool IsVectorType = A->getBase()->getType()->isVectorType();
  2177. // The "like" case is for situations where C standard prohibits the type to
  2178. // be an lvalue, e.g. taking the address of a subscript of an expression of
  2179. // type "void *".
  2180. bool IsGLValueLike = A->isGLValue() ||
  2181. (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
  2182. for (auto *Node : CheckerPreStmt) {
  2183. const LocationContext *LCtx = Node->getLocationContext();
  2184. ProgramStateRef state = Node->getState();
  2185. if (IsGLValueLike) {
  2186. QualType T = A->getType();
  2187. // One of the forbidden LValue types! We still need to have sensible
  2188. // symbolic locations to represent this stuff. Note that arithmetic on
  2189. // void pointers is a GCC extension.
  2190. if (T->isVoidType())
  2191. T = getContext().CharTy;
  2192. SVal V = state->getLValue(T,
  2193. state->getSVal(Idx, LCtx),
  2194. state->getSVal(Base, LCtx));
  2195. Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
  2196. ProgramPoint::PostLValueKind);
  2197. } else if (IsVectorType) {
  2198. // FIXME: non-glvalue vector reads are not modelled.
  2199. Bldr.generateNode(A, Node, state, nullptr);
  2200. } else {
  2201. llvm_unreachable("Array subscript should be an lValue when not \
  2202. a vector and not a forbidden lvalue type");
  2203. }
  2204. }
  2205. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
  2206. }
  2207. /// VisitMemberExpr - Transfer function for member expressions.
  2208. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  2209. ExplodedNodeSet &Dst) {
  2210. // FIXME: Prechecks eventually go in ::Visit().
  2211. ExplodedNodeSet CheckedSet;
  2212. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
  2213. ExplodedNodeSet EvalSet;
  2214. ValueDecl *Member = M->getMemberDecl();
  2215. // Handle static member variables and enum constants accessed via
  2216. // member syntax.
  2217. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  2218. for (const auto I : CheckedSet)
  2219. VisitCommonDeclRefExpr(M, Member, I, EvalSet);
  2220. } else {
  2221. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  2222. ExplodedNodeSet Tmp;
  2223. for (const auto I : CheckedSet) {
  2224. ProgramStateRef state = I->getState();
  2225. const LocationContext *LCtx = I->getLocationContext();
  2226. Expr *BaseExpr = M->getBase();
  2227. // Handle C++ method calls.
  2228. if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
  2229. if (MD->isInstance())
  2230. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  2231. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  2232. state = state->BindExpr(M, LCtx, MDVal);
  2233. Bldr.generateNode(M, I, state);
  2234. continue;
  2235. }
  2236. // Handle regular struct fields / member variables.
  2237. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  2238. SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
  2239. const auto *field = cast<FieldDecl>(Member);
  2240. SVal L = state->getLValue(field, baseExprVal);
  2241. if (M->isGLValue() || M->getType()->isArrayType()) {
  2242. // We special-case rvalues of array type because the analyzer cannot
  2243. // reason about them, since we expect all regions to be wrapped in Locs.
  2244. // We instead treat these as lvalues and assume that they will decay to
  2245. // pointers as soon as they are used.
  2246. if (!M->isGLValue()) {
  2247. assert(M->getType()->isArrayType());
  2248. const auto *PE =
  2249. dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
  2250. if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
  2251. llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
  2252. }
  2253. }
  2254. if (field->getType()->isReferenceType()) {
  2255. if (const MemRegion *R = L.getAsRegion())
  2256. L = state->getSVal(R);
  2257. else
  2258. L = UnknownVal();
  2259. }
  2260. Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
  2261. ProgramPoint::PostLValueKind);
  2262. } else {
  2263. Bldr.takeNodes(I);
  2264. evalLoad(Tmp, M, M, I, state, L);
  2265. Bldr.addNodes(Tmp);
  2266. }
  2267. }
  2268. }
  2269. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
  2270. }
  2271. void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
  2272. ExplodedNodeSet &Dst) {
  2273. ExplodedNodeSet AfterPreSet;
  2274. getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
  2275. // For now, treat all the arguments to C11 atomics as escaping.
  2276. // FIXME: Ideally we should model the behavior of the atomics precisely here.
  2277. ExplodedNodeSet AfterInvalidateSet;
  2278. StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
  2279. for (const auto I : AfterPreSet) {
  2280. ProgramStateRef State = I->getState();
  2281. const LocationContext *LCtx = I->getLocationContext();
  2282. SmallVector<SVal, 8> ValuesToInvalidate;
  2283. for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
  2284. const Expr *SubExpr = AE->getSubExprs()[SI];
  2285. SVal SubExprVal = State->getSVal(SubExpr, LCtx);
  2286. ValuesToInvalidate.push_back(SubExprVal);
  2287. }
  2288. State = State->invalidateRegions(ValuesToInvalidate, AE,
  2289. currBldrCtx->blockCount(),
  2290. LCtx,
  2291. /*CausedByPointerEscape*/true,
  2292. /*Symbols=*/nullptr);
  2293. SVal ResultVal = UnknownVal();
  2294. State = State->BindExpr(AE, LCtx, ResultVal);
  2295. Bldr.generateNode(AE, I, State, nullptr,
  2296. ProgramPoint::PostStmtKind);
  2297. }
  2298. getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
  2299. }
  2300. // A value escapes in three possible cases:
  2301. // (1) We are binding to something that is not a memory region.
  2302. // (2) We are binding to a MemrRegion that does not have stack storage.
  2303. // (3) We are binding to a MemRegion with stack storage that the store
  2304. // does not understand.
  2305. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  2306. SVal Loc,
  2307. SVal Val,
  2308. const LocationContext *LCtx) {
  2309. // Are we storing to something that causes the value to "escape"?
  2310. bool escapes = true;
  2311. // TODO: Move to StoreManager.
  2312. if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
  2313. escapes = !regionLoc->getRegion()->hasStackStorage();
  2314. if (!escapes) {
  2315. // To test (3), generate a new state with the binding added. If it is
  2316. // the same state, then it escapes (since the store cannot represent
  2317. // the binding).
  2318. // Do this only if we know that the store is not supposed to generate the
  2319. // same state.
  2320. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  2321. if (StoredVal != Val)
  2322. escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
  2323. }
  2324. }
  2325. // If our store can represent the binding and we aren't storing to something
  2326. // that doesn't have local storage then just return and have the simulation
  2327. // state continue as is.
  2328. if (!escapes)
  2329. return State;
  2330. // Otherwise, find all symbols referenced by 'val' that we are tracking
  2331. // and stop tracking them.
  2332. State = escapeValue(State, Val, PSK_EscapeOnBind);
  2333. return State;
  2334. }
  2335. ProgramStateRef
  2336. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  2337. const InvalidatedSymbols *Invalidated,
  2338. ArrayRef<const MemRegion *> ExplicitRegions,
  2339. ArrayRef<const MemRegion *> Regions,
  2340. const CallEvent *Call,
  2341. RegionAndSymbolInvalidationTraits &ITraits) {
  2342. if (!Invalidated || Invalidated->empty())
  2343. return State;
  2344. if (!Call)
  2345. return getCheckerManager().runCheckersForPointerEscape(State,
  2346. *Invalidated,
  2347. nullptr,
  2348. PSK_EscapeOther,
  2349. &ITraits);
  2350. // If the symbols were invalidated by a call, we want to find out which ones
  2351. // were invalidated directly due to being arguments to the call.
  2352. InvalidatedSymbols SymbolsDirectlyInvalidated;
  2353. for (const auto I : ExplicitRegions) {
  2354. if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
  2355. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  2356. }
  2357. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  2358. for (const auto &sym : *Invalidated) {
  2359. if (SymbolsDirectlyInvalidated.count(sym))
  2360. continue;
  2361. SymbolsIndirectlyInvalidated.insert(sym);
  2362. }
  2363. if (!SymbolsDirectlyInvalidated.empty())
  2364. State = getCheckerManager().runCheckersForPointerEscape(State,
  2365. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  2366. // Notify about the symbols that get indirectly invalidated by the call.
  2367. if (!SymbolsIndirectlyInvalidated.empty())
  2368. State = getCheckerManager().runCheckersForPointerEscape(State,
  2369. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  2370. return State;
  2371. }
  2372. /// evalBind - Handle the semantics of binding a value to a specific location.
  2373. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  2374. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  2375. ExplodedNode *Pred,
  2376. SVal location, SVal Val,
  2377. bool atDeclInit, const ProgramPoint *PP) {
  2378. const LocationContext *LC = Pred->getLocationContext();
  2379. PostStmt PS(StoreE, LC);
  2380. if (!PP)
  2381. PP = &PS;
  2382. // Do a previsit of the bind.
  2383. ExplodedNodeSet CheckedSet;
  2384. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  2385. StoreE, *this, *PP);
  2386. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  2387. // If the location is not a 'Loc', it will already be handled by
  2388. // the checkers. There is nothing left to do.
  2389. if (!location.getAs<Loc>()) {
  2390. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
  2391. /*tag*/nullptr);
  2392. ProgramStateRef state = Pred->getState();
  2393. state = processPointerEscapedOnBind(state, location, Val, LC);
  2394. Bldr.generateNode(L, state, Pred);
  2395. return;
  2396. }
  2397. for (const auto PredI : CheckedSet) {
  2398. ProgramStateRef state = PredI->getState();
  2399. state = processPointerEscapedOnBind(state, location, Val, LC);
  2400. // When binding the value, pass on the hint that this is a initialization.
  2401. // For initializations, we do not need to inform clients of region
  2402. // changes.
  2403. state = state->bindLoc(location.castAs<Loc>(),
  2404. Val, LC, /* notifyChanges = */ !atDeclInit);
  2405. const MemRegion *LocReg = nullptr;
  2406. if (Optional<loc::MemRegionVal> LocRegVal =
  2407. location.getAs<loc::MemRegionVal>()) {
  2408. LocReg = LocRegVal->getRegion();
  2409. }
  2410. const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
  2411. Bldr.generateNode(L, state, PredI);
  2412. }
  2413. }
  2414. /// evalStore - Handle the semantics of a store via an assignment.
  2415. /// @param Dst The node set to store generated state nodes
  2416. /// @param AssignE The assignment expression if the store happens in an
  2417. /// assignment.
  2418. /// @param LocationE The location expression that is stored to.
  2419. /// @param state The current simulation state
  2420. /// @param location The location to store the value
  2421. /// @param Val The value to be stored
  2422. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  2423. const Expr *LocationE,
  2424. ExplodedNode *Pred,
  2425. ProgramStateRef state, SVal location, SVal Val,
  2426. const ProgramPointTag *tag) {
  2427. // Proceed with the store. We use AssignE as the anchor for the PostStore
  2428. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  2429. const Expr *StoreE = AssignE ? AssignE : LocationE;
  2430. // Evaluate the location (checks for bad dereferences).
  2431. ExplodedNodeSet Tmp;
  2432. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  2433. if (Tmp.empty())
  2434. return;
  2435. if (location.isUndef())
  2436. return;
  2437. for (const auto I : Tmp)
  2438. evalBind(Dst, StoreE, I, location, Val, false);
  2439. }
  2440. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  2441. const Expr *NodeEx,
  2442. const Expr *BoundEx,
  2443. ExplodedNode *Pred,
  2444. ProgramStateRef state,
  2445. SVal location,
  2446. const ProgramPointTag *tag,
  2447. QualType LoadTy) {
  2448. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  2449. assert(NodeEx);
  2450. assert(BoundEx);
  2451. // Evaluate the location (checks for bad dereferences).
  2452. ExplodedNodeSet Tmp;
  2453. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  2454. if (Tmp.empty())
  2455. return;
  2456. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  2457. if (location.isUndef())
  2458. return;
  2459. // Proceed with the load.
  2460. for (const auto I : Tmp) {
  2461. state = I->getState();
  2462. const LocationContext *LCtx = I->getLocationContext();
  2463. SVal V = UnknownVal();
  2464. if (location.isValid()) {
  2465. if (LoadTy.isNull())
  2466. LoadTy = BoundEx->getType();
  2467. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  2468. }
  2469. Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
  2470. ProgramPoint::PostLoadKind);
  2471. }
  2472. }
  2473. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  2474. const Stmt *NodeEx,
  2475. const Stmt *BoundEx,
  2476. ExplodedNode *Pred,
  2477. ProgramStateRef state,
  2478. SVal location,
  2479. const ProgramPointTag *tag,
  2480. bool isLoad) {
  2481. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  2482. // Early checks for performance reason.
  2483. if (location.isUnknown()) {
  2484. return;
  2485. }
  2486. ExplodedNodeSet Src;
  2487. BldrTop.takeNodes(Pred);
  2488. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  2489. if (Pred->getState() != state) {
  2490. // Associate this new state with an ExplodedNode.
  2491. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  2492. // int *p;
  2493. // p = 0;
  2494. // *p = 0xDEADBEEF;
  2495. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  2496. // instead "int *p" is noted as
  2497. // "Variable 'p' initialized to a null pointer value"
  2498. static SimpleProgramPointTag tag(TagProviderName, "Location");
  2499. Bldr.generateNode(NodeEx, Pred, state, &tag);
  2500. }
  2501. ExplodedNodeSet Tmp;
  2502. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  2503. NodeEx, BoundEx, *this);
  2504. BldrTop.addNodes(Tmp);
  2505. }
  2506. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  2507. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  2508. static SimpleProgramPointTag
  2509. eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
  2510. "Eagerly Assume True"),
  2511. eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
  2512. "Eagerly Assume False");
  2513. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  2514. &eagerlyAssumeBinOpBifurcationFalse);
  2515. }
  2516. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  2517. ExplodedNodeSet &Src,
  2518. const Expr *Ex) {
  2519. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  2520. for (const auto Pred : Src) {
  2521. // Test if the previous node was as the same expression. This can happen
  2522. // when the expression fails to evaluate to anything meaningful and
  2523. // (as an optimization) we don't generate a node.
  2524. ProgramPoint P = Pred->getLocation();
  2525. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  2526. continue;
  2527. }
  2528. ProgramStateRef state = Pred->getState();
  2529. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  2530. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  2531. if (SEV && SEV->isExpression()) {
  2532. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  2533. geteagerlyAssumeBinOpBifurcationTags();
  2534. ProgramStateRef StateTrue, StateFalse;
  2535. std::tie(StateTrue, StateFalse) = state->assume(*SEV);
  2536. // First assume that the condition is true.
  2537. if (StateTrue) {
  2538. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  2539. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  2540. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  2541. }
  2542. // Next, assume that the condition is false.
  2543. if (StateFalse) {
  2544. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  2545. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  2546. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  2547. }
  2548. }
  2549. }
  2550. }
  2551. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  2552. ExplodedNodeSet &Dst) {
  2553. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2554. // We have processed both the inputs and the outputs. All of the outputs
  2555. // should evaluate to Locs. Nuke all of their values.
  2556. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2557. // which interprets the inline asm and stores proper results in the
  2558. // outputs.
  2559. ProgramStateRef state = Pred->getState();
  2560. for (const Expr *O : A->outputs()) {
  2561. SVal X = state->getSVal(O, Pred->getLocationContext());
  2562. assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  2563. if (Optional<Loc> LV = X.getAs<Loc>())
  2564. state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
  2565. }
  2566. Bldr.generateNode(A, Pred, state);
  2567. }
  2568. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  2569. ExplodedNodeSet &Dst) {
  2570. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2571. Bldr.generateNode(A, Pred, Pred->getState());
  2572. }
  2573. //===----------------------------------------------------------------------===//
  2574. // Visualization.
  2575. //===----------------------------------------------------------------------===//
  2576. #ifndef NDEBUG
  2577. static ExprEngine* GraphPrintCheckerState;
  2578. static SourceManager* GraphPrintSourceManager;
  2579. namespace llvm {
  2580. template<>
  2581. struct DOTGraphTraits<ExplodedNode*> : public DefaultDOTGraphTraits {
  2582. DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  2583. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  2584. // work.
  2585. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  2586. return {};
  2587. }
  2588. // De-duplicate some source location pretty-printing.
  2589. static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
  2590. if (SLoc.isFileID()) {
  2591. Out << "\\lline="
  2592. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2593. << " col="
  2594. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  2595. << "\\l";
  2596. }
  2597. }
  2598. static std::string getNodeLabel(const ExplodedNode *N, void*){
  2599. std::string sbuf;
  2600. llvm::raw_string_ostream Out(sbuf);
  2601. // Program Location.
  2602. ProgramPoint Loc = N->getLocation();
  2603. switch (Loc.getKind()) {
  2604. case ProgramPoint::BlockEntranceKind:
  2605. Out << "Block Entrance: B"
  2606. << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
  2607. break;
  2608. case ProgramPoint::BlockExitKind:
  2609. assert(false);
  2610. break;
  2611. case ProgramPoint::CallEnterKind:
  2612. Out << "CallEnter";
  2613. break;
  2614. case ProgramPoint::CallExitBeginKind:
  2615. Out << "CallExitBegin";
  2616. break;
  2617. case ProgramPoint::CallExitEndKind:
  2618. Out << "CallExitEnd";
  2619. break;
  2620. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  2621. Out << "PostStmtPurgeDeadSymbols";
  2622. break;
  2623. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  2624. Out << "PreStmtPurgeDeadSymbols";
  2625. break;
  2626. case ProgramPoint::EpsilonKind:
  2627. Out << "Epsilon Point";
  2628. break;
  2629. case ProgramPoint::LoopExitKind: {
  2630. LoopExit LE = Loc.castAs<LoopExit>();
  2631. Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
  2632. break;
  2633. }
  2634. case ProgramPoint::PreImplicitCallKind: {
  2635. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  2636. Out << "PreCall: ";
  2637. // FIXME: Get proper printing options.
  2638. PC.getDecl()->print(Out, LangOptions());
  2639. printLocation(Out, PC.getLocation());
  2640. break;
  2641. }
  2642. case ProgramPoint::PostImplicitCallKind: {
  2643. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  2644. Out << "PostCall: ";
  2645. // FIXME: Get proper printing options.
  2646. PC.getDecl()->print(Out, LangOptions());
  2647. printLocation(Out, PC.getLocation());
  2648. break;
  2649. }
  2650. case ProgramPoint::PostInitializerKind: {
  2651. Out << "PostInitializer: ";
  2652. const CXXCtorInitializer *Init =
  2653. Loc.castAs<PostInitializer>().getInitializer();
  2654. if (const FieldDecl *FD = Init->getAnyMember())
  2655. Out << *FD;
  2656. else {
  2657. QualType Ty = Init->getTypeSourceInfo()->getType();
  2658. Ty = Ty.getLocalUnqualifiedType();
  2659. LangOptions LO; // FIXME.
  2660. Ty.print(Out, LO);
  2661. }
  2662. break;
  2663. }
  2664. case ProgramPoint::BlockEdgeKind: {
  2665. const BlockEdge &E = Loc.castAs<BlockEdge>();
  2666. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  2667. << E.getDst()->getBlockID() << ')';
  2668. if (const Stmt *T = E.getSrc()->getTerminator()) {
  2669. SourceLocation SLoc = T->getLocStart();
  2670. Out << "\\|Terminator: ";
  2671. LangOptions LO; // FIXME.
  2672. E.getSrc()->printTerminator(Out, LO);
  2673. if (SLoc.isFileID()) {
  2674. Out << "\\lline="
  2675. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2676. << " col="
  2677. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  2678. }
  2679. if (isa<SwitchStmt>(T)) {
  2680. const Stmt *Label = E.getDst()->getLabel();
  2681. if (Label) {
  2682. if (const auto *C = dyn_cast<CaseStmt>(Label)) {
  2683. Out << "\\lcase ";
  2684. LangOptions LO; // FIXME.
  2685. if (C->getLHS())
  2686. C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
  2687. if (const Stmt *RHS = C->getRHS()) {
  2688. Out << " .. ";
  2689. RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
  2690. }
  2691. Out << ":";
  2692. }
  2693. else {
  2694. assert(isa<DefaultStmt>(Label));
  2695. Out << "\\ldefault:";
  2696. }
  2697. }
  2698. else
  2699. Out << "\\l(implicit) default:";
  2700. }
  2701. else if (isa<IndirectGotoStmt>(T)) {
  2702. // FIXME
  2703. }
  2704. else {
  2705. Out << "\\lCondition: ";
  2706. if (*E.getSrc()->succ_begin() == E.getDst())
  2707. Out << "true";
  2708. else
  2709. Out << "false";
  2710. }
  2711. Out << "\\l";
  2712. }
  2713. break;
  2714. }
  2715. default: {
  2716. const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
  2717. assert(S != nullptr && "Expecting non-null Stmt");
  2718. Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
  2719. LangOptions LO; // FIXME.
  2720. S->printPretty(Out, nullptr, PrintingPolicy(LO));
  2721. printLocation(Out, S->getLocStart());
  2722. if (Loc.getAs<PreStmt>())
  2723. Out << "\\lPreStmt\\l;";
  2724. else if (Loc.getAs<PostLoad>())
  2725. Out << "\\lPostLoad\\l;";
  2726. else if (Loc.getAs<PostStore>())
  2727. Out << "\\lPostStore\\l";
  2728. else if (Loc.getAs<PostLValue>())
  2729. Out << "\\lPostLValue\\l";
  2730. else if (Loc.getAs<PostAllocatorCall>())
  2731. Out << "\\lPostAllocatorCall\\l";
  2732. break;
  2733. }
  2734. }
  2735. ProgramStateRef state = N->getState();
  2736. Out << "\\|StateID: " << (const void*) state.get()
  2737. << " NodeID: " << (const void*) N << "\\|";
  2738. state->printDOT(Out, N->getLocationContext());
  2739. Out << "\\l";
  2740. if (const ProgramPointTag *tag = Loc.getTag()) {
  2741. Out << "\\|Tag: " << tag->getTagDescription();
  2742. Out << "\\l";
  2743. }
  2744. return Out.str();
  2745. }
  2746. };
  2747. } // namespace llvm
  2748. #endif
  2749. void ExprEngine::ViewGraph(bool trim) {
  2750. #ifndef NDEBUG
  2751. if (trim) {
  2752. std::vector<const ExplodedNode *> Src;
  2753. // Flush any outstanding reports to make sure we cover all the nodes.
  2754. // This does not cause them to get displayed.
  2755. for (const auto I : BR)
  2756. const_cast<BugType *>(I)->FlushReports(BR);
  2757. // Iterate through the reports and get their nodes.
  2758. for (BugReporter::EQClasses_iterator
  2759. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2760. const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
  2761. if (N) Src.push_back(N);
  2762. }
  2763. ViewGraph(Src);
  2764. }
  2765. else {
  2766. GraphPrintCheckerState = this;
  2767. GraphPrintSourceManager = &getContext().getSourceManager();
  2768. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2769. GraphPrintCheckerState = nullptr;
  2770. GraphPrintSourceManager = nullptr;
  2771. }
  2772. #endif
  2773. }
  2774. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2775. #ifndef NDEBUG
  2776. GraphPrintCheckerState = this;
  2777. GraphPrintSourceManager = &getContext().getSourceManager();
  2778. std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2779. if (!TrimmedG.get())
  2780. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2781. else
  2782. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2783. GraphPrintCheckerState = nullptr;
  2784. GraphPrintSourceManager = nullptr;
  2785. #endif
  2786. }