ExprEngine.cpp 101 KB

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