ExprEngine.cpp 102 KB

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