ExprEngine.cpp 103 KB

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