ExprEngine.cpp 117 KB

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