ExprEngine.cpp 124 KB

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