ExprEngine.cpp 114 KB

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