ExprEngine.cpp 114 KB

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