ExprEngine.cpp 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112
  1. //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines a meta-engine for path-sensitive dataflow analysis that
  10. // is built on GREngine, but provides the boilerplate to execute transfer
  11. // functions and build the ExplodedGraph at the expression level.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  15. #include "PrettyStackTraceLocationContext.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclBase.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/ParentMap.h"
  25. #include "clang/AST/PrettyPrinter.h"
  26. #include "clang/AST/Stmt.h"
  27. #include "clang/AST/StmtCXX.h"
  28. #include "clang/AST/StmtObjC.h"
  29. #include "clang/AST/Type.h"
  30. #include "clang/Analysis/AnalysisDeclContext.h"
  31. #include "clang/Analysis/CFG.h"
  32. #include "clang/Analysis/ConstructionContext.h"
  33. #include "clang/Analysis/ProgramPoint.h"
  34. #include "clang/Basic/IdentifierTable.h"
  35. #include "clang/Basic/LLVM.h"
  36. #include "clang/Basic/LangOptions.h"
  37. #include "clang/Basic/PrettyStackTrace.h"
  38. #include "clang/Basic/SourceLocation.h"
  39. #include "clang/Basic/SourceManager.h"
  40. #include "clang/Basic/Specifiers.h"
  41. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  42. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  43. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  44. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  45. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  47. #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
  48. #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
  49. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  50. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
  51. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
  52. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  53. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  54. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  55. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  56. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  57. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  58. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  59. #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
  60. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  61. #include "llvm/ADT/APSInt.h"
  62. #include "llvm/ADT/DenseMap.h"
  63. #include "llvm/ADT/ImmutableMap.h"
  64. #include "llvm/ADT/ImmutableSet.h"
  65. #include "llvm/ADT/Optional.h"
  66. #include "llvm/ADT/SmallVector.h"
  67. #include "llvm/ADT/Statistic.h"
  68. #include "llvm/Support/Casting.h"
  69. #include "llvm/Support/Compiler.h"
  70. #include "llvm/Support/DOTGraphTraits.h"
  71. #include "llvm/Support/ErrorHandling.h"
  72. #include "llvm/Support/GraphWriter.h"
  73. #include "llvm/Support/SaveAndRestore.h"
  74. #include "llvm/Support/raw_ostream.h"
  75. #include <cassert>
  76. #include <cstdint>
  77. #include <memory>
  78. #include <string>
  79. #include <tuple>
  80. #include <utility>
  81. #include <vector>
  82. using namespace clang;
  83. using namespace ento;
  84. #define DEBUG_TYPE "ExprEngine"
  85. STATISTIC(NumRemoveDeadBindings,
  86. "The # of times RemoveDeadBindings is called");
  87. STATISTIC(NumMaxBlockCountReached,
  88. "The # of aborted paths due to reaching the maximum block count in "
  89. "a top level function");
  90. STATISTIC(NumMaxBlockCountReachedInInlined,
  91. "The # of aborted paths due to reaching the maximum block count in "
  92. "an inlined function");
  93. STATISTIC(NumTimesRetriedWithoutInlining,
  94. "The # of times we re-evaluated a call without inlining");
  95. //===----------------------------------------------------------------------===//
  96. // Internal program state traits.
  97. //===----------------------------------------------------------------------===//
  98. namespace {
  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. ASTContext &getASTContext() const {
  128. return getLocationContext()->getDecl()->getASTContext();
  129. }
  130. void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
  131. OS << "(LC" << getLocationContext()->getID() << ',';
  132. if (const Stmt *S = getItem().getStmtOrNull())
  133. OS << 'S' << S->getID(getASTContext());
  134. else
  135. OS << 'I' << getItem().getCXXCtorInitializer()->getID(getASTContext());
  136. OS << ',' << getItem().getKindAsString();
  137. if (getItem().getKind() == ConstructionContextItem::ArgumentKind)
  138. OS << " #" << getItem().getIndex();
  139. OS << ") ";
  140. if (const Stmt *S = getItem().getStmtOrNull()) {
  141. S->printPretty(OS, Helper, PP);
  142. } else {
  143. const CXXCtorInitializer *I = getItem().getCXXCtorInitializer();
  144. OS << I->getAnyMember()->getNameAsString();
  145. }
  146. }
  147. void Profile(llvm::FoldingSetNodeID &ID) const {
  148. ID.Add(Impl.first);
  149. ID.AddPointer(Impl.second);
  150. }
  151. bool operator==(const ConstructedObjectKey &RHS) const {
  152. return Impl == RHS.Impl;
  153. }
  154. bool operator<(const ConstructedObjectKey &RHS) const {
  155. return Impl < RHS.Impl;
  156. }
  157. };
  158. } // namespace
  159. typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
  160. ObjectsUnderConstructionMap;
  161. REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
  162. ObjectsUnderConstructionMap)
  163. //===----------------------------------------------------------------------===//
  164. // Engine construction and deletion.
  165. //===----------------------------------------------------------------------===//
  166. static const char* TagProviderName = "ExprEngine";
  167. ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
  168. AnalysisManager &mgr,
  169. SetOfConstDecls *VisitedCalleesIn,
  170. FunctionSummariesTy *FS,
  171. InliningModes HowToInlineIn)
  172. : CTU(CTU), AMgr(mgr),
  173. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  174. Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
  175. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  176. mgr.getConstraintManagerCreator(), G.getAllocator(),
  177. this),
  178. SymMgr(StateMgr.getSymbolManager()),
  179. MRMgr(StateMgr.getRegionManager()),
  180. svalBuilder(StateMgr.getSValBuilder()),
  181. ObjCNoRet(mgr.getASTContext()),
  182. BR(mgr, *this),
  183. VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
  184. unsigned TrimInterval = mgr.options.GraphTrimInterval;
  185. if (TrimInterval != 0) {
  186. // Enable eager node reclamation when constructing the ExplodedGraph.
  187. G.enableNodeReclamation(TrimInterval);
  188. }
  189. }
  190. ExprEngine::~ExprEngine() {
  191. BR.FlushReports();
  192. }
  193. //===----------------------------------------------------------------------===//
  194. // Utility methods.
  195. //===----------------------------------------------------------------------===//
  196. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  197. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  198. const Decl *D = InitLoc->getDecl();
  199. // Preconditions.
  200. // FIXME: It would be nice if we had a more general mechanism to add
  201. // such preconditions. Some day.
  202. do {
  203. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  204. // Precondition: the first argument of 'main' is an integer guaranteed
  205. // to be > 0.
  206. const IdentifierInfo *II = FD->getIdentifier();
  207. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  208. break;
  209. const ParmVarDecl *PD = FD->getParamDecl(0);
  210. QualType T = PD->getType();
  211. const auto *BT = dyn_cast<BuiltinType>(T);
  212. if (!BT || !BT->isInteger())
  213. break;
  214. const MemRegion *R = state->getRegion(PD, InitLoc);
  215. if (!R)
  216. break;
  217. SVal V = state->getSVal(loc::MemRegionVal(R));
  218. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  219. svalBuilder.makeZeroVal(T),
  220. svalBuilder.getConditionType());
  221. Optional<DefinedOrUnknownSVal> Constraint =
  222. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  223. if (!Constraint)
  224. break;
  225. if (ProgramStateRef newState = state->assume(*Constraint, true))
  226. state = newState;
  227. }
  228. break;
  229. }
  230. while (false);
  231. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  232. // Precondition: 'self' is always non-null upon entry to an Objective-C
  233. // method.
  234. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  235. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  236. SVal V = state->getSVal(loc::MemRegionVal(R));
  237. if (Optional<Loc> LV = V.getAs<Loc>()) {
  238. // Assume that the pointer value in 'self' is non-null.
  239. state = state->assume(*LV, true);
  240. assert(state && "'self' cannot be null");
  241. }
  242. }
  243. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  244. if (!MD->isStatic()) {
  245. // Precondition: 'this' is always non-null upon entry to the
  246. // top-level function. This is our starting assumption for
  247. // analyzing an "open" program.
  248. const StackFrameContext *SFC = InitLoc->getStackFrame();
  249. if (SFC->getParent() == nullptr) {
  250. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  251. SVal V = state->getSVal(L);
  252. if (Optional<Loc> LV = V.getAs<Loc>()) {
  253. state = state->assume(*LV, true);
  254. assert(state && "'this' cannot be null");
  255. }
  256. }
  257. }
  258. }
  259. return state;
  260. }
  261. ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
  262. ProgramStateRef State, const LocationContext *LC,
  263. const Expr *InitWithAdjustments, const Expr *Result,
  264. const SubRegion **OutRegionWithAdjustments) {
  265. // FIXME: This function is a hack that works around the quirky AST
  266. // we're often having with respect to C++ temporaries. If only we modelled
  267. // the actual execution order of statements properly in the CFG,
  268. // all the hassle with adjustments would not be necessary,
  269. // and perhaps the whole function would be removed.
  270. SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
  271. if (!Result) {
  272. // If we don't have an explicit result expression, we're in "if needed"
  273. // mode. Only create a region if the current value is a NonLoc.
  274. if (!InitValWithAdjustments.getAs<NonLoc>()) {
  275. if (OutRegionWithAdjustments)
  276. *OutRegionWithAdjustments = nullptr;
  277. return State;
  278. }
  279. Result = InitWithAdjustments;
  280. } else {
  281. // We need to create a region no matter what. For sanity, make sure we don't
  282. // try to stuff a Loc into a non-pointer temporary region.
  283. assert(!InitValWithAdjustments.getAs<Loc>() ||
  284. Loc::isLocType(Result->getType()) ||
  285. Result->getType()->isMemberPointerType());
  286. }
  287. ProgramStateManager &StateMgr = State->getStateManager();
  288. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  289. StoreManager &StoreMgr = StateMgr.getStoreManager();
  290. // MaterializeTemporaryExpr may appear out of place, after a few field and
  291. // base-class accesses have been made to the object, even though semantically
  292. // it is the whole object that gets materialized and lifetime-extended.
  293. //
  294. // For example:
  295. //
  296. // `-MaterializeTemporaryExpr
  297. // `-MemberExpr
  298. // `-CXXTemporaryObjectExpr
  299. //
  300. // instead of the more natural
  301. //
  302. // `-MemberExpr
  303. // `-MaterializeTemporaryExpr
  304. // `-CXXTemporaryObjectExpr
  305. //
  306. // Use the usual methods for obtaining the expression of the base object,
  307. // and record the adjustments that we need to make to obtain the sub-object
  308. // that the whole expression 'Ex' refers to. This trick is usual,
  309. // in the sense that CodeGen takes a similar route.
  310. SmallVector<const Expr *, 2> CommaLHSs;
  311. SmallVector<SubobjectAdjustment, 2> Adjustments;
  312. const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
  313. CommaLHSs, Adjustments);
  314. // Take the region for Init, i.e. for the whole object. If we do not remember
  315. // the region in which the object originally was constructed, come up with
  316. // a new temporary region out of thin air and copy the contents of the object
  317. // (which are currently present in the Environment, because Init is an rvalue)
  318. // into that region. This is not correct, but it is better than nothing.
  319. const TypedValueRegion *TR = nullptr;
  320. if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
  321. if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
  322. State = finishObjectConstruction(State, MT, LC);
  323. State = State->BindExpr(Result, LC, *V);
  324. return State;
  325. } else {
  326. StorageDuration SD = MT->getStorageDuration();
  327. // If this object is bound to a reference with static storage duration, we
  328. // put it in a different region to prevent "address leakage" warnings.
  329. if (SD == SD_Static || SD == SD_Thread) {
  330. TR = MRMgr.getCXXStaticTempObjectRegion(Init);
  331. } else {
  332. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  333. }
  334. }
  335. } else {
  336. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  337. }
  338. SVal Reg = loc::MemRegionVal(TR);
  339. SVal BaseReg = Reg;
  340. // Make the necessary adjustments to obtain the sub-object.
  341. for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
  342. const SubobjectAdjustment &Adj = *I;
  343. switch (Adj.Kind) {
  344. case SubobjectAdjustment::DerivedToBaseAdjustment:
  345. Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
  346. break;
  347. case SubobjectAdjustment::FieldAdjustment:
  348. Reg = StoreMgr.getLValueField(Adj.Field, Reg);
  349. break;
  350. case SubobjectAdjustment::MemberPointerAdjustment:
  351. // FIXME: Unimplemented.
  352. State = State->invalidateRegions(Reg, InitWithAdjustments,
  353. currBldrCtx->blockCount(), LC, true,
  354. nullptr, nullptr, nullptr);
  355. return State;
  356. }
  357. }
  358. // What remains is to copy the value of the object to the new region.
  359. // FIXME: In other words, what we should always do is copy value of the
  360. // Init expression (which corresponds to the bigger object) to the whole
  361. // temporary region TR. However, this value is often no longer present
  362. // in the Environment. If it has disappeared, we instead invalidate TR.
  363. // Still, what we can do is assign the value of expression Ex (which
  364. // corresponds to the sub-object) to the TR's sub-region Reg. At least,
  365. // values inside Reg would be correct.
  366. SVal InitVal = State->getSVal(Init, LC);
  367. if (InitVal.isUnknown()) {
  368. InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
  369. currBldrCtx->blockCount());
  370. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  371. // Then we'd need to take the value that certainly exists and bind it
  372. // over.
  373. if (InitValWithAdjustments.isUnknown()) {
  374. // Try to recover some path sensitivity in case we couldn't
  375. // compute the value.
  376. InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
  377. Result, LC, InitWithAdjustments->getType(),
  378. currBldrCtx->blockCount());
  379. }
  380. State =
  381. State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
  382. } else {
  383. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  384. }
  385. // The result expression would now point to the correct sub-region of the
  386. // newly created temporary region. Do this last in order to getSVal of Init
  387. // correctly in case (Result == Init).
  388. if (Result->isGLValue()) {
  389. State = State->BindExpr(Result, LC, Reg);
  390. } else {
  391. State = State->BindExpr(Result, LC, InitValWithAdjustments);
  392. }
  393. // Notify checkers once for two bindLoc()s.
  394. State = processRegionChange(State, TR, LC);
  395. if (OutRegionWithAdjustments)
  396. *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
  397. return State;
  398. }
  399. ProgramStateRef
  400. ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
  401. const ConstructionContextItem &Item,
  402. const LocationContext *LC, SVal V) {
  403. ConstructedObjectKey Key(Item, LC->getStackFrame());
  404. // FIXME: Currently the state might already contain the marker due to
  405. // incorrect handling of temporaries bound to default parameters.
  406. assert(!State->get<ObjectsUnderConstruction>(Key) ||
  407. Key.getItem().getKind() ==
  408. ConstructionContextItem::TemporaryDestructorKind);
  409. return State->set<ObjectsUnderConstruction>(Key, V);
  410. }
  411. Optional<SVal>
  412. ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
  413. const ConstructionContextItem &Item,
  414. const LocationContext *LC) {
  415. ConstructedObjectKey Key(Item, LC->getStackFrame());
  416. return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
  417. }
  418. ProgramStateRef
  419. ExprEngine::finishObjectConstruction(ProgramStateRef State,
  420. const ConstructionContextItem &Item,
  421. const LocationContext *LC) {
  422. ConstructedObjectKey Key(Item, LC->getStackFrame());
  423. assert(State->contains<ObjectsUnderConstruction>(Key));
  424. return State->remove<ObjectsUnderConstruction>(Key);
  425. }
  426. ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
  427. const CXXBindTemporaryExpr *BTE,
  428. const LocationContext *LC) {
  429. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  430. // FIXME: Currently the state might already contain the marker due to
  431. // incorrect handling of temporaries bound to default parameters.
  432. return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
  433. }
  434. ProgramStateRef
  435. ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
  436. const CXXBindTemporaryExpr *BTE,
  437. const LocationContext *LC) {
  438. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  439. assert(State->contains<ObjectsUnderConstruction>(Key));
  440. return State->remove<ObjectsUnderConstruction>(Key);
  441. }
  442. bool ExprEngine::isDestructorElided(ProgramStateRef State,
  443. const CXXBindTemporaryExpr *BTE,
  444. const LocationContext *LC) {
  445. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  446. return State->contains<ObjectsUnderConstruction>(Key);
  447. }
  448. bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
  449. const LocationContext *FromLC,
  450. const LocationContext *ToLC) {
  451. const LocationContext *LC = FromLC;
  452. while (LC != ToLC) {
  453. assert(LC && "ToLC must be a parent of FromLC!");
  454. for (auto I : State->get<ObjectsUnderConstruction>())
  455. if (I.first.getLocationContext() == LC)
  456. return false;
  457. LC = LC->getParent();
  458. }
  459. return true;
  460. }
  461. //===----------------------------------------------------------------------===//
  462. // Top-level transfer function logic (Dispatcher).
  463. //===----------------------------------------------------------------------===//
  464. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  465. /// logic for handling assumptions on symbolic values.
  466. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  467. SVal cond, bool assumption) {
  468. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  469. }
  470. ProgramStateRef
  471. ExprEngine::processRegionChanges(ProgramStateRef state,
  472. const InvalidatedSymbols *invalidated,
  473. ArrayRef<const MemRegion *> Explicits,
  474. ArrayRef<const MemRegion *> Regions,
  475. const LocationContext *LCtx,
  476. const CallEvent *Call) {
  477. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  478. Explicits, Regions,
  479. LCtx, Call);
  480. }
  481. static void printObjectsUnderConstructionForContext(raw_ostream &Out,
  482. ProgramStateRef State,
  483. const char *NL,
  484. const LocationContext *LC) {
  485. PrintingPolicy PP =
  486. LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
  487. for (auto I : State->get<ObjectsUnderConstruction>()) {
  488. ConstructedObjectKey Key = I.first;
  489. SVal Value = I.second;
  490. if (Key.getLocationContext() != LC)
  491. continue;
  492. Key.print(Out, nullptr, PP);
  493. Out << " : " << Value << NL;
  494. }
  495. }
  496. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  497. const char *NL, const char *Sep,
  498. const LocationContext *LCtx) {
  499. if (LCtx) {
  500. if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
  501. Out << Sep << "Objects under construction:" << NL;
  502. LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
  503. printObjectsUnderConstructionForContext(Out, State, NL, LC);
  504. });
  505. }
  506. }
  507. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  508. }
  509. void ExprEngine::processEndWorklist() {
  510. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  511. }
  512. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  513. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  514. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  515. currStmtIdx = StmtIdx;
  516. currBldrCtx = Ctx;
  517. switch (E.getKind()) {
  518. case CFGElement::Statement:
  519. case CFGElement::Constructor:
  520. case CFGElement::CXXRecordTypedCall:
  521. ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
  522. return;
  523. case CFGElement::Initializer:
  524. ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
  525. return;
  526. case CFGElement::NewAllocator:
  527. ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
  528. Pred);
  529. return;
  530. case CFGElement::AutomaticObjectDtor:
  531. case CFGElement::DeleteDtor:
  532. case CFGElement::BaseDtor:
  533. case CFGElement::MemberDtor:
  534. case CFGElement::TemporaryDtor:
  535. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  536. return;
  537. case CFGElement::LoopExit:
  538. ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
  539. return;
  540. case CFGElement::LifetimeEnds:
  541. case CFGElement::ScopeBegin:
  542. case CFGElement::ScopeEnd:
  543. return;
  544. }
  545. }
  546. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  547. const Stmt *S,
  548. const ExplodedNode *Pred,
  549. const LocationContext *LC) {
  550. // Are we never purging state values?
  551. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  552. return false;
  553. // Is this the beginning of a basic block?
  554. if (Pred->getLocation().getAs<BlockEntrance>())
  555. return true;
  556. // Is this on a non-expression?
  557. if (!isa<Expr>(S))
  558. return true;
  559. // Run before processing a call.
  560. if (CallEvent::isCallStmt(S))
  561. return true;
  562. // Is this an expression that is consumed by another expression? If so,
  563. // postpone cleaning out the state.
  564. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  565. return !PM.isConsumedExpr(cast<Expr>(S));
  566. }
  567. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  568. const Stmt *ReferenceStmt,
  569. const LocationContext *LC,
  570. const Stmt *DiagnosticStmt,
  571. ProgramPoint::Kind K) {
  572. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  573. ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
  574. && "PostStmt is not generally supported by the SymbolReaper yet");
  575. assert(LC && "Must pass the current (or expiring) LocationContext");
  576. if (!DiagnosticStmt) {
  577. DiagnosticStmt = ReferenceStmt;
  578. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  579. }
  580. NumRemoveDeadBindings++;
  581. ProgramStateRef CleanedState = Pred->getState();
  582. // LC is the location context being destroyed, but SymbolReaper wants a
  583. // location context that is still live. (If this is the top-level stack
  584. // frame, this will be null.)
  585. if (!ReferenceStmt) {
  586. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  587. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  588. LC = LC->getParent();
  589. }
  590. const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
  591. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  592. for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
  593. if (SymbolRef Sym = I.second.getAsSymbol())
  594. SymReaper.markLive(Sym);
  595. if (const MemRegion *MR = I.second.getAsRegion())
  596. SymReaper.markLive(MR);
  597. }
  598. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  599. // Create a state in which dead bindings are removed from the environment
  600. // and the store. TODO: The function should just return new env and store,
  601. // not a new state.
  602. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  603. // Process any special transfer function for dead symbols.
  604. // A tag to track convenience transitions, which can be removed at cleanup.
  605. static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
  606. // Call checkers with the non-cleaned state so that they could query the
  607. // values of the soon to be dead symbols.
  608. ExplodedNodeSet CheckedSet;
  609. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  610. DiagnosticStmt, *this, K);
  611. // For each node in CheckedSet, generate CleanedNodes that have the
  612. // environment, the store, and the constraints cleaned up but have the
  613. // user-supplied states as the predecessors.
  614. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  615. for (const auto I : CheckedSet) {
  616. ProgramStateRef CheckerState = I->getState();
  617. // The constraint manager has not been cleaned up yet, so clean up now.
  618. CheckerState =
  619. getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
  620. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  621. "Checkers are not allowed to modify the Environment as a part of "
  622. "checkDeadSymbols processing.");
  623. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  624. "Checkers are not allowed to modify the Store as a part of "
  625. "checkDeadSymbols processing.");
  626. // Create a state based on CleanedState with CheckerState GDM and
  627. // generate a transition to that state.
  628. ProgramStateRef CleanedCheckerSt =
  629. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  630. Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
  631. }
  632. }
  633. void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
  634. // Reclaim any unnecessary nodes in the ExplodedGraph.
  635. G.reclaimRecentlyAllocatedNodes();
  636. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  637. currStmt->getBeginLoc(),
  638. "Error evaluating statement");
  639. // Remove dead bindings and symbols.
  640. ExplodedNodeSet CleanedStates;
  641. if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
  642. Pred->getLocationContext())) {
  643. removeDead(Pred, CleanedStates, currStmt,
  644. Pred->getLocationContext());
  645. } else
  646. CleanedStates.Add(Pred);
  647. // Visit the statement.
  648. ExplodedNodeSet Dst;
  649. for (const auto I : CleanedStates) {
  650. ExplodedNodeSet DstI;
  651. // Visit the statement.
  652. Visit(currStmt, I, DstI);
  653. Dst.insert(DstI);
  654. }
  655. // Enqueue the new nodes onto the work list.
  656. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  657. }
  658. void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
  659. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  660. S->getBeginLoc(),
  661. "Error evaluating end of the loop");
  662. ExplodedNodeSet Dst;
  663. Dst.Add(Pred);
  664. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  665. ProgramStateRef NewState = Pred->getState();
  666. if(AMgr.options.ShouldUnrollLoops)
  667. NewState = processLoopEnd(S, NewState);
  668. LoopExit PP(S, Pred->getLocationContext());
  669. Bldr.generateNode(PP, NewState, Pred);
  670. // Enqueue the new nodes onto the work list.
  671. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  672. }
  673. void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
  674. ExplodedNode *Pred) {
  675. const CXXCtorInitializer *BMI = CFGInit.getInitializer();
  676. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  677. const LocationContext *LC = Pred->getLocationContext();
  678. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  679. BMI->getSourceLocation(),
  680. "Error evaluating initializer");
  681. // We don't clean up dead bindings here.
  682. const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
  683. const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
  684. ProgramStateRef State = Pred->getState();
  685. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  686. ExplodedNodeSet Tmp;
  687. SVal FieldLoc;
  688. // Evaluate the initializer, if necessary
  689. if (BMI->isAnyMemberInitializer()) {
  690. // Constructors build the object directly in the field,
  691. // but non-objects must be copied in from the initializer.
  692. if (getObjectUnderConstruction(State, BMI, LC)) {
  693. // The field was directly constructed, so there is no need to bind.
  694. // But we still need to stop tracking the object under construction.
  695. State = finishObjectConstruction(State, BMI, LC);
  696. NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  697. PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
  698. Bldr.generateNode(PS, State, Pred);
  699. } else {
  700. const ValueDecl *Field;
  701. if (BMI->isIndirectMemberInitializer()) {
  702. Field = BMI->getIndirectMember();
  703. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  704. } else {
  705. Field = BMI->getMember();
  706. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  707. }
  708. SVal InitVal;
  709. if (Init->getType()->isArrayType()) {
  710. // Handle arrays of trivial type. We can represent this with a
  711. // primitive load/copy from the base array region.
  712. const ArraySubscriptExpr *ASE;
  713. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  714. Init = ASE->getBase()->IgnoreImplicit();
  715. SVal LValue = State->getSVal(Init, stackFrame);
  716. if (!Field->getType()->isReferenceType())
  717. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  718. InitVal = State->getSVal(*LValueLoc);
  719. // If we fail to get the value for some reason, use a symbolic value.
  720. if (InitVal.isUnknownOrUndef()) {
  721. SValBuilder &SVB = getSValBuilder();
  722. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  723. Field->getType(),
  724. currBldrCtx->blockCount());
  725. }
  726. } else {
  727. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  728. }
  729. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  730. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  731. }
  732. } else {
  733. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  734. Tmp.insert(Pred);
  735. // We already did all the work when visiting the CXXConstructExpr.
  736. }
  737. // Construct PostInitializer nodes whether the state changed or not,
  738. // so that the diagnostics don't get confused.
  739. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  740. ExplodedNodeSet Dst;
  741. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  742. for (const auto I : Tmp) {
  743. ProgramStateRef State = I->getState();
  744. Bldr.generateNode(PP, State, I);
  745. }
  746. // Enqueue the new nodes onto the work list.
  747. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  748. }
  749. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  750. ExplodedNode *Pred) {
  751. ExplodedNodeSet Dst;
  752. switch (D.getKind()) {
  753. case CFGElement::AutomaticObjectDtor:
  754. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  755. break;
  756. case CFGElement::BaseDtor:
  757. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  758. break;
  759. case CFGElement::MemberDtor:
  760. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  761. break;
  762. case CFGElement::TemporaryDtor:
  763. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  764. break;
  765. case CFGElement::DeleteDtor:
  766. ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
  767. break;
  768. default:
  769. llvm_unreachable("Unexpected dtor kind.");
  770. }
  771. // Enqueue the new nodes onto the work list.
  772. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  773. }
  774. void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
  775. ExplodedNode *Pred) {
  776. ExplodedNodeSet Dst;
  777. AnalysisManager &AMgr = getAnalysisManager();
  778. AnalyzerOptions &Opts = AMgr.options;
  779. // TODO: We're not evaluating allocators for all cases just yet as
  780. // we're not handling the return value correctly, which causes false
  781. // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
  782. if (Opts.MayInlineCXXAllocator)
  783. VisitCXXNewAllocatorCall(NE, Pred, Dst);
  784. else {
  785. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  786. const LocationContext *LCtx = Pred->getLocationContext();
  787. PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx);
  788. Bldr.generateNode(PP, Pred->getState(), Pred);
  789. }
  790. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  791. }
  792. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  793. ExplodedNode *Pred,
  794. ExplodedNodeSet &Dst) {
  795. const VarDecl *varDecl = Dtor.getVarDecl();
  796. QualType varType = varDecl->getType();
  797. ProgramStateRef state = Pred->getState();
  798. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  799. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  800. if (varType->isReferenceType()) {
  801. const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
  802. if (!ValueRegion) {
  803. // FIXME: This should not happen. The language guarantees a presence
  804. // of a valid initializer here, so the reference shall not be undefined.
  805. // It seems that we're calling destructors over variables that
  806. // were not initialized yet.
  807. return;
  808. }
  809. Region = ValueRegion->getBaseRegion();
  810. varType = cast<TypedValueRegion>(Region)->getValueType();
  811. }
  812. // FIXME: We need to run the same destructor on every element of the array.
  813. // This workaround will just run the first destructor (which will still
  814. // invalidate the entire array).
  815. EvalCallOptions CallOpts;
  816. Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
  817. CallOpts.IsArrayCtorOrDtor).getAsRegion();
  818. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  819. Pred, Dst, CallOpts);
  820. }
  821. void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
  822. ExplodedNode *Pred,
  823. ExplodedNodeSet &Dst) {
  824. ProgramStateRef State = Pred->getState();
  825. const LocationContext *LCtx = Pred->getLocationContext();
  826. const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
  827. const Stmt *Arg = DE->getArgument();
  828. QualType DTy = DE->getDestroyedType();
  829. SVal ArgVal = State->getSVal(Arg, LCtx);
  830. // If the argument to delete is known to be a null value,
  831. // don't run destructor.
  832. if (State->isNull(ArgVal).isConstrainedTrue()) {
  833. QualType BTy = getContext().getBaseElementType(DTy);
  834. const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
  835. const CXXDestructorDecl *Dtor = RD->getDestructor();
  836. PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx);
  837. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  838. Bldr.generateNode(PP, Pred->getState(), Pred);
  839. return;
  840. }
  841. EvalCallOptions CallOpts;
  842. const MemRegion *ArgR = ArgVal.getAsRegion();
  843. if (DE->isArrayForm()) {
  844. // FIXME: We need to run the same destructor on every element of the array.
  845. // This workaround will just run the first destructor (which will still
  846. // invalidate the entire array).
  847. CallOpts.IsArrayCtorOrDtor = true;
  848. // Yes, it may even be a multi-dimensional array.
  849. while (const auto *AT = getContext().getAsArrayType(DTy))
  850. DTy = AT->getElementType();
  851. if (ArgR)
  852. ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
  853. }
  854. VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
  855. }
  856. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  857. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  858. const LocationContext *LCtx = Pred->getLocationContext();
  859. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  860. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  861. LCtx->getStackFrame());
  862. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  863. // Create the base object region.
  864. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  865. QualType BaseTy = Base->getType();
  866. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  867. Base->isVirtual());
  868. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  869. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
  870. }
  871. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  872. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  873. const FieldDecl *Member = D.getFieldDecl();
  874. QualType T = Member->getType();
  875. ProgramStateRef State = Pred->getState();
  876. const LocationContext *LCtx = Pred->getLocationContext();
  877. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  878. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  879. LCtx->getStackFrame());
  880. SVal FieldVal =
  881. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  882. // FIXME: We need to run the same destructor on every element of the array.
  883. // This workaround will just run the first destructor (which will still
  884. // invalidate the entire array).
  885. EvalCallOptions CallOpts;
  886. FieldVal = makeZeroElementRegion(State, FieldVal, T,
  887. CallOpts.IsArrayCtorOrDtor);
  888. VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  889. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
  890. }
  891. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  892. ExplodedNode *Pred,
  893. ExplodedNodeSet &Dst) {
  894. const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
  895. ProgramStateRef State = Pred->getState();
  896. const LocationContext *LC = Pred->getLocationContext();
  897. const MemRegion *MR = nullptr;
  898. if (Optional<SVal> V =
  899. getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
  900. Pred->getLocationContext())) {
  901. // FIXME: Currently we insert temporary destructors for default parameters,
  902. // but we don't insert the constructors, so the entry in
  903. // ObjectsUnderConstruction may be missing.
  904. State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
  905. Pred->getLocationContext());
  906. MR = V->getAsRegion();
  907. }
  908. // If copy elision has occurred, and the constructor corresponding to the
  909. // destructor was elided, we need to skip the destructor as well.
  910. if (isDestructorElided(State, BTE, LC)) {
  911. State = cleanupElidedDestructor(State, BTE, LC);
  912. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  913. PostImplicitCall PP(D.getDestructorDecl(getContext()),
  914. D.getBindTemporaryExpr()->getBeginLoc(),
  915. Pred->getLocationContext());
  916. Bldr.generateNode(PP, State, Pred);
  917. return;
  918. }
  919. ExplodedNodeSet CleanDtorState;
  920. StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
  921. StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
  922. QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
  923. // FIXME: Currently CleanDtorState can be empty here due to temporaries being
  924. // bound to default parameters.
  925. assert(CleanDtorState.size() <= 1);
  926. ExplodedNode *CleanPred =
  927. CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
  928. EvalCallOptions CallOpts;
  929. CallOpts.IsTemporaryCtorOrDtor = true;
  930. if (!MR) {
  931. CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
  932. // If we have no MR, we still need to unwrap the array to avoid destroying
  933. // the whole array at once. Regardless, we'd eventually need to model array
  934. // destructors properly, element-by-element.
  935. while (const ArrayType *AT = getContext().getAsArrayType(T)) {
  936. T = AT->getElementType();
  937. CallOpts.IsArrayCtorOrDtor = true;
  938. }
  939. } else {
  940. // We'd eventually need to makeZeroElementRegion() trick here,
  941. // but for now we don't have the respective construction contexts,
  942. // so MR would always be null in this case. Do nothing for now.
  943. }
  944. VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
  945. /*IsBase=*/false, CleanPred, Dst, CallOpts);
  946. }
  947. void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
  948. NodeBuilderContext &BldCtx,
  949. ExplodedNode *Pred,
  950. ExplodedNodeSet &Dst,
  951. const CFGBlock *DstT,
  952. const CFGBlock *DstF) {
  953. BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
  954. ProgramStateRef State = Pred->getState();
  955. const LocationContext *LC = Pred->getLocationContext();
  956. if (getObjectUnderConstruction(State, BTE, LC)) {
  957. TempDtorBuilder.markInfeasible(false);
  958. TempDtorBuilder.generateNode(State, true, Pred);
  959. } else {
  960. TempDtorBuilder.markInfeasible(true);
  961. TempDtorBuilder.generateNode(State, false, Pred);
  962. }
  963. }
  964. void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
  965. ExplodedNodeSet &PreVisit,
  966. ExplodedNodeSet &Dst) {
  967. // This is a fallback solution in case we didn't have a construction
  968. // context when we were constructing the temporary. Otherwise the map should
  969. // have been populated there.
  970. if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) {
  971. // In case we don't have temporary destructors in the CFG, do not mark
  972. // the initialization - we would otherwise never clean it up.
  973. Dst = PreVisit;
  974. return;
  975. }
  976. StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
  977. for (ExplodedNode *Node : PreVisit) {
  978. ProgramStateRef State = Node->getState();
  979. const LocationContext *LC = Node->getLocationContext();
  980. if (!getObjectUnderConstruction(State, BTE, LC)) {
  981. // FIXME: Currently the state might also already contain the marker due to
  982. // incorrect handling of temporaries bound to default parameters; for
  983. // those, we currently skip the CXXBindTemporaryExpr but rely on adding
  984. // temporary destructor nodes.
  985. State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
  986. }
  987. StmtBldr.generateNode(BTE, Node, State);
  988. }
  989. }
  990. ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
  991. PointerEscapeKind K) const {
  992. class CollectReachableSymbolsCallback final : public SymbolVisitor {
  993. InvalidatedSymbols Symbols;
  994. public:
  995. explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
  996. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  997. bool VisitSymbol(SymbolRef Sym) override {
  998. Symbols.insert(Sym);
  999. return true;
  1000. }
  1001. };
  1002. const CollectReachableSymbolsCallback &Scanner =
  1003. State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
  1004. return getCheckerManager().runCheckersForPointerEscape(
  1005. State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
  1006. }
  1007. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  1008. ExplodedNodeSet &DstTop) {
  1009. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1010. S->getBeginLoc(), "Error evaluating statement");
  1011. ExplodedNodeSet Dst;
  1012. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  1013. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  1014. switch (S->getStmtClass()) {
  1015. // C++, OpenMP and ARC stuff we don't support yet.
  1016. case Expr::ObjCIndirectCopyRestoreExprClass:
  1017. case Stmt::CXXDependentScopeMemberExprClass:
  1018. case Stmt::CXXInheritedCtorInitExprClass:
  1019. case Stmt::CXXTryStmtClass:
  1020. case Stmt::CXXTypeidExprClass:
  1021. case Stmt::CXXUuidofExprClass:
  1022. case Stmt::CXXFoldExprClass:
  1023. case Stmt::MSPropertyRefExprClass:
  1024. case Stmt::MSPropertySubscriptExprClass:
  1025. case Stmt::CXXUnresolvedConstructExprClass:
  1026. case Stmt::DependentScopeDeclRefExprClass:
  1027. case Stmt::ArrayTypeTraitExprClass:
  1028. case Stmt::ExpressionTraitExprClass:
  1029. case Stmt::UnresolvedLookupExprClass:
  1030. case Stmt::UnresolvedMemberExprClass:
  1031. case Stmt::TypoExprClass:
  1032. case Stmt::CXXNoexceptExprClass:
  1033. case Stmt::PackExpansionExprClass:
  1034. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  1035. case Stmt::FunctionParmPackExprClass:
  1036. case Stmt::CoroutineBodyStmtClass:
  1037. case Stmt::CoawaitExprClass:
  1038. case Stmt::DependentCoawaitExprClass:
  1039. case Stmt::CoreturnStmtClass:
  1040. case Stmt::CoyieldExprClass:
  1041. case Stmt::SEHTryStmtClass:
  1042. case Stmt::SEHExceptStmtClass:
  1043. case Stmt::SEHLeaveStmtClass:
  1044. case Stmt::SEHFinallyStmtClass:
  1045. case Stmt::OMPParallelDirectiveClass:
  1046. case Stmt::OMPSimdDirectiveClass:
  1047. case Stmt::OMPForDirectiveClass:
  1048. case Stmt::OMPForSimdDirectiveClass:
  1049. case Stmt::OMPSectionsDirectiveClass:
  1050. case Stmt::OMPSectionDirectiveClass:
  1051. case Stmt::OMPSingleDirectiveClass:
  1052. case Stmt::OMPMasterDirectiveClass:
  1053. case Stmt::OMPCriticalDirectiveClass:
  1054. case Stmt::OMPParallelForDirectiveClass:
  1055. case Stmt::OMPParallelForSimdDirectiveClass:
  1056. case Stmt::OMPParallelSectionsDirectiveClass:
  1057. case Stmt::OMPTaskDirectiveClass:
  1058. case Stmt::OMPTaskyieldDirectiveClass:
  1059. case Stmt::OMPBarrierDirectiveClass:
  1060. case Stmt::OMPTaskwaitDirectiveClass:
  1061. case Stmt::OMPTaskgroupDirectiveClass:
  1062. case Stmt::OMPFlushDirectiveClass:
  1063. case Stmt::OMPOrderedDirectiveClass:
  1064. case Stmt::OMPAtomicDirectiveClass:
  1065. case Stmt::OMPTargetDirectiveClass:
  1066. case Stmt::OMPTargetDataDirectiveClass:
  1067. case Stmt::OMPTargetEnterDataDirectiveClass:
  1068. case Stmt::OMPTargetExitDataDirectiveClass:
  1069. case Stmt::OMPTargetParallelDirectiveClass:
  1070. case Stmt::OMPTargetParallelForDirectiveClass:
  1071. case Stmt::OMPTargetUpdateDirectiveClass:
  1072. case Stmt::OMPTeamsDirectiveClass:
  1073. case Stmt::OMPCancellationPointDirectiveClass:
  1074. case Stmt::OMPCancelDirectiveClass:
  1075. case Stmt::OMPTaskLoopDirectiveClass:
  1076. case Stmt::OMPTaskLoopSimdDirectiveClass:
  1077. case Stmt::OMPDistributeDirectiveClass:
  1078. case Stmt::OMPDistributeParallelForDirectiveClass:
  1079. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  1080. case Stmt::OMPDistributeSimdDirectiveClass:
  1081. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  1082. case Stmt::OMPTargetSimdDirectiveClass:
  1083. case Stmt::OMPTeamsDistributeDirectiveClass:
  1084. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  1085. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  1086. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  1087. case Stmt::OMPTargetTeamsDirectiveClass:
  1088. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  1089. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  1090. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  1091. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  1092. case Stmt::CapturedStmtClass: {
  1093. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1094. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1095. break;
  1096. }
  1097. case Stmt::ParenExprClass:
  1098. llvm_unreachable("ParenExprs already handled.");
  1099. case Stmt::GenericSelectionExprClass:
  1100. llvm_unreachable("GenericSelectionExprs already handled.");
  1101. // Cases that should never be evaluated simply because they shouldn't
  1102. // appear in the CFG.
  1103. case Stmt::BreakStmtClass:
  1104. case Stmt::CaseStmtClass:
  1105. case Stmt::CompoundStmtClass:
  1106. case Stmt::ContinueStmtClass:
  1107. case Stmt::CXXForRangeStmtClass:
  1108. case Stmt::DefaultStmtClass:
  1109. case Stmt::DoStmtClass:
  1110. case Stmt::ForStmtClass:
  1111. case Stmt::GotoStmtClass:
  1112. case Stmt::IfStmtClass:
  1113. case Stmt::IndirectGotoStmtClass:
  1114. case Stmt::LabelStmtClass:
  1115. case Stmt::NoStmtClass:
  1116. case Stmt::NullStmtClass:
  1117. case Stmt::SwitchStmtClass:
  1118. case Stmt::WhileStmtClass:
  1119. case Expr::MSDependentExistsStmtClass:
  1120. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  1121. case Stmt::ObjCSubscriptRefExprClass:
  1122. case Stmt::ObjCPropertyRefExprClass:
  1123. llvm_unreachable("These are handled by PseudoObjectExpr");
  1124. case Stmt::GNUNullExprClass: {
  1125. // GNU __null is a pointer-width integer, not an actual pointer.
  1126. ProgramStateRef state = Pred->getState();
  1127. state = state->BindExpr(S, Pred->getLocationContext(),
  1128. svalBuilder.makeIntValWithPtrWidth(0, false));
  1129. Bldr.generateNode(S, Pred, state);
  1130. break;
  1131. }
  1132. case Stmt::ObjCAtSynchronizedStmtClass:
  1133. Bldr.takeNodes(Pred);
  1134. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  1135. Bldr.addNodes(Dst);
  1136. break;
  1137. case Expr::ConstantExprClass:
  1138. case Stmt::ExprWithCleanupsClass:
  1139. // Handled due to fully linearised CFG.
  1140. break;
  1141. case Stmt::CXXBindTemporaryExprClass: {
  1142. Bldr.takeNodes(Pred);
  1143. ExplodedNodeSet PreVisit;
  1144. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1145. ExplodedNodeSet Next;
  1146. VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
  1147. getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
  1148. Bldr.addNodes(Dst);
  1149. break;
  1150. }
  1151. // Cases not handled yet; but will handle some day.
  1152. case Stmt::DesignatedInitExprClass:
  1153. case Stmt::DesignatedInitUpdateExprClass:
  1154. case Stmt::ArrayInitLoopExprClass:
  1155. case Stmt::ArrayInitIndexExprClass:
  1156. case Stmt::ExtVectorElementExprClass:
  1157. case Stmt::ImaginaryLiteralClass:
  1158. case Stmt::ObjCAtCatchStmtClass:
  1159. case Stmt::ObjCAtFinallyStmtClass:
  1160. case Stmt::ObjCAtTryStmtClass:
  1161. case Stmt::ObjCAutoreleasePoolStmtClass:
  1162. case Stmt::ObjCEncodeExprClass:
  1163. case Stmt::ObjCIsaExprClass:
  1164. case Stmt::ObjCProtocolExprClass:
  1165. case Stmt::ObjCSelectorExprClass:
  1166. case Stmt::ParenListExprClass:
  1167. case Stmt::ShuffleVectorExprClass:
  1168. case Stmt::ConvertVectorExprClass:
  1169. case Stmt::VAArgExprClass:
  1170. case Stmt::CUDAKernelCallExprClass:
  1171. case Stmt::OpaqueValueExprClass:
  1172. case Stmt::AsTypeExprClass:
  1173. // Fall through.
  1174. // Cases we intentionally don't evaluate, since they don't need
  1175. // to be explicitly evaluated.
  1176. case Stmt::PredefinedExprClass:
  1177. case Stmt::AddrLabelExprClass:
  1178. case Stmt::AttributedStmtClass:
  1179. case Stmt::IntegerLiteralClass:
  1180. case Stmt::FixedPointLiteralClass:
  1181. case Stmt::CharacterLiteralClass:
  1182. case Stmt::ImplicitValueInitExprClass:
  1183. case Stmt::CXXScalarValueInitExprClass:
  1184. case Stmt::CXXBoolLiteralExprClass:
  1185. case Stmt::ObjCBoolLiteralExprClass:
  1186. case Stmt::ObjCAvailabilityCheckExprClass:
  1187. case Stmt::FloatingLiteralClass:
  1188. case Stmt::NoInitExprClass:
  1189. case Stmt::SizeOfPackExprClass:
  1190. case Stmt::StringLiteralClass:
  1191. case Stmt::ObjCStringLiteralClass:
  1192. case Stmt::CXXPseudoDestructorExprClass:
  1193. case Stmt::SubstNonTypeTemplateParmExprClass:
  1194. case Stmt::CXXNullPtrLiteralExprClass:
  1195. case Stmt::OMPArraySectionExprClass:
  1196. case Stmt::TypeTraitExprClass: {
  1197. Bldr.takeNodes(Pred);
  1198. ExplodedNodeSet preVisit;
  1199. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1200. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  1201. Bldr.addNodes(Dst);
  1202. break;
  1203. }
  1204. case Stmt::CXXDefaultArgExprClass:
  1205. case Stmt::CXXDefaultInitExprClass: {
  1206. Bldr.takeNodes(Pred);
  1207. ExplodedNodeSet PreVisit;
  1208. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1209. ExplodedNodeSet Tmp;
  1210. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  1211. const Expr *ArgE;
  1212. if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  1213. ArgE = DefE->getExpr();
  1214. else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  1215. ArgE = DefE->getExpr();
  1216. else
  1217. llvm_unreachable("unknown constant wrapper kind");
  1218. bool IsTemporary = false;
  1219. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  1220. ArgE = MTE->GetTemporaryExpr();
  1221. IsTemporary = true;
  1222. }
  1223. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  1224. if (!ConstantVal)
  1225. ConstantVal = UnknownVal();
  1226. const LocationContext *LCtx = Pred->getLocationContext();
  1227. for (const auto I : PreVisit) {
  1228. ProgramStateRef State = I->getState();
  1229. State = State->BindExpr(S, LCtx, *ConstantVal);
  1230. if (IsTemporary)
  1231. State = createTemporaryRegionIfNeeded(State, LCtx,
  1232. cast<Expr>(S),
  1233. cast<Expr>(S));
  1234. Bldr2.generateNode(S, I, State);
  1235. }
  1236. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1237. Bldr.addNodes(Dst);
  1238. break;
  1239. }
  1240. // Cases we evaluate as opaque expressions, conjuring a symbol.
  1241. case Stmt::CXXStdInitializerListExprClass:
  1242. case Expr::ObjCArrayLiteralClass:
  1243. case Expr::ObjCDictionaryLiteralClass:
  1244. case Expr::ObjCBoxedExprClass: {
  1245. Bldr.takeNodes(Pred);
  1246. ExplodedNodeSet preVisit;
  1247. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1248. ExplodedNodeSet Tmp;
  1249. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  1250. const auto *Ex = cast<Expr>(S);
  1251. QualType resultType = Ex->getType();
  1252. for (const auto N : preVisit) {
  1253. const LocationContext *LCtx = N->getLocationContext();
  1254. SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  1255. resultType,
  1256. currBldrCtx->blockCount());
  1257. ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
  1258. // Escape pointers passed into the list, unless it's an ObjC boxed
  1259. // expression which is not a boxable C structure.
  1260. if (!(isa<ObjCBoxedExpr>(Ex) &&
  1261. !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
  1262. ->getType()->isRecordType()))
  1263. for (auto Child : Ex->children()) {
  1264. assert(Child);
  1265. SVal Val = State->getSVal(Child, LCtx);
  1266. State = escapeValue(State, Val, PSK_EscapeOther);
  1267. }
  1268. Bldr2.generateNode(S, N, State);
  1269. }
  1270. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1271. Bldr.addNodes(Dst);
  1272. break;
  1273. }
  1274. case Stmt::ArraySubscriptExprClass:
  1275. Bldr.takeNodes(Pred);
  1276. VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  1277. Bldr.addNodes(Dst);
  1278. break;
  1279. case Stmt::GCCAsmStmtClass:
  1280. Bldr.takeNodes(Pred);
  1281. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  1282. Bldr.addNodes(Dst);
  1283. break;
  1284. case Stmt::MSAsmStmtClass:
  1285. Bldr.takeNodes(Pred);
  1286. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  1287. Bldr.addNodes(Dst);
  1288. break;
  1289. case Stmt::BlockExprClass:
  1290. Bldr.takeNodes(Pred);
  1291. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  1292. Bldr.addNodes(Dst);
  1293. break;
  1294. case Stmt::LambdaExprClass:
  1295. if (AMgr.options.ShouldInlineLambdas) {
  1296. Bldr.takeNodes(Pred);
  1297. VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
  1298. Bldr.addNodes(Dst);
  1299. } else {
  1300. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1301. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1302. }
  1303. break;
  1304. case Stmt::BinaryOperatorClass: {
  1305. const auto *B = cast<BinaryOperator>(S);
  1306. if (B->isLogicalOp()) {
  1307. Bldr.takeNodes(Pred);
  1308. VisitLogicalExpr(B, Pred, Dst);
  1309. Bldr.addNodes(Dst);
  1310. break;
  1311. }
  1312. else if (B->getOpcode() == BO_Comma) {
  1313. ProgramStateRef state = Pred->getState();
  1314. Bldr.generateNode(B, Pred,
  1315. state->BindExpr(B, Pred->getLocationContext(),
  1316. state->getSVal(B->getRHS(),
  1317. Pred->getLocationContext())));
  1318. break;
  1319. }
  1320. Bldr.takeNodes(Pred);
  1321. if (AMgr.options.ShouldEagerlyAssume &&
  1322. (B->isRelationalOp() || B->isEqualityOp())) {
  1323. ExplodedNodeSet Tmp;
  1324. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  1325. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  1326. }
  1327. else
  1328. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1329. Bldr.addNodes(Dst);
  1330. break;
  1331. }
  1332. case Stmt::CXXOperatorCallExprClass: {
  1333. const auto *OCE = cast<CXXOperatorCallExpr>(S);
  1334. // For instance method operators, make sure the 'this' argument has a
  1335. // valid region.
  1336. const Decl *Callee = OCE->getCalleeDecl();
  1337. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  1338. if (MD->isInstance()) {
  1339. ProgramStateRef State = Pred->getState();
  1340. const LocationContext *LCtx = Pred->getLocationContext();
  1341. ProgramStateRef NewState =
  1342. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  1343. if (NewState != State) {
  1344. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
  1345. ProgramPoint::PreStmtKind);
  1346. // Did we cache out?
  1347. if (!Pred)
  1348. break;
  1349. }
  1350. }
  1351. }
  1352. // FALLTHROUGH
  1353. LLVM_FALLTHROUGH;
  1354. }
  1355. case Stmt::CallExprClass:
  1356. case Stmt::CXXMemberCallExprClass:
  1357. case Stmt::UserDefinedLiteralClass:
  1358. Bldr.takeNodes(Pred);
  1359. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  1360. Bldr.addNodes(Dst);
  1361. break;
  1362. case Stmt::CXXCatchStmtClass:
  1363. Bldr.takeNodes(Pred);
  1364. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  1365. Bldr.addNodes(Dst);
  1366. break;
  1367. case Stmt::CXXTemporaryObjectExprClass:
  1368. case Stmt::CXXConstructExprClass:
  1369. Bldr.takeNodes(Pred);
  1370. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  1371. Bldr.addNodes(Dst);
  1372. break;
  1373. case Stmt::CXXNewExprClass: {
  1374. Bldr.takeNodes(Pred);
  1375. ExplodedNodeSet PreVisit;
  1376. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1377. ExplodedNodeSet PostVisit;
  1378. for (const auto i : PreVisit)
  1379. VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
  1380. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1381. Bldr.addNodes(Dst);
  1382. break;
  1383. }
  1384. case Stmt::CXXDeleteExprClass: {
  1385. Bldr.takeNodes(Pred);
  1386. ExplodedNodeSet PreVisit;
  1387. const auto *CDE = cast<CXXDeleteExpr>(S);
  1388. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1389. for (const auto i : PreVisit)
  1390. VisitCXXDeleteExpr(CDE, i, Dst);
  1391. Bldr.addNodes(Dst);
  1392. break;
  1393. }
  1394. // FIXME: ChooseExpr is really a constant. We need to fix
  1395. // the CFG do not model them as explicit control-flow.
  1396. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  1397. Bldr.takeNodes(Pred);
  1398. const auto *C = cast<ChooseExpr>(S);
  1399. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  1400. Bldr.addNodes(Dst);
  1401. break;
  1402. }
  1403. case Stmt::CompoundAssignOperatorClass:
  1404. Bldr.takeNodes(Pred);
  1405. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1406. Bldr.addNodes(Dst);
  1407. break;
  1408. case Stmt::CompoundLiteralExprClass:
  1409. Bldr.takeNodes(Pred);
  1410. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  1411. Bldr.addNodes(Dst);
  1412. break;
  1413. case Stmt::BinaryConditionalOperatorClass:
  1414. case Stmt::ConditionalOperatorClass: { // '?' operator
  1415. Bldr.takeNodes(Pred);
  1416. const auto *C = cast<AbstractConditionalOperator>(S);
  1417. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  1418. Bldr.addNodes(Dst);
  1419. break;
  1420. }
  1421. case Stmt::CXXThisExprClass:
  1422. Bldr.takeNodes(Pred);
  1423. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  1424. Bldr.addNodes(Dst);
  1425. break;
  1426. case Stmt::DeclRefExprClass: {
  1427. Bldr.takeNodes(Pred);
  1428. const auto *DE = cast<DeclRefExpr>(S);
  1429. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  1430. Bldr.addNodes(Dst);
  1431. break;
  1432. }
  1433. case Stmt::DeclStmtClass:
  1434. Bldr.takeNodes(Pred);
  1435. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  1436. Bldr.addNodes(Dst);
  1437. break;
  1438. case Stmt::ImplicitCastExprClass:
  1439. case Stmt::CStyleCastExprClass:
  1440. case Stmt::CXXStaticCastExprClass:
  1441. case Stmt::CXXDynamicCastExprClass:
  1442. case Stmt::CXXReinterpretCastExprClass:
  1443. case Stmt::CXXConstCastExprClass:
  1444. case Stmt::CXXFunctionalCastExprClass:
  1445. case Stmt::ObjCBridgedCastExprClass: {
  1446. Bldr.takeNodes(Pred);
  1447. const auto *C = cast<CastExpr>(S);
  1448. ExplodedNodeSet dstExpr;
  1449. VisitCast(C, C->getSubExpr(), Pred, dstExpr);
  1450. // Handle the postvisit checks.
  1451. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  1452. Bldr.addNodes(Dst);
  1453. break;
  1454. }
  1455. case Expr::MaterializeTemporaryExprClass: {
  1456. Bldr.takeNodes(Pred);
  1457. const auto *MTE = cast<MaterializeTemporaryExpr>(S);
  1458. ExplodedNodeSet dstPrevisit;
  1459. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
  1460. ExplodedNodeSet dstExpr;
  1461. for (const auto i : dstPrevisit)
  1462. CreateCXXTemporaryObject(MTE, i, dstExpr);
  1463. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
  1464. Bldr.addNodes(Dst);
  1465. break;
  1466. }
  1467. case Stmt::InitListExprClass:
  1468. Bldr.takeNodes(Pred);
  1469. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  1470. Bldr.addNodes(Dst);
  1471. break;
  1472. case Stmt::MemberExprClass:
  1473. Bldr.takeNodes(Pred);
  1474. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  1475. Bldr.addNodes(Dst);
  1476. break;
  1477. case Stmt::AtomicExprClass:
  1478. Bldr.takeNodes(Pred);
  1479. VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
  1480. Bldr.addNodes(Dst);
  1481. break;
  1482. case Stmt::ObjCIvarRefExprClass:
  1483. Bldr.takeNodes(Pred);
  1484. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  1485. Bldr.addNodes(Dst);
  1486. break;
  1487. case Stmt::ObjCForCollectionStmtClass:
  1488. Bldr.takeNodes(Pred);
  1489. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  1490. Bldr.addNodes(Dst);
  1491. break;
  1492. case Stmt::ObjCMessageExprClass:
  1493. Bldr.takeNodes(Pred);
  1494. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  1495. Bldr.addNodes(Dst);
  1496. break;
  1497. case Stmt::ObjCAtThrowStmtClass:
  1498. case Stmt::CXXThrowExprClass:
  1499. // FIXME: This is not complete. We basically treat @throw as
  1500. // an abort.
  1501. Bldr.generateSink(S, Pred, Pred->getState());
  1502. break;
  1503. case Stmt::ReturnStmtClass:
  1504. Bldr.takeNodes(Pred);
  1505. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  1506. Bldr.addNodes(Dst);
  1507. break;
  1508. case Stmt::OffsetOfExprClass: {
  1509. Bldr.takeNodes(Pred);
  1510. ExplodedNodeSet PreVisit;
  1511. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1512. ExplodedNodeSet PostVisit;
  1513. for (const auto Node : PreVisit)
  1514. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
  1515. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1516. Bldr.addNodes(Dst);
  1517. break;
  1518. }
  1519. case Stmt::UnaryExprOrTypeTraitExprClass:
  1520. Bldr.takeNodes(Pred);
  1521. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1522. Pred, Dst);
  1523. Bldr.addNodes(Dst);
  1524. break;
  1525. case Stmt::StmtExprClass: {
  1526. const auto *SE = cast<StmtExpr>(S);
  1527. if (SE->getSubStmt()->body_empty()) {
  1528. // Empty statement expression.
  1529. assert(SE->getType() == getContext().VoidTy
  1530. && "Empty statement expression must have void type.");
  1531. break;
  1532. }
  1533. if (const auto *LastExpr =
  1534. dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  1535. ProgramStateRef state = Pred->getState();
  1536. Bldr.generateNode(SE, Pred,
  1537. state->BindExpr(SE, Pred->getLocationContext(),
  1538. state->getSVal(LastExpr,
  1539. Pred->getLocationContext())));
  1540. }
  1541. break;
  1542. }
  1543. case Stmt::UnaryOperatorClass: {
  1544. Bldr.takeNodes(Pred);
  1545. const auto *U = cast<UnaryOperator>(S);
  1546. if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
  1547. ExplodedNodeSet Tmp;
  1548. VisitUnaryOperator(U, Pred, Tmp);
  1549. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  1550. }
  1551. else
  1552. VisitUnaryOperator(U, Pred, Dst);
  1553. Bldr.addNodes(Dst);
  1554. break;
  1555. }
  1556. case Stmt::PseudoObjectExprClass: {
  1557. Bldr.takeNodes(Pred);
  1558. ProgramStateRef state = Pred->getState();
  1559. const auto *PE = cast<PseudoObjectExpr>(S);
  1560. if (const Expr *Result = PE->getResultExpr()) {
  1561. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1562. Bldr.generateNode(S, Pred,
  1563. state->BindExpr(S, Pred->getLocationContext(), V));
  1564. }
  1565. else
  1566. Bldr.generateNode(S, Pred,
  1567. state->BindExpr(S, Pred->getLocationContext(),
  1568. UnknownVal()));
  1569. Bldr.addNodes(Dst);
  1570. break;
  1571. }
  1572. }
  1573. }
  1574. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1575. const LocationContext *CalleeLC) {
  1576. const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
  1577. const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
  1578. assert(CalleeSF && CallerSF);
  1579. ExplodedNode *BeforeProcessingCall = nullptr;
  1580. const Stmt *CE = CalleeSF->getCallSite();
  1581. // Find the first node before we started processing the call expression.
  1582. while (N) {
  1583. ProgramPoint L = N->getLocation();
  1584. BeforeProcessingCall = N;
  1585. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1586. // Skip the nodes corresponding to the inlined code.
  1587. if (L.getStackFrame() != CallerSF)
  1588. continue;
  1589. // We reached the caller. Find the node right before we started
  1590. // processing the call.
  1591. if (L.isPurgeKind())
  1592. continue;
  1593. if (L.getAs<PreImplicitCall>())
  1594. continue;
  1595. if (L.getAs<CallEnter>())
  1596. continue;
  1597. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1598. if (SP->getStmt() == CE)
  1599. continue;
  1600. break;
  1601. }
  1602. if (!BeforeProcessingCall)
  1603. return false;
  1604. // TODO: Clean up the unneeded nodes.
  1605. // Build an Epsilon node from which we will restart the analyzes.
  1606. // Note that CE is permitted to be NULL!
  1607. ProgramPoint NewNodeLoc =
  1608. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1609. // Add the special flag to GDM to signal retrying with no inlining.
  1610. // Note, changing the state ensures that we are not going to cache out.
  1611. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1612. NewNodeState =
  1613. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1614. // Make the new node a successor of BeforeProcessingCall.
  1615. bool IsNew = false;
  1616. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1617. // We cached out at this point. Caching out is common due to us backtracking
  1618. // from the inlined function, which might spawn several paths.
  1619. if (!IsNew)
  1620. return true;
  1621. NewNode->addPredecessor(BeforeProcessingCall, G);
  1622. // Add the new node to the work list.
  1623. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1624. CalleeSF->getIndex());
  1625. NumTimesRetriedWithoutInlining++;
  1626. return true;
  1627. }
  1628. /// Block entrance. (Update counters).
  1629. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1630. NodeBuilderWithSinks &nodeBuilder,
  1631. ExplodedNode *Pred) {
  1632. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1633. // If we reach a loop which has a known bound (and meets
  1634. // other constraints) then consider completely unrolling it.
  1635. if(AMgr.options.ShouldUnrollLoops) {
  1636. unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
  1637. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1638. if (Term) {
  1639. ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
  1640. Pred, maxBlockVisitOnPath);
  1641. if (NewState != Pred->getState()) {
  1642. ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
  1643. if (!UpdatedNode)
  1644. return;
  1645. Pred = UpdatedNode;
  1646. }
  1647. }
  1648. // Is we are inside an unrolled loop then no need the check the counters.
  1649. if(isUnrolledState(Pred->getState()))
  1650. return;
  1651. }
  1652. // If this block is terminated by a loop and it has already been visited the
  1653. // maximum number of times, widen the loop.
  1654. unsigned int BlockCount = nodeBuilder.getContext().blockCount();
  1655. if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
  1656. AMgr.options.ShouldWidenLoops) {
  1657. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1658. if (!(Term &&
  1659. (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
  1660. return;
  1661. // Widen.
  1662. const LocationContext *LCtx = Pred->getLocationContext();
  1663. ProgramStateRef WidenedState =
  1664. getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
  1665. nodeBuilder.generateNode(WidenedState, Pred);
  1666. return;
  1667. }
  1668. // FIXME: Refactor this into a checker.
  1669. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
  1670. static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
  1671. const ExplodedNode *Sink =
  1672. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1673. // Check if we stopped at the top level function or not.
  1674. // Root node should have the location context of the top most function.
  1675. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1676. const LocationContext *CalleeSF = CalleeLC->getStackFrame();
  1677. const LocationContext *RootLC =
  1678. (*G.roots_begin())->getLocation().getLocationContext();
  1679. if (RootLC->getStackFrame() != CalleeSF) {
  1680. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1681. // Re-run the call evaluation without inlining it, by storing the
  1682. // no-inlining policy in the state and enqueuing the new work item on
  1683. // the list. Replay should almost never fail. Use the stats to catch it
  1684. // if it does.
  1685. if ((!AMgr.options.NoRetryExhausted &&
  1686. replayWithoutInlining(Pred, CalleeLC)))
  1687. return;
  1688. NumMaxBlockCountReachedInInlined++;
  1689. } else
  1690. NumMaxBlockCountReached++;
  1691. // Make sink nodes as exhausted(for stats) only if retry failed.
  1692. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1693. }
  1694. }
  1695. //===----------------------------------------------------------------------===//
  1696. // Branch processing.
  1697. //===----------------------------------------------------------------------===//
  1698. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1699. /// to try to recover some path-sensitivity for casts of symbolic
  1700. /// integers that promote their values (which are currently not tracked well).
  1701. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1702. // cast(s) did was sign-extend the original value.
  1703. static SVal RecoverCastedSymbol(ProgramStateRef state,
  1704. const Stmt *Condition,
  1705. const LocationContext *LCtx,
  1706. ASTContext &Ctx) {
  1707. const auto *Ex = dyn_cast<Expr>(Condition);
  1708. if (!Ex)
  1709. return UnknownVal();
  1710. uint64_t bits = 0;
  1711. bool bitsInit = false;
  1712. while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
  1713. QualType T = CE->getType();
  1714. if (!T->isIntegralOrEnumerationType())
  1715. return UnknownVal();
  1716. uint64_t newBits = Ctx.getTypeSize(T);
  1717. if (!bitsInit || newBits < bits) {
  1718. bitsInit = true;
  1719. bits = newBits;
  1720. }
  1721. Ex = CE->getSubExpr();
  1722. }
  1723. // We reached a non-cast. Is it a symbolic value?
  1724. QualType T = Ex->getType();
  1725. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1726. Ctx.getTypeSize(T) > bits)
  1727. return UnknownVal();
  1728. return state->getSVal(Ex, LCtx);
  1729. }
  1730. #ifndef NDEBUG
  1731. static const Stmt *getRightmostLeaf(const Stmt *Condition) {
  1732. while (Condition) {
  1733. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1734. if (!BO || !BO->isLogicalOp()) {
  1735. return Condition;
  1736. }
  1737. Condition = BO->getRHS()->IgnoreParens();
  1738. }
  1739. return nullptr;
  1740. }
  1741. #endif
  1742. // Returns the condition the branch at the end of 'B' depends on and whose value
  1743. // has been evaluated within 'B'.
  1744. // In most cases, the terminator condition of 'B' will be evaluated fully in
  1745. // the last statement of 'B'; in those cases, the resolved condition is the
  1746. // given 'Condition'.
  1747. // If the condition of the branch is a logical binary operator tree, the CFG is
  1748. // optimized: in that case, we know that the expression formed by all but the
  1749. // rightmost leaf of the logical binary operator tree must be true, and thus
  1750. // the branch condition is at this point equivalent to the truth value of that
  1751. // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
  1752. // expression in its final statement. As the full condition in that case was
  1753. // not evaluated, and is thus not in the SVal cache, we need to use that leaf
  1754. // expression to evaluate the truth value of the condition in the current state
  1755. // space.
  1756. static const Stmt *ResolveCondition(const Stmt *Condition,
  1757. const CFGBlock *B) {
  1758. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1759. Condition = Ex->IgnoreParens();
  1760. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1761. if (!BO || !BO->isLogicalOp())
  1762. return Condition;
  1763. assert(!B->getTerminator().isTemporaryDtorsBranch() &&
  1764. "Temporary destructor branches handled by processBindTemporary.");
  1765. // For logical operations, we still have the case where some branches
  1766. // use the traditional "merge" approach and others sink the branch
  1767. // directly into the basic blocks representing the logical operation.
  1768. // We need to distinguish between those two cases here.
  1769. // The invariants are still shifting, but it is possible that the
  1770. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1771. // CFGStmt as the value of the condition.
  1772. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1773. for (; I != E; ++I) {
  1774. CFGElement Elem = *I;
  1775. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1776. if (!CS)
  1777. continue;
  1778. const Stmt *LastStmt = CS->getStmt();
  1779. assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
  1780. return LastStmt;
  1781. }
  1782. llvm_unreachable("could not resolve condition");
  1783. }
  1784. void ExprEngine::processBranch(const Stmt *Condition,
  1785. NodeBuilderContext& BldCtx,
  1786. ExplodedNode *Pred,
  1787. ExplodedNodeSet &Dst,
  1788. const CFGBlock *DstT,
  1789. const CFGBlock *DstF) {
  1790. assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
  1791. "CXXBindTemporaryExprs are handled by processBindTemporary.");
  1792. const LocationContext *LCtx = Pred->getLocationContext();
  1793. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1794. currBldrCtx = &BldCtx;
  1795. // Check for NULL conditions; e.g. "for(;;)"
  1796. if (!Condition) {
  1797. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1798. NullCondBldr.markInfeasible(false);
  1799. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1800. return;
  1801. }
  1802. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1803. Condition = Ex->IgnoreParens();
  1804. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1805. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1806. Condition->getBeginLoc(),
  1807. "Error evaluating branch");
  1808. ExplodedNodeSet CheckersOutSet;
  1809. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1810. Pred, *this);
  1811. // We generated only sinks.
  1812. if (CheckersOutSet.empty())
  1813. return;
  1814. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1815. for (const auto PredI : CheckersOutSet) {
  1816. if (PredI->isSink())
  1817. continue;
  1818. ProgramStateRef PrevState = PredI->getState();
  1819. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1820. if (X.isUnknownOrUndef()) {
  1821. // Give it a chance to recover from unknown.
  1822. if (const auto *Ex = dyn_cast<Expr>(Condition)) {
  1823. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1824. // Try to recover some path-sensitivity. Right now casts of symbolic
  1825. // integers that promote their values are currently not tracked well.
  1826. // If 'Condition' is such an expression, try and recover the
  1827. // underlying value and use that instead.
  1828. SVal recovered = RecoverCastedSymbol(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 four possible cases:
  2280. // (1) We are binding to something that is not a memory region.
  2281. // (2) We are binding to a MemRegion that does not have stack storage.
  2282. // (3) We are binding to a top-level parameter region with a non-trivial
  2283. // destructor. We won't see the destructor during analysis, but it's there.
  2284. // (4) We are binding to a MemRegion with stack storage that the store
  2285. // does not understand.
  2286. ProgramStateRef
  2287. ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc,
  2288. SVal Val, const LocationContext *LCtx) {
  2289. // Cases (1) and (2).
  2290. const MemRegion *MR = Loc.getAsRegion();
  2291. if (!MR || !MR->hasStackStorage())
  2292. return escapeValue(State, Val, PSK_EscapeOnBind);
  2293. // Case (3).
  2294. if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
  2295. if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame())
  2296. if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
  2297. if (!RD->hasTrivialDestructor())
  2298. return escapeValue(State, Val, PSK_EscapeOnBind);
  2299. // Case (4): in order to test that, generate a new state with the binding
  2300. // added. If it is the same state, then it escapes (since the store cannot
  2301. // represent the binding).
  2302. // Do this only if we know that the store is not supposed to generate the
  2303. // same state.
  2304. SVal StoredVal = State->getSVal(MR);
  2305. if (StoredVal != Val)
  2306. if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx)))
  2307. return escapeValue(State, Val, PSK_EscapeOnBind);
  2308. return State;
  2309. }
  2310. ProgramStateRef
  2311. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  2312. const InvalidatedSymbols *Invalidated,
  2313. ArrayRef<const MemRegion *> ExplicitRegions,
  2314. const CallEvent *Call,
  2315. RegionAndSymbolInvalidationTraits &ITraits) {
  2316. if (!Invalidated || Invalidated->empty())
  2317. return State;
  2318. if (!Call)
  2319. return getCheckerManager().runCheckersForPointerEscape(State,
  2320. *Invalidated,
  2321. nullptr,
  2322. PSK_EscapeOther,
  2323. &ITraits);
  2324. // If the symbols were invalidated by a call, we want to find out which ones
  2325. // were invalidated directly due to being arguments to the call.
  2326. InvalidatedSymbols SymbolsDirectlyInvalidated;
  2327. for (const auto I : ExplicitRegions) {
  2328. if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
  2329. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  2330. }
  2331. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  2332. for (const auto &sym : *Invalidated) {
  2333. if (SymbolsDirectlyInvalidated.count(sym))
  2334. continue;
  2335. SymbolsIndirectlyInvalidated.insert(sym);
  2336. }
  2337. if (!SymbolsDirectlyInvalidated.empty())
  2338. State = getCheckerManager().runCheckersForPointerEscape(State,
  2339. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  2340. // Notify about the symbols that get indirectly invalidated by the call.
  2341. if (!SymbolsIndirectlyInvalidated.empty())
  2342. State = getCheckerManager().runCheckersForPointerEscape(State,
  2343. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  2344. return State;
  2345. }
  2346. /// evalBind - Handle the semantics of binding a value to a specific location.
  2347. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  2348. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  2349. ExplodedNode *Pred,
  2350. SVal location, SVal Val,
  2351. bool atDeclInit, const ProgramPoint *PP) {
  2352. const LocationContext *LC = Pred->getLocationContext();
  2353. PostStmt PS(StoreE, LC);
  2354. if (!PP)
  2355. PP = &PS;
  2356. // Do a previsit of the bind.
  2357. ExplodedNodeSet CheckedSet;
  2358. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  2359. StoreE, *this, *PP);
  2360. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  2361. // If the location is not a 'Loc', it will already be handled by
  2362. // the checkers. There is nothing left to do.
  2363. if (!location.getAs<Loc>()) {
  2364. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
  2365. /*tag*/nullptr);
  2366. ProgramStateRef state = Pred->getState();
  2367. state = processPointerEscapedOnBind(state, location, Val, LC);
  2368. Bldr.generateNode(L, state, Pred);
  2369. return;
  2370. }
  2371. for (const auto PredI : CheckedSet) {
  2372. ProgramStateRef state = PredI->getState();
  2373. state = processPointerEscapedOnBind(state, location, Val, LC);
  2374. // When binding the value, pass on the hint that this is a initialization.
  2375. // For initializations, we do not need to inform clients of region
  2376. // changes.
  2377. state = state->bindLoc(location.castAs<Loc>(),
  2378. Val, LC, /* notifyChanges = */ !atDeclInit);
  2379. const MemRegion *LocReg = nullptr;
  2380. if (Optional<loc::MemRegionVal> LocRegVal =
  2381. location.getAs<loc::MemRegionVal>()) {
  2382. LocReg = LocRegVal->getRegion();
  2383. }
  2384. const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
  2385. Bldr.generateNode(L, state, PredI);
  2386. }
  2387. }
  2388. /// evalStore - Handle the semantics of a store via an assignment.
  2389. /// @param Dst The node set to store generated state nodes
  2390. /// @param AssignE The assignment expression if the store happens in an
  2391. /// assignment.
  2392. /// @param LocationE The location expression that is stored to.
  2393. /// @param state The current simulation state
  2394. /// @param location The location to store the value
  2395. /// @param Val The value to be stored
  2396. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  2397. const Expr *LocationE,
  2398. ExplodedNode *Pred,
  2399. ProgramStateRef state, SVal location, SVal Val,
  2400. const ProgramPointTag *tag) {
  2401. // Proceed with the store. We use AssignE as the anchor for the PostStore
  2402. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  2403. const Expr *StoreE = AssignE ? AssignE : LocationE;
  2404. // Evaluate the location (checks for bad dereferences).
  2405. ExplodedNodeSet Tmp;
  2406. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
  2407. if (Tmp.empty())
  2408. return;
  2409. if (location.isUndef())
  2410. return;
  2411. for (const auto I : Tmp)
  2412. evalBind(Dst, StoreE, I, location, Val, false);
  2413. }
  2414. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  2415. const Expr *NodeEx,
  2416. const Expr *BoundEx,
  2417. ExplodedNode *Pred,
  2418. ProgramStateRef state,
  2419. SVal location,
  2420. const ProgramPointTag *tag,
  2421. QualType LoadTy) {
  2422. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  2423. assert(NodeEx);
  2424. assert(BoundEx);
  2425. // Evaluate the location (checks for bad dereferences).
  2426. ExplodedNodeSet Tmp;
  2427. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
  2428. if (Tmp.empty())
  2429. return;
  2430. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  2431. if (location.isUndef())
  2432. return;
  2433. // Proceed with the load.
  2434. for (const auto I : Tmp) {
  2435. state = I->getState();
  2436. const LocationContext *LCtx = I->getLocationContext();
  2437. SVal V = UnknownVal();
  2438. if (location.isValid()) {
  2439. if (LoadTy.isNull())
  2440. LoadTy = BoundEx->getType();
  2441. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  2442. }
  2443. Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
  2444. ProgramPoint::PostLoadKind);
  2445. }
  2446. }
  2447. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  2448. const Stmt *NodeEx,
  2449. const Stmt *BoundEx,
  2450. ExplodedNode *Pred,
  2451. ProgramStateRef state,
  2452. SVal location,
  2453. bool isLoad) {
  2454. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  2455. // Early checks for performance reason.
  2456. if (location.isUnknown()) {
  2457. return;
  2458. }
  2459. ExplodedNodeSet Src;
  2460. BldrTop.takeNodes(Pred);
  2461. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  2462. if (Pred->getState() != state) {
  2463. // Associate this new state with an ExplodedNode.
  2464. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  2465. // int *p;
  2466. // p = 0;
  2467. // *p = 0xDEADBEEF;
  2468. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  2469. // instead "int *p" is noted as
  2470. // "Variable 'p' initialized to a null pointer value"
  2471. static SimpleProgramPointTag tag(TagProviderName, "Location");
  2472. Bldr.generateNode(NodeEx, Pred, state, &tag);
  2473. }
  2474. ExplodedNodeSet Tmp;
  2475. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  2476. NodeEx, BoundEx, *this);
  2477. BldrTop.addNodes(Tmp);
  2478. }
  2479. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  2480. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  2481. static SimpleProgramPointTag
  2482. eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
  2483. "Eagerly Assume True"),
  2484. eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
  2485. "Eagerly Assume False");
  2486. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  2487. &eagerlyAssumeBinOpBifurcationFalse);
  2488. }
  2489. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  2490. ExplodedNodeSet &Src,
  2491. const Expr *Ex) {
  2492. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  2493. for (const auto Pred : Src) {
  2494. // Test if the previous node was as the same expression. This can happen
  2495. // when the expression fails to evaluate to anything meaningful and
  2496. // (as an optimization) we don't generate a node.
  2497. ProgramPoint P = Pred->getLocation();
  2498. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  2499. continue;
  2500. }
  2501. ProgramStateRef state = Pred->getState();
  2502. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  2503. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  2504. if (SEV && SEV->isExpression()) {
  2505. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  2506. geteagerlyAssumeBinOpBifurcationTags();
  2507. ProgramStateRef StateTrue, StateFalse;
  2508. std::tie(StateTrue, StateFalse) = state->assume(*SEV);
  2509. // First assume that the condition is true.
  2510. if (StateTrue) {
  2511. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  2512. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  2513. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  2514. }
  2515. // Next, assume that the condition is false.
  2516. if (StateFalse) {
  2517. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  2518. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  2519. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  2520. }
  2521. }
  2522. }
  2523. }
  2524. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  2525. ExplodedNodeSet &Dst) {
  2526. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2527. // We have processed both the inputs and the outputs. All of the outputs
  2528. // should evaluate to Locs. Nuke all of their values.
  2529. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2530. // which interprets the inline asm and stores proper results in the
  2531. // outputs.
  2532. ProgramStateRef state = Pred->getState();
  2533. for (const Expr *O : A->outputs()) {
  2534. SVal X = state->getSVal(O, Pred->getLocationContext());
  2535. assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  2536. if (Optional<Loc> LV = X.getAs<Loc>())
  2537. state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
  2538. }
  2539. Bldr.generateNode(A, Pred, state);
  2540. }
  2541. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  2542. ExplodedNodeSet &Dst) {
  2543. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2544. Bldr.generateNode(A, Pred, Pred->getState());
  2545. }
  2546. //===----------------------------------------------------------------------===//
  2547. // Visualization.
  2548. //===----------------------------------------------------------------------===//
  2549. #ifndef NDEBUG
  2550. namespace llvm {
  2551. template<>
  2552. struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
  2553. DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  2554. static bool nodeHasBugReport(const ExplodedNode *N) {
  2555. BugReporter &BR = static_cast<ExprEngine &>(
  2556. N->getState()->getStateManager().getOwningEngine()).getBugReporter();
  2557. const auto EQClasses =
  2558. llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
  2559. for (const auto &EQ : EQClasses) {
  2560. for (const BugReport &Report : EQ) {
  2561. if (Report.getErrorNode() == N)
  2562. return true;
  2563. }
  2564. }
  2565. return false;
  2566. }
  2567. /// \p PreCallback: callback before break.
  2568. /// \p PostCallback: callback after break.
  2569. /// \p Stop: stop iteration if returns {@code true}
  2570. /// \return Whether {@code Stop} ever returned {@code true}.
  2571. static bool traverseHiddenNodes(
  2572. const ExplodedNode *N,
  2573. llvm::function_ref<void(const ExplodedNode *)> PreCallback,
  2574. llvm::function_ref<void(const ExplodedNode *)> PostCallback,
  2575. llvm::function_ref<bool(const ExplodedNode *)> Stop) {
  2576. const ExplodedNode *FirstHiddenNode = N;
  2577. while (FirstHiddenNode->pred_size() == 1 &&
  2578. isNodeHidden(*FirstHiddenNode->pred_begin())) {
  2579. FirstHiddenNode = *FirstHiddenNode->pred_begin();
  2580. }
  2581. const ExplodedNode *OtherNode = FirstHiddenNode;
  2582. while (true) {
  2583. PreCallback(OtherNode);
  2584. if (Stop(OtherNode))
  2585. return true;
  2586. if (OtherNode == N)
  2587. break;
  2588. PostCallback(OtherNode);
  2589. OtherNode = *OtherNode->succ_begin();
  2590. }
  2591. return false;
  2592. }
  2593. static std::string getNodeAttributes(const ExplodedNode *N,
  2594. ExplodedGraph *) {
  2595. SmallVector<StringRef, 10> Out;
  2596. auto Noop = [](const ExplodedNode*){};
  2597. if (traverseHiddenNodes(N, Noop, Noop, &nodeHasBugReport)) {
  2598. Out.push_back("style=filled");
  2599. Out.push_back("fillcolor=red");
  2600. }
  2601. if (traverseHiddenNodes(N, Noop, Noop,
  2602. [](const ExplodedNode *C) { return C->isSink(); }))
  2603. Out.push_back("color=blue");
  2604. return llvm::join(Out, ",");
  2605. }
  2606. static bool isNodeHidden(const ExplodedNode *N) {
  2607. return N->isTrivial();
  2608. }
  2609. static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
  2610. std::string sbuf;
  2611. llvm::raw_string_ostream Out(sbuf);
  2612. ProgramStateRef State = N->getState();
  2613. // Dump program point for all the previously skipped nodes.
  2614. traverseHiddenNodes(
  2615. N,
  2616. [&](const ExplodedNode *OtherNode) {
  2617. OtherNode->getLocation().print(/*CR=*/"\\l", Out);
  2618. if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
  2619. Out << "\\lTag:" << Tag->getTagDescription();
  2620. if (N->isSink())
  2621. Out << "\\lNode is sink\\l";
  2622. if (nodeHasBugReport(N))
  2623. Out << "\\lBug report attached\\l";
  2624. },
  2625. [&](const ExplodedNode *) { Out << "\\l--------\\l"; },
  2626. [&](const ExplodedNode *) { return false; });
  2627. Out << "\\l\\|";
  2628. Out << "StateID: ST" << State->getID() << ", NodeID: N" << N->getID(G)
  2629. << " <" << (const void *)N << ">\\|";
  2630. bool SameAsAllPredecessors =
  2631. std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
  2632. return P->getState() == State;
  2633. });
  2634. if (!SameAsAllPredecessors)
  2635. State->printDOT(Out, N->getLocationContext());
  2636. return Out.str();
  2637. }
  2638. };
  2639. } // namespace llvm
  2640. #endif
  2641. void ExprEngine::ViewGraph(bool trim) {
  2642. #ifndef NDEBUG
  2643. std::string Filename = DumpGraph(trim);
  2644. llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
  2645. #endif
  2646. llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
  2647. }
  2648. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2649. #ifndef NDEBUG
  2650. std::string Filename = DumpGraph(Nodes);
  2651. llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
  2652. #endif
  2653. llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
  2654. }
  2655. std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
  2656. #ifndef NDEBUG
  2657. if (trim) {
  2658. std::vector<const ExplodedNode *> Src;
  2659. // Iterate through the reports and get their nodes.
  2660. for (BugReporter::EQClasses_iterator
  2661. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2662. const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
  2663. if (N) Src.push_back(N);
  2664. }
  2665. return DumpGraph(Src, Filename);
  2666. } else {
  2667. return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
  2668. /*Title=*/"Exploded Graph", /*Filename=*/Filename);
  2669. }
  2670. #endif
  2671. llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
  2672. return "";
  2673. }
  2674. std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes,
  2675. StringRef Filename) {
  2676. #ifndef NDEBUG
  2677. std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2678. if (!TrimmedG.get()) {
  2679. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2680. } else {
  2681. return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
  2682. /*ShortNames=*/false,
  2683. /*Title=*/"Trimmed Exploded Graph",
  2684. /*Filename=*/Filename);
  2685. }
  2686. #endif
  2687. llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
  2688. return "";
  2689. }
  2690. void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() {
  2691. static int index = 0;
  2692. return &index;
  2693. }