ExprEngine.cpp 116 KB

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