ExprEngine.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  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. #define DEBUG_TYPE "ExprEngine"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  21. #include "clang/AST/CharUnits.h"
  22. #include "clang/AST/ParentMap.h"
  23. #include "clang/AST/StmtObjC.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/PrettyStackTrace.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/ADT/ImmutableList.h"
  31. #include "llvm/ADT/Statistic.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. STATISTIC(NumRemoveDeadBindings,
  39. "The # of times RemoveDeadBindings is called");
  40. STATISTIC(NumMaxBlockCountReached,
  41. "The # of aborted paths due to reaching the maximum block count in "
  42. "a top level function");
  43. STATISTIC(NumMaxBlockCountReachedInInlined,
  44. "The # of aborted paths due to reaching the maximum block count in "
  45. "an inlined function");
  46. STATISTIC(NumTimesRetriedWithoutInlining,
  47. "The # of times we re-evaluated a call without inlining");
  48. //===----------------------------------------------------------------------===//
  49. // Engine construction and deletion.
  50. //===----------------------------------------------------------------------===//
  51. ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
  52. SetOfConstDecls *VisitedCallees,
  53. FunctionSummariesTy *FS)
  54. : AMgr(mgr),
  55. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  56. Engine(*this, VisitedCallees, FS),
  57. G(Engine.getGraph()),
  58. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  59. mgr.getConstraintManagerCreator(), G.getAllocator(),
  60. *this),
  61. SymMgr(StateMgr.getSymbolManager()),
  62. svalBuilder(StateMgr.getSValBuilder()),
  63. EntryNode(NULL),
  64. currentStmt(NULL), currentStmtIdx(0), currentBuilderContext(0),
  65. NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
  66. RaiseSel(GetNullarySelector("raise", getContext())),
  67. ObjCGCEnabled(gcEnabled), BR(mgr, *this) {
  68. if (mgr.shouldEagerlyTrimExplodedGraph()) {
  69. // Enable eager node reclaimation when constructing the ExplodedGraph.
  70. G.enableNodeReclamation();
  71. }
  72. }
  73. ExprEngine::~ExprEngine() {
  74. BR.FlushReports();
  75. delete [] NSExceptionInstanceRaiseSelectors;
  76. }
  77. //===----------------------------------------------------------------------===//
  78. // Utility methods.
  79. //===----------------------------------------------------------------------===//
  80. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  81. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  82. const Decl *D = InitLoc->getDecl();
  83. // Preconditions.
  84. // FIXME: It would be nice if we had a more general mechanism to add
  85. // such preconditions. Some day.
  86. do {
  87. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  88. // Precondition: the first argument of 'main' is an integer guaranteed
  89. // to be > 0.
  90. const IdentifierInfo *II = FD->getIdentifier();
  91. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  92. break;
  93. const ParmVarDecl *PD = FD->getParamDecl(0);
  94. QualType T = PD->getType();
  95. if (!T->isIntegerType())
  96. break;
  97. const MemRegion *R = state->getRegion(PD, InitLoc);
  98. if (!R)
  99. break;
  100. SVal V = state->getSVal(loc::MemRegionVal(R));
  101. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  102. svalBuilder.makeZeroVal(T),
  103. getContext().IntTy);
  104. DefinedOrUnknownSVal *Constraint =
  105. dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
  106. if (!Constraint)
  107. break;
  108. if (ProgramStateRef newState = state->assume(*Constraint, true))
  109. state = newState;
  110. }
  111. break;
  112. }
  113. while (0);
  114. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  115. // Precondition: 'self' is always non-null upon entry to an Objective-C
  116. // method.
  117. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  118. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  119. SVal V = state->getSVal(loc::MemRegionVal(R));
  120. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  121. // Assume that the pointer value in 'self' is non-null.
  122. state = state->assume(*LV, true);
  123. assert(state && "'self' cannot be null");
  124. }
  125. }
  126. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  127. if (!MD->isStatic()) {
  128. // Precondition: 'this' is always non-null upon entry to the
  129. // top-level function. This is our starting assumption for
  130. // analyzing an "open" program.
  131. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  132. if (SFC->getParent() == 0) {
  133. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  134. SVal V = state->getSVal(L);
  135. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  136. state = state->assume(*LV, true);
  137. assert(state && "'this' cannot be null");
  138. }
  139. }
  140. }
  141. }
  142. return state;
  143. }
  144. //===----------------------------------------------------------------------===//
  145. // Top-level transfer function logic (Dispatcher).
  146. //===----------------------------------------------------------------------===//
  147. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  148. /// logic for handling assumptions on symbolic values.
  149. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  150. SVal cond, bool assumption) {
  151. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  152. }
  153. bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
  154. return getCheckerManager().wantsRegionChangeUpdate(state);
  155. }
  156. ProgramStateRef
  157. ExprEngine::processRegionChanges(ProgramStateRef state,
  158. const StoreManager::InvalidatedSymbols *invalidated,
  159. ArrayRef<const MemRegion *> Explicits,
  160. ArrayRef<const MemRegion *> Regions,
  161. const CallEvent *Call) {
  162. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  163. Explicits, Regions, Call);
  164. }
  165. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  166. const char *NL, const char *Sep) {
  167. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  168. }
  169. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  170. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  171. }
  172. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  173. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  174. currentStmtIdx = StmtIdx;
  175. currentBuilderContext = Ctx;
  176. switch (E.getKind()) {
  177. case CFGElement::Invalid:
  178. llvm_unreachable("Unexpected CFGElement kind.");
  179. case CFGElement::Statement:
  180. ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred);
  181. return;
  182. case CFGElement::Initializer:
  183. ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred);
  184. return;
  185. case CFGElement::AutomaticObjectDtor:
  186. case CFGElement::BaseDtor:
  187. case CFGElement::MemberDtor:
  188. case CFGElement::TemporaryDtor:
  189. ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred);
  190. return;
  191. }
  192. currentBuilderContext = 0;
  193. }
  194. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  195. const CFGStmt S,
  196. const ExplodedNode *Pred,
  197. const LocationContext *LC) {
  198. // Are we never purging state values?
  199. if (AMgr.getPurgeMode() == PurgeNone)
  200. return false;
  201. // Is this the beginning of a basic block?
  202. if (isa<BlockEntrance>(Pred->getLocation()))
  203. return true;
  204. // Is this on a non-expression?
  205. if (!isa<Expr>(S.getStmt()))
  206. return true;
  207. // Run before processing a call.
  208. if (CallEvent::mayBeInlined(S.getStmt()))
  209. return true;
  210. // Is this an expression that is consumed by another expression? If so,
  211. // postpone cleaning out the state.
  212. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  213. return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
  214. }
  215. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  216. const Stmt *ReferenceStmt,
  217. const LocationContext *LC,
  218. const Stmt *DiagnosticStmt,
  219. ProgramPoint::Kind K) {
  220. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  221. ReferenceStmt == 0) && "PreStmt is not generally supported by "
  222. "the SymbolReaper yet");
  223. NumRemoveDeadBindings++;
  224. CleanedState = Pred->getState();
  225. SymbolReaper SymReaper(LC, ReferenceStmt, SymMgr, getStoreManager());
  226. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  227. // Create a state in which dead bindings are removed from the environment
  228. // and the store. TODO: The function should just return new env and store,
  229. // not a new state.
  230. const StackFrameContext *SFC = LC->getCurrentStackFrame();
  231. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  232. // Process any special transfer function for dead symbols.
  233. // A tag to track convenience transitions, which can be removed at cleanup.
  234. static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
  235. if (!SymReaper.hasDeadSymbols()) {
  236. // Generate a CleanedNode that has the environment and store cleaned
  237. // up. Since no symbols are dead, we can optimize and not clean out
  238. // the constraint manager.
  239. StmtNodeBuilder Bldr(Pred, Out, *currentBuilderContext);
  240. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, false, &cleanupTag,K);
  241. } else {
  242. // Call checkers with the non-cleaned state so that they could query the
  243. // values of the soon to be dead symbols.
  244. ExplodedNodeSet CheckedSet;
  245. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  246. DiagnosticStmt, *this, K);
  247. // For each node in CheckedSet, generate CleanedNodes that have the
  248. // environment, the store, and the constraints cleaned up but have the
  249. // user-supplied states as the predecessors.
  250. StmtNodeBuilder Bldr(CheckedSet, Out, *currentBuilderContext);
  251. for (ExplodedNodeSet::const_iterator
  252. I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
  253. ProgramStateRef CheckerState = (*I)->getState();
  254. // The constraint manager has not been cleaned up yet, so clean up now.
  255. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  256. SymReaper);
  257. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  258. "Checkers are not allowed to modify the Environment as a part of "
  259. "checkDeadSymbols processing.");
  260. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  261. "Checkers are not allowed to modify the Store as a part of "
  262. "checkDeadSymbols processing.");
  263. // Create a state based on CleanedState with CheckerState GDM and
  264. // generate a transition to that state.
  265. ProgramStateRef CleanedCheckerSt =
  266. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  267. Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, false,
  268. &cleanupTag, K);
  269. }
  270. }
  271. }
  272. void ExprEngine::ProcessStmt(const CFGStmt S,
  273. ExplodedNode *Pred) {
  274. // Reclaim any unnecessary nodes in the ExplodedGraph.
  275. G.reclaimRecentlyAllocatedNodes();
  276. currentStmt = S.getStmt();
  277. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  278. currentStmt->getLocStart(),
  279. "Error evaluating statement");
  280. // Remove dead bindings and symbols.
  281. EntryNode = Pred;
  282. ExplodedNodeSet CleanedStates;
  283. if (shouldRemoveDeadBindings(AMgr, S, Pred, EntryNode->getLocationContext())){
  284. removeDead(EntryNode, CleanedStates, currentStmt,
  285. Pred->getLocationContext(), currentStmt);
  286. } else
  287. CleanedStates.Add(EntryNode);
  288. // Visit the statement.
  289. ExplodedNodeSet Dst;
  290. for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
  291. E = CleanedStates.end(); I != E; ++I) {
  292. ExplodedNodeSet DstI;
  293. // Visit the statement.
  294. Visit(currentStmt, *I, DstI);
  295. Dst.insert(DstI);
  296. }
  297. // Enqueue the new nodes onto the work list.
  298. Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
  299. // NULL out these variables to cleanup.
  300. CleanedState = NULL;
  301. EntryNode = NULL;
  302. currentStmt = 0;
  303. }
  304. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  305. ExplodedNode *Pred) {
  306. ExplodedNodeSet Dst;
  307. // We don't set EntryNode and currentStmt. And we don't clean up state.
  308. const CXXCtorInitializer *BMI = Init.getInitializer();
  309. const StackFrameContext *stackFrame =
  310. cast<StackFrameContext>(Pred->getLocationContext());
  311. const CXXConstructorDecl *decl =
  312. cast<CXXConstructorDecl>(stackFrame->getDecl());
  313. SVal thisVal = Pred->getState()->getSVal(svalBuilder.getCXXThis(decl,
  314. stackFrame));
  315. if (BMI->isAnyMemberInitializer()) {
  316. // Evaluate the initializer.
  317. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  318. ProgramStateRef state = Pred->getState();
  319. const FieldDecl *FD = BMI->getAnyMember();
  320. SVal FieldLoc = state->getLValue(FD, thisVal);
  321. SVal InitVal = state->getSVal(BMI->getInit(), Pred->getLocationContext());
  322. state = state->bindLoc(FieldLoc, InitVal);
  323. // Use a custom node building process.
  324. PostInitializer PP(BMI, stackFrame);
  325. // Builder automatically add the generated node to the deferred set,
  326. // which are processed in the builder's dtor.
  327. Bldr.generateNode(PP, Pred, state);
  328. } else {
  329. assert(BMI->isBaseInitializer());
  330. // Get the base class declaration.
  331. const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
  332. // Create the base object region.
  333. SVal baseVal =
  334. getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
  335. const MemRegion *baseReg = baseVal.getAsRegion();
  336. assert(baseReg);
  337. VisitCXXConstructExpr(ctorExpr, baseReg, Pred, Dst);
  338. }
  339. // Enqueue the new nodes onto the work list.
  340. Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
  341. }
  342. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  343. ExplodedNode *Pred) {
  344. ExplodedNodeSet Dst;
  345. switch (D.getKind()) {
  346. case CFGElement::AutomaticObjectDtor:
  347. ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst);
  348. break;
  349. case CFGElement::BaseDtor:
  350. ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst);
  351. break;
  352. case CFGElement::MemberDtor:
  353. ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst);
  354. break;
  355. case CFGElement::TemporaryDtor:
  356. ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst);
  357. break;
  358. default:
  359. llvm_unreachable("Unexpected dtor kind.");
  360. }
  361. // Enqueue the new nodes onto the work list.
  362. Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
  363. }
  364. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  365. ExplodedNode *Pred,
  366. ExplodedNodeSet &Dst) {
  367. ProgramStateRef state = Pred->getState();
  368. const VarDecl *varDecl = Dtor.getVarDecl();
  369. QualType varType = varDecl->getType();
  370. if (const ReferenceType *refType = varType->getAs<ReferenceType>())
  371. varType = refType->getPointeeType();
  372. const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
  373. assert(recordDecl && "get CXXRecordDecl fail");
  374. const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
  375. Loc dest = state->getLValue(varDecl, Pred->getLocationContext());
  376. VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
  377. Dtor.getTriggerStmt(), Pred, Dst);
  378. }
  379. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  380. ExplodedNode *Pred, ExplodedNodeSet &Dst) {}
  381. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  382. ExplodedNode *Pred, ExplodedNodeSet &Dst) {}
  383. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  384. ExplodedNode *Pred,
  385. ExplodedNodeSet &Dst) {}
  386. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  387. ExplodedNodeSet &DstTop) {
  388. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  389. S->getLocStart(),
  390. "Error evaluating statement");
  391. ExplodedNodeSet Dst;
  392. StmtNodeBuilder Bldr(Pred, DstTop, *currentBuilderContext);
  393. // Expressions to ignore.
  394. if (const Expr *Ex = dyn_cast<Expr>(S))
  395. S = Ex->IgnoreParens();
  396. // FIXME: add metadata to the CFG so that we can disable
  397. // this check when we KNOW that there is no block-level subexpression.
  398. // The motivation is that this check requires a hashtable lookup.
  399. if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S))
  400. return;
  401. switch (S->getStmtClass()) {
  402. // C++ and ARC stuff we don't support yet.
  403. case Expr::ObjCIndirectCopyRestoreExprClass:
  404. case Stmt::CXXDependentScopeMemberExprClass:
  405. case Stmt::CXXPseudoDestructorExprClass:
  406. case Stmt::CXXTryStmtClass:
  407. case Stmt::CXXTypeidExprClass:
  408. case Stmt::CXXUuidofExprClass:
  409. case Stmt::CXXUnresolvedConstructExprClass:
  410. case Stmt::DependentScopeDeclRefExprClass:
  411. case Stmt::UnaryTypeTraitExprClass:
  412. case Stmt::BinaryTypeTraitExprClass:
  413. case Stmt::TypeTraitExprClass:
  414. case Stmt::ArrayTypeTraitExprClass:
  415. case Stmt::ExpressionTraitExprClass:
  416. case Stmt::UnresolvedLookupExprClass:
  417. case Stmt::UnresolvedMemberExprClass:
  418. case Stmt::CXXNoexceptExprClass:
  419. case Stmt::PackExpansionExprClass:
  420. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  421. case Stmt::SEHTryStmtClass:
  422. case Stmt::SEHExceptStmtClass:
  423. case Stmt::LambdaExprClass:
  424. case Stmt::SEHFinallyStmtClass: {
  425. const ExplodedNode *node = Bldr.generateNode(S, Pred, Pred->getState(),
  426. /* sink */ true);
  427. Engine.addAbortedBlock(node, currentBuilderContext->getBlock());
  428. break;
  429. }
  430. // We don't handle default arguments either yet, but we can fake it
  431. // for now by just skipping them.
  432. case Stmt::SubstNonTypeTemplateParmExprClass:
  433. case Stmt::CXXDefaultArgExprClass:
  434. break;
  435. case Stmt::ParenExprClass:
  436. llvm_unreachable("ParenExprs already handled.");
  437. case Stmt::GenericSelectionExprClass:
  438. llvm_unreachable("GenericSelectionExprs already handled.");
  439. // Cases that should never be evaluated simply because they shouldn't
  440. // appear in the CFG.
  441. case Stmt::BreakStmtClass:
  442. case Stmt::CaseStmtClass:
  443. case Stmt::CompoundStmtClass:
  444. case Stmt::ContinueStmtClass:
  445. case Stmt::CXXForRangeStmtClass:
  446. case Stmt::DefaultStmtClass:
  447. case Stmt::DoStmtClass:
  448. case Stmt::ForStmtClass:
  449. case Stmt::GotoStmtClass:
  450. case Stmt::IfStmtClass:
  451. case Stmt::IndirectGotoStmtClass:
  452. case Stmt::LabelStmtClass:
  453. case Stmt::AttributedStmtClass:
  454. case Stmt::NoStmtClass:
  455. case Stmt::NullStmtClass:
  456. case Stmt::SwitchStmtClass:
  457. case Stmt::WhileStmtClass:
  458. case Expr::MSDependentExistsStmtClass:
  459. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  460. case Stmt::GNUNullExprClass: {
  461. // GNU __null is a pointer-width integer, not an actual pointer.
  462. ProgramStateRef state = Pred->getState();
  463. state = state->BindExpr(S, Pred->getLocationContext(),
  464. svalBuilder.makeIntValWithPtrWidth(0, false));
  465. Bldr.generateNode(S, Pred, state);
  466. break;
  467. }
  468. case Stmt::ObjCAtSynchronizedStmtClass:
  469. Bldr.takeNodes(Pred);
  470. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  471. Bldr.addNodes(Dst);
  472. break;
  473. // FIXME.
  474. case Stmt::ObjCSubscriptRefExprClass:
  475. break;
  476. case Stmt::ObjCPropertyRefExprClass:
  477. // Implicitly handled by Environment::getSVal().
  478. break;
  479. case Stmt::ExprWithCleanupsClass:
  480. // Handled due to fully linearised CFG.
  481. break;
  482. // Cases not handled yet; but will handle some day.
  483. case Stmt::DesignatedInitExprClass:
  484. case Stmt::ExtVectorElementExprClass:
  485. case Stmt::ImaginaryLiteralClass:
  486. case Stmt::ObjCAtCatchStmtClass:
  487. case Stmt::ObjCAtFinallyStmtClass:
  488. case Stmt::ObjCAtTryStmtClass:
  489. case Stmt::ObjCAutoreleasePoolStmtClass:
  490. case Stmt::ObjCEncodeExprClass:
  491. case Stmt::ObjCIsaExprClass:
  492. case Stmt::ObjCProtocolExprClass:
  493. case Stmt::ObjCSelectorExprClass:
  494. case Stmt::ParenListExprClass:
  495. case Stmt::PredefinedExprClass:
  496. case Stmt::ShuffleVectorExprClass:
  497. case Stmt::VAArgExprClass:
  498. case Stmt::CUDAKernelCallExprClass:
  499. case Stmt::OpaqueValueExprClass:
  500. case Stmt::AsTypeExprClass:
  501. case Stmt::AtomicExprClass:
  502. // Fall through.
  503. // Currently all handling of 'throw' just falls to the CFG. We
  504. // can consider doing more if necessary.
  505. case Stmt::CXXThrowExprClass:
  506. // Fall through.
  507. // Cases we intentionally don't evaluate, since they don't need
  508. // to be explicitly evaluated.
  509. case Stmt::AddrLabelExprClass:
  510. case Stmt::IntegerLiteralClass:
  511. case Stmt::CharacterLiteralClass:
  512. case Stmt::ImplicitValueInitExprClass:
  513. case Stmt::CXXScalarValueInitExprClass:
  514. case Stmt::CXXBoolLiteralExprClass:
  515. case Stmt::ObjCBoolLiteralExprClass:
  516. case Stmt::FloatingLiteralClass:
  517. case Stmt::SizeOfPackExprClass:
  518. case Stmt::StringLiteralClass:
  519. case Stmt::ObjCStringLiteralClass:
  520. case Stmt::CXXBindTemporaryExprClass:
  521. case Stmt::CXXNullPtrLiteralExprClass: {
  522. Bldr.takeNodes(Pred);
  523. ExplodedNodeSet preVisit;
  524. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  525. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  526. Bldr.addNodes(Dst);
  527. break;
  528. }
  529. case Expr::ObjCArrayLiteralClass:
  530. case Expr::ObjCDictionaryLiteralClass:
  531. // FIXME: explicitly model with a region and the actual contents
  532. // of the container. For now, conjure a symbol.
  533. case Expr::ObjCBoxedExprClass: {
  534. Bldr.takeNodes(Pred);
  535. ExplodedNodeSet preVisit;
  536. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  537. ExplodedNodeSet Tmp;
  538. StmtNodeBuilder Bldr2(preVisit, Tmp, *currentBuilderContext);
  539. const Expr *Ex = cast<Expr>(S);
  540. QualType resultType = Ex->getType();
  541. for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
  542. it != et; ++it) {
  543. ExplodedNode *N = *it;
  544. const LocationContext *LCtx = N->getLocationContext();
  545. SVal result =
  546. svalBuilder.getConjuredSymbolVal(0, Ex, LCtx, resultType,
  547. currentBuilderContext->getCurrentBlockCount());
  548. ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
  549. Bldr2.generateNode(S, N, state);
  550. }
  551. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  552. Bldr.addNodes(Dst);
  553. break;
  554. }
  555. case Stmt::ArraySubscriptExprClass:
  556. Bldr.takeNodes(Pred);
  557. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  558. Bldr.addNodes(Dst);
  559. break;
  560. case Stmt::AsmStmtClass:
  561. Bldr.takeNodes(Pred);
  562. VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
  563. Bldr.addNodes(Dst);
  564. break;
  565. case Stmt::MSAsmStmtClass:
  566. Bldr.takeNodes(Pred);
  567. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  568. Bldr.addNodes(Dst);
  569. break;
  570. case Stmt::BlockExprClass:
  571. Bldr.takeNodes(Pred);
  572. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  573. Bldr.addNodes(Dst);
  574. break;
  575. case Stmt::BinaryOperatorClass: {
  576. const BinaryOperator* B = cast<BinaryOperator>(S);
  577. if (B->isLogicalOp()) {
  578. Bldr.takeNodes(Pred);
  579. VisitLogicalExpr(B, Pred, Dst);
  580. Bldr.addNodes(Dst);
  581. break;
  582. }
  583. else if (B->getOpcode() == BO_Comma) {
  584. ProgramStateRef state = Pred->getState();
  585. Bldr.generateNode(B, Pred,
  586. state->BindExpr(B, Pred->getLocationContext(),
  587. state->getSVal(B->getRHS(),
  588. Pred->getLocationContext())));
  589. break;
  590. }
  591. Bldr.takeNodes(Pred);
  592. if (AMgr.shouldEagerlyAssume() &&
  593. (B->isRelationalOp() || B->isEqualityOp())) {
  594. ExplodedNodeSet Tmp;
  595. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  596. evalEagerlyAssume(Dst, Tmp, cast<Expr>(S));
  597. }
  598. else
  599. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  600. Bldr.addNodes(Dst);
  601. break;
  602. }
  603. case Stmt::CallExprClass:
  604. case Stmt::CXXOperatorCallExprClass:
  605. case Stmt::CXXMemberCallExprClass:
  606. case Stmt::UserDefinedLiteralClass: {
  607. Bldr.takeNodes(Pred);
  608. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  609. Bldr.addNodes(Dst);
  610. break;
  611. }
  612. case Stmt::CXXCatchStmtClass: {
  613. Bldr.takeNodes(Pred);
  614. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  615. Bldr.addNodes(Dst);
  616. break;
  617. }
  618. case Stmt::CXXTemporaryObjectExprClass:
  619. case Stmt::CXXConstructExprClass: {
  620. const CXXConstructExpr *C = cast<CXXConstructExpr>(S);
  621. // For block-level CXXConstructExpr, we don't have a destination region.
  622. // Let VisitCXXConstructExpr() create one.
  623. Bldr.takeNodes(Pred);
  624. VisitCXXConstructExpr(C, 0, Pred, Dst);
  625. Bldr.addNodes(Dst);
  626. break;
  627. }
  628. case Stmt::CXXNewExprClass: {
  629. Bldr.takeNodes(Pred);
  630. const CXXNewExpr *NE = cast<CXXNewExpr>(S);
  631. VisitCXXNewExpr(NE, Pred, Dst);
  632. Bldr.addNodes(Dst);
  633. break;
  634. }
  635. case Stmt::CXXDeleteExprClass: {
  636. Bldr.takeNodes(Pred);
  637. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  638. VisitCXXDeleteExpr(CDE, Pred, Dst);
  639. Bldr.addNodes(Dst);
  640. break;
  641. }
  642. // FIXME: ChooseExpr is really a constant. We need to fix
  643. // the CFG do not model them as explicit control-flow.
  644. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  645. Bldr.takeNodes(Pred);
  646. const ChooseExpr *C = cast<ChooseExpr>(S);
  647. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  648. Bldr.addNodes(Dst);
  649. break;
  650. }
  651. case Stmt::CompoundAssignOperatorClass:
  652. Bldr.takeNodes(Pred);
  653. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  654. Bldr.addNodes(Dst);
  655. break;
  656. case Stmt::CompoundLiteralExprClass:
  657. Bldr.takeNodes(Pred);
  658. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  659. Bldr.addNodes(Dst);
  660. break;
  661. case Stmt::BinaryConditionalOperatorClass:
  662. case Stmt::ConditionalOperatorClass: { // '?' operator
  663. Bldr.takeNodes(Pred);
  664. const AbstractConditionalOperator *C
  665. = cast<AbstractConditionalOperator>(S);
  666. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  667. Bldr.addNodes(Dst);
  668. break;
  669. }
  670. case Stmt::CXXThisExprClass:
  671. Bldr.takeNodes(Pred);
  672. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  673. Bldr.addNodes(Dst);
  674. break;
  675. case Stmt::DeclRefExprClass: {
  676. Bldr.takeNodes(Pred);
  677. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  678. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  679. Bldr.addNodes(Dst);
  680. break;
  681. }
  682. case Stmt::DeclStmtClass:
  683. Bldr.takeNodes(Pred);
  684. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  685. Bldr.addNodes(Dst);
  686. break;
  687. case Stmt::ImplicitCastExprClass:
  688. case Stmt::CStyleCastExprClass:
  689. case Stmt::CXXStaticCastExprClass:
  690. case Stmt::CXXDynamicCastExprClass:
  691. case Stmt::CXXReinterpretCastExprClass:
  692. case Stmt::CXXConstCastExprClass:
  693. case Stmt::CXXFunctionalCastExprClass:
  694. case Stmt::ObjCBridgedCastExprClass: {
  695. Bldr.takeNodes(Pred);
  696. const CastExpr *C = cast<CastExpr>(S);
  697. // Handle the previsit checks.
  698. ExplodedNodeSet dstPrevisit;
  699. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
  700. // Handle the expression itself.
  701. ExplodedNodeSet dstExpr;
  702. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  703. e = dstPrevisit.end(); i != e ; ++i) {
  704. VisitCast(C, C->getSubExpr(), *i, dstExpr);
  705. }
  706. // Handle the postvisit checks.
  707. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  708. Bldr.addNodes(Dst);
  709. break;
  710. }
  711. case Expr::MaterializeTemporaryExprClass: {
  712. Bldr.takeNodes(Pred);
  713. const MaterializeTemporaryExpr *Materialize
  714. = cast<MaterializeTemporaryExpr>(S);
  715. if (Materialize->getType()->isRecordType())
  716. Dst.Add(Pred);
  717. else
  718. CreateCXXTemporaryObject(Materialize, Pred, Dst);
  719. Bldr.addNodes(Dst);
  720. break;
  721. }
  722. case Stmt::InitListExprClass:
  723. Bldr.takeNodes(Pred);
  724. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  725. Bldr.addNodes(Dst);
  726. break;
  727. case Stmt::MemberExprClass:
  728. Bldr.takeNodes(Pred);
  729. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  730. Bldr.addNodes(Dst);
  731. break;
  732. case Stmt::ObjCIvarRefExprClass:
  733. Bldr.takeNodes(Pred);
  734. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  735. Bldr.addNodes(Dst);
  736. break;
  737. case Stmt::ObjCForCollectionStmtClass:
  738. Bldr.takeNodes(Pred);
  739. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  740. Bldr.addNodes(Dst);
  741. break;
  742. case Stmt::ObjCMessageExprClass: {
  743. Bldr.takeNodes(Pred);
  744. // Is this a property access?
  745. const LocationContext *LCtx = Pred->getLocationContext();
  746. const ParentMap &PM = LCtx->getParentMap();
  747. const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(S);
  748. bool evaluated = false;
  749. if (const PseudoObjectExpr *PO =
  750. dyn_cast_or_null<PseudoObjectExpr>(PM.getParent(S))) {
  751. const Expr *syntactic = PO->getSyntacticForm();
  752. // This handles the funny case of assigning to the result of a getter.
  753. // This can happen if the getter returns a non-const reference.
  754. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(syntactic))
  755. syntactic = BO->getLHS();
  756. if (const ObjCPropertyRefExpr *PR =
  757. dyn_cast<ObjCPropertyRefExpr>(syntactic)) {
  758. VisitObjCMessage(ObjCPropertyAccess(PR, PO->getSourceRange(), ME,
  759. Pred->getState(), LCtx),
  760. Pred, Dst);
  761. evaluated = true;
  762. }
  763. }
  764. if (!evaluated)
  765. VisitObjCMessage(ObjCMessageSend(ME, Pred->getState(), LCtx),
  766. Pred, Dst);
  767. Bldr.addNodes(Dst);
  768. break;
  769. }
  770. case Stmt::ObjCAtThrowStmtClass: {
  771. // FIXME: This is not complete. We basically treat @throw as
  772. // an abort.
  773. Bldr.generateNode(S, Pred, Pred->getState());
  774. break;
  775. }
  776. case Stmt::ReturnStmtClass:
  777. Bldr.takeNodes(Pred);
  778. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  779. Bldr.addNodes(Dst);
  780. break;
  781. case Stmt::OffsetOfExprClass:
  782. Bldr.takeNodes(Pred);
  783. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  784. Bldr.addNodes(Dst);
  785. break;
  786. case Stmt::UnaryExprOrTypeTraitExprClass:
  787. Bldr.takeNodes(Pred);
  788. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  789. Pred, Dst);
  790. Bldr.addNodes(Dst);
  791. break;
  792. case Stmt::StmtExprClass: {
  793. const StmtExpr *SE = cast<StmtExpr>(S);
  794. if (SE->getSubStmt()->body_empty()) {
  795. // Empty statement expression.
  796. assert(SE->getType() == getContext().VoidTy
  797. && "Empty statement expression must have void type.");
  798. break;
  799. }
  800. if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  801. ProgramStateRef state = Pred->getState();
  802. Bldr.generateNode(SE, Pred,
  803. state->BindExpr(SE, Pred->getLocationContext(),
  804. state->getSVal(LastExpr,
  805. Pred->getLocationContext())));
  806. }
  807. break;
  808. }
  809. case Stmt::UnaryOperatorClass: {
  810. Bldr.takeNodes(Pred);
  811. const UnaryOperator *U = cast<UnaryOperator>(S);
  812. if (AMgr.shouldEagerlyAssume() && (U->getOpcode() == UO_LNot)) {
  813. ExplodedNodeSet Tmp;
  814. VisitUnaryOperator(U, Pred, Tmp);
  815. evalEagerlyAssume(Dst, Tmp, U);
  816. }
  817. else
  818. VisitUnaryOperator(U, Pred, Dst);
  819. Bldr.addNodes(Dst);
  820. break;
  821. }
  822. case Stmt::PseudoObjectExprClass: {
  823. Bldr.takeNodes(Pred);
  824. ProgramStateRef state = Pred->getState();
  825. const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
  826. if (const Expr *Result = PE->getResultExpr()) {
  827. SVal V = state->getSVal(Result, Pred->getLocationContext());
  828. Bldr.generateNode(S, Pred,
  829. state->BindExpr(S, Pred->getLocationContext(), V));
  830. }
  831. else
  832. Bldr.generateNode(S, Pred,
  833. state->BindExpr(S, Pred->getLocationContext(),
  834. UnknownVal()));
  835. Bldr.addNodes(Dst);
  836. break;
  837. }
  838. }
  839. }
  840. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  841. const LocationContext *CalleeLC) {
  842. const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  843. const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
  844. assert(CalleeSF && CallerSF);
  845. ExplodedNode *BeforeProcessingCall = 0;
  846. const Stmt *CE = CalleeSF->getCallSite();
  847. // Find the first node before we started processing the call expression.
  848. while (N) {
  849. ProgramPoint L = N->getLocation();
  850. BeforeProcessingCall = N;
  851. N = N->pred_empty() ? NULL : *(N->pred_begin());
  852. // Skip the nodes corresponding to the inlined code.
  853. if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
  854. continue;
  855. // We reached the caller. Find the node right before we started
  856. // processing the call.
  857. if (L.isPurgeKind())
  858. continue;
  859. if (isa<PreImplicitCall>(&L))
  860. continue;
  861. if (isa<CallEnter>(&L))
  862. continue;
  863. if (const StmtPoint *SP = dyn_cast<StmtPoint>(&L))
  864. if (SP->getStmt() == CE)
  865. continue;
  866. break;
  867. }
  868. if (!BeforeProcessingCall)
  869. return false;
  870. // TODO: Clean up the unneeded nodes.
  871. // Build an Epsilon node from which we will restart the analyzes.
  872. // Note that CE is permitted to be NULL!
  873. ProgramPoint NewNodeLoc =
  874. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  875. // Add the special flag to GDM to signal retrying with no inlining.
  876. // Note, changing the state ensures that we are not going to cache out.
  877. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  878. NewNodeState = NewNodeState->set<ReplayWithoutInlining>((void*)CE);
  879. // Make the new node a successor of BeforeProcessingCall.
  880. bool IsNew = false;
  881. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  882. // We cached out at this point. Caching out is common due to us backtracking
  883. // from the inlined function, which might spawn several paths.
  884. if (!IsNew)
  885. return true;
  886. NewNode->addPredecessor(BeforeProcessingCall, G);
  887. // Add the new node to the work list.
  888. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  889. CalleeSF->getIndex());
  890. NumTimesRetriedWithoutInlining++;
  891. return true;
  892. }
  893. /// Block entrance. (Update counters).
  894. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  895. NodeBuilderWithSinks &nodeBuilder) {
  896. // FIXME: Refactor this into a checker.
  897. ExplodedNode *pred = nodeBuilder.getContext().getPred();
  898. if (nodeBuilder.getContext().getCurrentBlockCount() >= AMgr.getMaxVisit()) {
  899. static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
  900. const ExplodedNode *Sink =
  901. nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
  902. // Check if we stopped at the top level function or not.
  903. // Root node should have the location context of the top most function.
  904. const LocationContext *CalleeLC = pred->getLocation().getLocationContext();
  905. const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  906. const LocationContext *RootLC =
  907. (*G.roots_begin())->getLocation().getLocationContext();
  908. if (RootLC->getCurrentStackFrame() != CalleeSF) {
  909. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  910. // Re-run the call evaluation without inlining it, by storing the
  911. // no-inlining policy in the state and enqueuing the new work item on
  912. // the list. Replay should almost never fail. Use the stats to catch it
  913. // if it does.
  914. if ((!AMgr.NoRetryExhausted && replayWithoutInlining(pred, CalleeLC)))
  915. return;
  916. NumMaxBlockCountReachedInInlined++;
  917. } else
  918. NumMaxBlockCountReached++;
  919. // Make sink nodes as exhausted(for stats) only if retry failed.
  920. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  921. }
  922. }
  923. //===----------------------------------------------------------------------===//
  924. // Branch processing.
  925. //===----------------------------------------------------------------------===//
  926. ProgramStateRef ExprEngine::MarkBranch(ProgramStateRef state,
  927. const Stmt *Terminator,
  928. const LocationContext *LCtx,
  929. bool branchTaken) {
  930. switch (Terminator->getStmtClass()) {
  931. default:
  932. return state;
  933. case Stmt::BinaryOperatorClass: { // '&&' and '||'
  934. const BinaryOperator* B = cast<BinaryOperator>(Terminator);
  935. BinaryOperator::Opcode Op = B->getOpcode();
  936. assert (Op == BO_LAnd || Op == BO_LOr);
  937. // For &&, if we take the true branch, then the value of the whole
  938. // expression is that of the RHS expression.
  939. //
  940. // For ||, if we take the false branch, then the value of the whole
  941. // expression is that of the RHS expression.
  942. const Expr *Ex = (Op == BO_LAnd && branchTaken) ||
  943. (Op == BO_LOr && !branchTaken)
  944. ? B->getRHS() : B->getLHS();
  945. return state->BindExpr(B, LCtx, UndefinedVal(Ex));
  946. }
  947. case Stmt::BinaryConditionalOperatorClass:
  948. case Stmt::ConditionalOperatorClass: { // ?:
  949. const AbstractConditionalOperator* C
  950. = cast<AbstractConditionalOperator>(Terminator);
  951. // For ?, if branchTaken == true then the value is either the LHS or
  952. // the condition itself. (GNU extension).
  953. const Expr *Ex;
  954. if (branchTaken)
  955. Ex = C->getTrueExpr();
  956. else
  957. Ex = C->getFalseExpr();
  958. return state->BindExpr(C, LCtx, UndefinedVal(Ex));
  959. }
  960. case Stmt::ChooseExprClass: { // ?:
  961. const ChooseExpr *C = cast<ChooseExpr>(Terminator);
  962. const Expr *Ex = branchTaken ? C->getLHS() : C->getRHS();
  963. return state->BindExpr(C, LCtx, UndefinedVal(Ex));
  964. }
  965. }
  966. }
  967. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  968. /// to try to recover some path-sensitivity for casts of symbolic
  969. /// integers that promote their values (which are currently not tracked well).
  970. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  971. // cast(s) did was sign-extend the original value.
  972. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  973. ProgramStateRef state,
  974. const Stmt *Condition,
  975. const LocationContext *LCtx,
  976. ASTContext &Ctx) {
  977. const Expr *Ex = dyn_cast<Expr>(Condition);
  978. if (!Ex)
  979. return UnknownVal();
  980. uint64_t bits = 0;
  981. bool bitsInit = false;
  982. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  983. QualType T = CE->getType();
  984. if (!T->isIntegerType())
  985. return UnknownVal();
  986. uint64_t newBits = Ctx.getTypeSize(T);
  987. if (!bitsInit || newBits < bits) {
  988. bitsInit = true;
  989. bits = newBits;
  990. }
  991. Ex = CE->getSubExpr();
  992. }
  993. // We reached a non-cast. Is it a symbolic value?
  994. QualType T = Ex->getType();
  995. if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
  996. return UnknownVal();
  997. return state->getSVal(Ex, LCtx);
  998. }
  999. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1000. NodeBuilderContext& BldCtx,
  1001. ExplodedNode *Pred,
  1002. ExplodedNodeSet &Dst,
  1003. const CFGBlock *DstT,
  1004. const CFGBlock *DstF) {
  1005. currentBuilderContext = &BldCtx;
  1006. // Check for NULL conditions; e.g. "for(;;)"
  1007. if (!Condition) {
  1008. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1009. NullCondBldr.markInfeasible(false);
  1010. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1011. return;
  1012. }
  1013. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1014. Condition->getLocStart(),
  1015. "Error evaluating branch");
  1016. ExplodedNodeSet CheckersOutSet;
  1017. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1018. Pred, *this);
  1019. // We generated only sinks.
  1020. if (CheckersOutSet.empty())
  1021. return;
  1022. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1023. for (NodeBuilder::iterator I = CheckersOutSet.begin(),
  1024. E = CheckersOutSet.end(); E != I; ++I) {
  1025. ExplodedNode *PredI = *I;
  1026. if (PredI->isSink())
  1027. continue;
  1028. ProgramStateRef PrevState = Pred->getState();
  1029. SVal X = PrevState->getSVal(Condition, Pred->getLocationContext());
  1030. if (X.isUnknownOrUndef()) {
  1031. // Give it a chance to recover from unknown.
  1032. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  1033. if (Ex->getType()->isIntegerType()) {
  1034. // Try to recover some path-sensitivity. Right now casts of symbolic
  1035. // integers that promote their values are currently not tracked well.
  1036. // If 'Condition' is such an expression, try and recover the
  1037. // underlying value and use that instead.
  1038. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1039. PrevState, Condition,
  1040. Pred->getLocationContext(),
  1041. getContext());
  1042. if (!recovered.isUnknown()) {
  1043. X = recovered;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. const LocationContext *LCtx = PredI->getLocationContext();
  1049. // If the condition is still unknown, give up.
  1050. if (X.isUnknownOrUndef()) {
  1051. builder.generateNode(MarkBranch(PrevState, Term, LCtx, true),
  1052. true, PredI);
  1053. builder.generateNode(MarkBranch(PrevState, Term, LCtx, false),
  1054. false, PredI);
  1055. continue;
  1056. }
  1057. DefinedSVal V = cast<DefinedSVal>(X);
  1058. // Process the true branch.
  1059. if (builder.isFeasible(true)) {
  1060. if (ProgramStateRef state = PrevState->assume(V, true))
  1061. builder.generateNode(MarkBranch(state, Term, LCtx, true),
  1062. true, PredI);
  1063. else
  1064. builder.markInfeasible(true);
  1065. }
  1066. // Process the false branch.
  1067. if (builder.isFeasible(false)) {
  1068. if (ProgramStateRef state = PrevState->assume(V, false))
  1069. builder.generateNode(MarkBranch(state, Term, LCtx, false),
  1070. false, PredI);
  1071. else
  1072. builder.markInfeasible(false);
  1073. }
  1074. }
  1075. currentBuilderContext = 0;
  1076. }
  1077. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1078. /// nodes by processing the 'effects' of a computed goto jump.
  1079. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1080. ProgramStateRef state = builder.getState();
  1081. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1082. // Three possibilities:
  1083. //
  1084. // (1) We know the computed label.
  1085. // (2) The label is NULL (or some other constant), or Undefined.
  1086. // (3) We have no clue about the label. Dispatch to all targets.
  1087. //
  1088. typedef IndirectGotoNodeBuilder::iterator iterator;
  1089. if (isa<loc::GotoLabel>(V)) {
  1090. const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
  1091. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1092. if (I.getLabel() == L) {
  1093. builder.generateNode(I, state);
  1094. return;
  1095. }
  1096. }
  1097. llvm_unreachable("No block with label.");
  1098. }
  1099. if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
  1100. // Dispatch to the first target and mark it as a sink.
  1101. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1102. // FIXME: add checker visit.
  1103. // UndefBranches.insert(N);
  1104. return;
  1105. }
  1106. // This is really a catch-all. We don't support symbolics yet.
  1107. // FIXME: Implement dispatch for symbolic pointers.
  1108. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  1109. builder.generateNode(I, state);
  1110. }
  1111. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1112. /// nodes when the control reaches the end of a function.
  1113. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC) {
  1114. StateMgr.EndPath(BC.Pred->getState());
  1115. ExplodedNodeSet Dst;
  1116. getCheckerManager().runCheckersForEndPath(BC, Dst, *this);
  1117. Engine.enqueueEndOfFunction(Dst);
  1118. }
  1119. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1120. /// nodes by processing the 'effects' of a switch statement.
  1121. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1122. typedef SwitchNodeBuilder::iterator iterator;
  1123. ProgramStateRef state = builder.getState();
  1124. const Expr *CondE = builder.getCondition();
  1125. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1126. if (CondV_untested.isUndef()) {
  1127. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1128. // FIXME: add checker
  1129. //UndefBranches.insert(N);
  1130. return;
  1131. }
  1132. DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
  1133. ProgramStateRef DefaultSt = state;
  1134. iterator I = builder.begin(), EI = builder.end();
  1135. bool defaultIsFeasible = I == EI;
  1136. for ( ; I != EI; ++I) {
  1137. // Successor may be pruned out during CFG construction.
  1138. if (!I.getBlock())
  1139. continue;
  1140. const CaseStmt *Case = I.getCase();
  1141. // Evaluate the LHS of the case value.
  1142. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  1143. assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
  1144. // Get the RHS of the case, if it exists.
  1145. llvm::APSInt V2;
  1146. if (const Expr *E = Case->getRHS())
  1147. V2 = E->EvaluateKnownConstInt(getContext());
  1148. else
  1149. V2 = V1;
  1150. // FIXME: Eventually we should replace the logic below with a range
  1151. // comparison, rather than concretize the values within the range.
  1152. // This should be easy once we have "ranges" for NonLVals.
  1153. do {
  1154. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
  1155. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  1156. CondV, CaseVal);
  1157. // Now "assume" that the case matches.
  1158. if (ProgramStateRef stateNew = state->assume(Res, true)) {
  1159. builder.generateCaseStmtNode(I, stateNew);
  1160. // If CondV evaluates to a constant, then we know that this
  1161. // is the *only* case that we can take, so stop evaluating the
  1162. // others.
  1163. if (isa<nonloc::ConcreteInt>(CondV))
  1164. return;
  1165. }
  1166. // Now "assume" that the case doesn't match. Add this state
  1167. // to the default state (if it is feasible).
  1168. if (DefaultSt) {
  1169. if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
  1170. defaultIsFeasible = true;
  1171. DefaultSt = stateNew;
  1172. }
  1173. else {
  1174. defaultIsFeasible = false;
  1175. DefaultSt = NULL;
  1176. }
  1177. }
  1178. // Concretize the next value in the range.
  1179. if (V1 == V2)
  1180. break;
  1181. ++V1;
  1182. assert (V1 <= V2);
  1183. } while (true);
  1184. }
  1185. if (!defaultIsFeasible)
  1186. return;
  1187. // If we have switch(enum value), the default branch is not
  1188. // feasible if all of the enum constants not covered by 'case:' statements
  1189. // are not feasible values for the switch condition.
  1190. //
  1191. // Note that this isn't as accurate as it could be. Even if there isn't
  1192. // a case for a particular enum value as long as that enum value isn't
  1193. // feasible then it shouldn't be considered for making 'default:' reachable.
  1194. const SwitchStmt *SS = builder.getSwitch();
  1195. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1196. if (CondExpr->getType()->getAs<EnumType>()) {
  1197. if (SS->isAllEnumCasesCovered())
  1198. return;
  1199. }
  1200. builder.generateDefaultCaseNode(DefaultSt);
  1201. }
  1202. //===----------------------------------------------------------------------===//
  1203. // Transfer functions: Loads and stores.
  1204. //===----------------------------------------------------------------------===//
  1205. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1206. ExplodedNode *Pred,
  1207. ExplodedNodeSet &Dst) {
  1208. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  1209. ProgramStateRef state = Pred->getState();
  1210. const LocationContext *LCtx = Pred->getLocationContext();
  1211. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1212. assert(Ex->isGLValue());
  1213. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1214. // For references, the 'lvalue' is the pointer address stored in the
  1215. // reference region.
  1216. if (VD->getType()->isReferenceType()) {
  1217. if (const MemRegion *R = V.getAsRegion())
  1218. V = state->getSVal(R);
  1219. else
  1220. V = UnknownVal();
  1221. }
  1222. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
  1223. ProgramPoint::PostLValueKind);
  1224. return;
  1225. }
  1226. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  1227. assert(!Ex->isGLValue());
  1228. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1229. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  1230. return;
  1231. }
  1232. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1233. SVal V = svalBuilder.getFunctionPointer(FD);
  1234. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
  1235. ProgramPoint::PostLValueKind);
  1236. return;
  1237. }
  1238. if (isa<FieldDecl>(D)) {
  1239. // FIXME: Compute lvalue of fields.
  1240. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, UnknownVal()),
  1241. false, 0, ProgramPoint::PostLValueKind);
  1242. return;
  1243. }
  1244. assert (false &&
  1245. "ValueDecl support for this ValueDecl not implemented.");
  1246. }
  1247. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1248. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
  1249. ExplodedNode *Pred,
  1250. ExplodedNodeSet &Dst){
  1251. const Expr *Base = A->getBase()->IgnoreParens();
  1252. const Expr *Idx = A->getIdx()->IgnoreParens();
  1253. ExplodedNodeSet checkerPreStmt;
  1254. getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
  1255. StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currentBuilderContext);
  1256. for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
  1257. ei = checkerPreStmt.end(); it != ei; ++it) {
  1258. const LocationContext *LCtx = (*it)->getLocationContext();
  1259. ProgramStateRef state = (*it)->getState();
  1260. SVal V = state->getLValue(A->getType(),
  1261. state->getSVal(Idx, LCtx),
  1262. state->getSVal(Base, LCtx));
  1263. assert(A->isGLValue());
  1264. Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V),
  1265. false, 0, ProgramPoint::PostLValueKind);
  1266. }
  1267. }
  1268. /// VisitMemberExpr - Transfer function for member expressions.
  1269. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  1270. ExplodedNodeSet &TopDst) {
  1271. StmtNodeBuilder Bldr(Pred, TopDst, *currentBuilderContext);
  1272. ExplodedNodeSet Dst;
  1273. Decl *member = M->getMemberDecl();
  1274. if (VarDecl *VD = dyn_cast<VarDecl>(member)) {
  1275. assert(M->isGLValue());
  1276. Bldr.takeNodes(Pred);
  1277. VisitCommonDeclRefExpr(M, VD, Pred, Dst);
  1278. Bldr.addNodes(Dst);
  1279. return;
  1280. }
  1281. // Handle C++ method calls.
  1282. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(member)) {
  1283. Bldr.takeNodes(Pred);
  1284. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  1285. ProgramStateRef state =
  1286. Pred->getState()->BindExpr(M, Pred->getLocationContext(), MDVal);
  1287. Bldr.generateNode(M, Pred, state);
  1288. return;
  1289. }
  1290. FieldDecl *field = dyn_cast<FieldDecl>(member);
  1291. if (!field) // FIXME: skipping member expressions for non-fields
  1292. return;
  1293. Expr *baseExpr = M->getBase()->IgnoreParens();
  1294. ProgramStateRef state = Pred->getState();
  1295. const LocationContext *LCtx = Pred->getLocationContext();
  1296. SVal baseExprVal = state->getSVal(baseExpr, Pred->getLocationContext());
  1297. if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
  1298. isa<nonloc::CompoundVal>(baseExprVal) ||
  1299. // FIXME: This can originate by conjuring a symbol for an unknown
  1300. // temporary struct object, see test/Analysis/fields.c:
  1301. // (p = getit()).x
  1302. isa<nonloc::SymbolVal>(baseExprVal)) {
  1303. Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, UnknownVal()));
  1304. return;
  1305. }
  1306. // FIXME: Should we insert some assumption logic in here to determine
  1307. // if "Base" is a valid piece of memory? Before we put this assumption
  1308. // later when using FieldOffset lvals (which we no longer have).
  1309. // For all other cases, compute an lvalue.
  1310. SVal L = state->getLValue(field, baseExprVal);
  1311. if (M->isGLValue())
  1312. Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), false, 0,
  1313. ProgramPoint::PostLValueKind);
  1314. else {
  1315. Bldr.takeNodes(Pred);
  1316. evalLoad(Dst, M, M, Pred, state, L);
  1317. Bldr.addNodes(Dst);
  1318. }
  1319. }
  1320. /// evalBind - Handle the semantics of binding a value to a specific location.
  1321. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1322. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  1323. ExplodedNode *Pred,
  1324. SVal location, SVal Val, bool atDeclInit) {
  1325. // Do a previsit of the bind.
  1326. ExplodedNodeSet CheckedSet;
  1327. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  1328. StoreE, *this,
  1329. ProgramPoint::PostStmtKind);
  1330. ExplodedNodeSet TmpDst;
  1331. StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currentBuilderContext);
  1332. const LocationContext *LC = Pred->getLocationContext();
  1333. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1334. I!=E; ++I) {
  1335. ExplodedNode *PredI = *I;
  1336. ProgramStateRef state = PredI->getState();
  1337. if (atDeclInit) {
  1338. const VarRegion *VR =
  1339. cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
  1340. state = state->bindDecl(VR, Val);
  1341. } else {
  1342. state = state->bindLoc(location, Val);
  1343. }
  1344. const MemRegion *LocReg = 0;
  1345. if (loc::MemRegionVal *LocRegVal = dyn_cast<loc::MemRegionVal>(&location))
  1346. LocReg = LocRegVal->getRegion();
  1347. const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
  1348. Bldr.generateNode(L, PredI, state, false);
  1349. }
  1350. Dst.insert(TmpDst);
  1351. }
  1352. /// evalStore - Handle the semantics of a store via an assignment.
  1353. /// @param Dst The node set to store generated state nodes
  1354. /// @param AssignE The assignment expression if the store happens in an
  1355. /// assignment.
  1356. /// @param LocationE The location expression that is stored to.
  1357. /// @param state The current simulation state
  1358. /// @param location The location to store the value
  1359. /// @param Val The value to be stored
  1360. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  1361. const Expr *LocationE,
  1362. ExplodedNode *Pred,
  1363. ProgramStateRef state, SVal location, SVal Val,
  1364. const ProgramPointTag *tag) {
  1365. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1366. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1367. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1368. if (isa<loc::ObjCPropRef>(location)) {
  1369. assert(false);
  1370. }
  1371. // Evaluate the location (checks for bad dereferences).
  1372. ExplodedNodeSet Tmp;
  1373. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  1374. if (Tmp.empty())
  1375. return;
  1376. if (location.isUndef())
  1377. return;
  1378. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1379. evalBind(Dst, StoreE, *NI, location, Val, false);
  1380. }
  1381. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  1382. const Expr *NodeEx,
  1383. const Expr *BoundEx,
  1384. ExplodedNode *Pred,
  1385. ProgramStateRef state,
  1386. SVal location,
  1387. const ProgramPointTag *tag,
  1388. QualType LoadTy)
  1389. {
  1390. assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
  1391. assert(!isa<loc::ObjCPropRef>(location));
  1392. // Are we loading from a region? This actually results in two loads; one
  1393. // to fetch the address of the referenced value and one to fetch the
  1394. // referenced value.
  1395. if (const TypedValueRegion *TR =
  1396. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  1397. QualType ValTy = TR->getValueType();
  1398. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1399. static SimpleProgramPointTag
  1400. loadReferenceTag("ExprEngine : Load Reference");
  1401. ExplodedNodeSet Tmp;
  1402. evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
  1403. location, &loadReferenceTag,
  1404. getContext().getPointerType(RT->getPointeeType()));
  1405. // Perform the load from the referenced value.
  1406. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1407. state = (*I)->getState();
  1408. location = state->getSVal(BoundEx, (*I)->getLocationContext());
  1409. evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
  1410. }
  1411. return;
  1412. }
  1413. }
  1414. evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
  1415. }
  1416. void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
  1417. const Expr *NodeEx,
  1418. const Expr *BoundEx,
  1419. ExplodedNode *Pred,
  1420. ProgramStateRef state,
  1421. SVal location,
  1422. const ProgramPointTag *tag,
  1423. QualType LoadTy) {
  1424. assert(NodeEx);
  1425. assert(BoundEx);
  1426. // Evaluate the location (checks for bad dereferences).
  1427. ExplodedNodeSet Tmp;
  1428. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  1429. if (Tmp.empty())
  1430. return;
  1431. StmtNodeBuilder Bldr(Tmp, Dst, *currentBuilderContext);
  1432. if (location.isUndef())
  1433. return;
  1434. // Proceed with the load.
  1435. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1436. state = (*NI)->getState();
  1437. const LocationContext *LCtx = (*NI)->getLocationContext();
  1438. if (location.isUnknown()) {
  1439. // This is important. We must nuke the old binding.
  1440. Bldr.generateNode(NodeEx, *NI,
  1441. state->BindExpr(BoundEx, LCtx, UnknownVal()),
  1442. false, tag,
  1443. ProgramPoint::PostLoadKind);
  1444. }
  1445. else {
  1446. if (LoadTy.isNull())
  1447. LoadTy = BoundEx->getType();
  1448. SVal V = state->getSVal(cast<Loc>(location), LoadTy);
  1449. Bldr.generateNode(NodeEx, *NI,
  1450. state->bindExprAndLocation(BoundEx, LCtx, location, V),
  1451. false, tag, ProgramPoint::PostLoadKind);
  1452. }
  1453. }
  1454. }
  1455. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  1456. const Stmt *NodeEx,
  1457. const Stmt *BoundEx,
  1458. ExplodedNode *Pred,
  1459. ProgramStateRef state,
  1460. SVal location,
  1461. const ProgramPointTag *tag,
  1462. bool isLoad) {
  1463. StmtNodeBuilder BldrTop(Pred, Dst, *currentBuilderContext);
  1464. // Early checks for performance reason.
  1465. if (location.isUnknown()) {
  1466. return;
  1467. }
  1468. ExplodedNodeSet Src;
  1469. BldrTop.takeNodes(Pred);
  1470. StmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext);
  1471. if (Pred->getState() != state) {
  1472. // Associate this new state with an ExplodedNode.
  1473. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  1474. // int *p;
  1475. // p = 0;
  1476. // *p = 0xDEADBEEF;
  1477. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  1478. // instead "int *p" is noted as
  1479. // "Variable 'p' initialized to a null pointer value"
  1480. // FIXME: why is 'tag' not used instead of etag?
  1481. static SimpleProgramPointTag etag("ExprEngine: Location");
  1482. Bldr.generateNode(NodeEx, Pred, state, false, &etag);
  1483. }
  1484. ExplodedNodeSet Tmp;
  1485. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  1486. NodeEx, BoundEx, *this);
  1487. BldrTop.addNodes(Tmp);
  1488. }
  1489. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  1490. ExprEngine::getEagerlyAssumeTags() {
  1491. static SimpleProgramPointTag
  1492. EagerlyAssumeTrue("ExprEngine : Eagerly Assume True"),
  1493. EagerlyAssumeFalse("ExprEngine : Eagerly Assume False");
  1494. return std::make_pair(&EagerlyAssumeTrue, &EagerlyAssumeFalse);
  1495. }
  1496. void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
  1497. const Expr *Ex) {
  1498. StmtNodeBuilder Bldr(Src, Dst, *currentBuilderContext);
  1499. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1500. ExplodedNode *Pred = *I;
  1501. // Test if the previous node was as the same expression. This can happen
  1502. // when the expression fails to evaluate to anything meaningful and
  1503. // (as an optimization) we don't generate a node.
  1504. ProgramPoint P = Pred->getLocation();
  1505. if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
  1506. continue;
  1507. }
  1508. ProgramStateRef state = Pred->getState();
  1509. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  1510. nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V);
  1511. if (SEV && SEV->isExpression()) {
  1512. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  1513. getEagerlyAssumeTags();
  1514. // First assume that the condition is true.
  1515. if (ProgramStateRef StateTrue = state->assume(*SEV, true)) {
  1516. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  1517. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  1518. Bldr.generateNode(Ex, Pred, StateTrue, false, tags.first);
  1519. }
  1520. // Next, assume that the condition is false.
  1521. if (ProgramStateRef StateFalse = state->assume(*SEV, false)) {
  1522. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  1523. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  1524. Bldr.generateNode(Ex, Pred, StateFalse, false, tags.second);
  1525. }
  1526. }
  1527. }
  1528. }
  1529. void ExprEngine::VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred,
  1530. ExplodedNodeSet &Dst) {
  1531. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  1532. // We have processed both the inputs and the outputs. All of the outputs
  1533. // should evaluate to Locs. Nuke all of their values.
  1534. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  1535. // which interprets the inline asm and stores proper results in the
  1536. // outputs.
  1537. ProgramStateRef state = Pred->getState();
  1538. for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  1539. OE = A->end_outputs(); OI != OE; ++OI) {
  1540. SVal X = state->getSVal(*OI, Pred->getLocationContext());
  1541. assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
  1542. if (isa<Loc>(X))
  1543. state = state->bindLoc(cast<Loc>(X), UnknownVal());
  1544. }
  1545. Bldr.generateNode(A, Pred, state);
  1546. }
  1547. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  1548. ExplodedNodeSet &Dst) {
  1549. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  1550. Bldr.generateNode(A, Pred, Pred->getState());
  1551. }
  1552. //===----------------------------------------------------------------------===//
  1553. // Visualization.
  1554. //===----------------------------------------------------------------------===//
  1555. #ifndef NDEBUG
  1556. static ExprEngine* GraphPrintCheckerState;
  1557. static SourceManager* GraphPrintSourceManager;
  1558. namespace llvm {
  1559. template<>
  1560. struct DOTGraphTraits<ExplodedNode*> :
  1561. public DefaultDOTGraphTraits {
  1562. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  1563. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  1564. // work.
  1565. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  1566. #if 0
  1567. // FIXME: Replace with a general scheme to tell if the node is
  1568. // an error node.
  1569. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  1570. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  1571. GraphPrintCheckerState->isUndefDeref(N) ||
  1572. GraphPrintCheckerState->isUndefStore(N) ||
  1573. GraphPrintCheckerState->isUndefControlFlow(N) ||
  1574. GraphPrintCheckerState->isUndefResult(N) ||
  1575. GraphPrintCheckerState->isBadCall(N) ||
  1576. GraphPrintCheckerState->isUndefArg(N))
  1577. return "color=\"red\",style=\"filled\"";
  1578. if (GraphPrintCheckerState->isNoReturnCall(N))
  1579. return "color=\"blue\",style=\"filled\"";
  1580. #endif
  1581. return "";
  1582. }
  1583. static void printLocation(llvm::raw_ostream &Out, SourceLocation SLoc) {
  1584. if (SLoc.isFileID()) {
  1585. Out << "\\lline="
  1586. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1587. << " col="
  1588. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  1589. << "\\l";
  1590. }
  1591. }
  1592. static std::string getNodeLabel(const ExplodedNode *N, void*){
  1593. std::string sbuf;
  1594. llvm::raw_string_ostream Out(sbuf);
  1595. // Program Location.
  1596. ProgramPoint Loc = N->getLocation();
  1597. switch (Loc.getKind()) {
  1598. case ProgramPoint::BlockEntranceKind: {
  1599. Out << "Block Entrance: B"
  1600. << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
  1601. if (const NamedDecl *ND =
  1602. dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
  1603. Out << " (";
  1604. ND->printName(Out);
  1605. Out << ")";
  1606. }
  1607. break;
  1608. }
  1609. case ProgramPoint::BlockExitKind:
  1610. assert (false);
  1611. break;
  1612. case ProgramPoint::CallEnterKind:
  1613. Out << "CallEnter";
  1614. break;
  1615. case ProgramPoint::CallExitBeginKind:
  1616. Out << "CallExitBegin";
  1617. break;
  1618. case ProgramPoint::CallExitEndKind:
  1619. Out << "CallExitEnd";
  1620. break;
  1621. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  1622. Out << "PostStmtPurgeDeadSymbols";
  1623. break;
  1624. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  1625. Out << "PreStmtPurgeDeadSymbols";
  1626. break;
  1627. case ProgramPoint::EpsilonKind:
  1628. Out << "Epsilon Point";
  1629. break;
  1630. case ProgramPoint::PreImplicitCallKind: {
  1631. ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
  1632. Out << "PreCall: ";
  1633. // FIXME: Get proper printing options.
  1634. PC->getDecl()->print(Out, LangOptions());
  1635. printLocation(Out, PC->getLocation());
  1636. break;
  1637. }
  1638. case ProgramPoint::PostImplicitCallKind: {
  1639. ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
  1640. Out << "PostCall: ";
  1641. // FIXME: Get proper printing options.
  1642. PC->getDecl()->print(Out, LangOptions());
  1643. printLocation(Out, PC->getLocation());
  1644. break;
  1645. }
  1646. default: {
  1647. if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
  1648. const Stmt *S = L->getStmt();
  1649. Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
  1650. LangOptions LO; // FIXME.
  1651. S->printPretty(Out, 0, PrintingPolicy(LO));
  1652. printLocation(Out, S->getLocStart());
  1653. if (isa<PreStmt>(Loc))
  1654. Out << "\\lPreStmt\\l;";
  1655. else if (isa<PostLoad>(Loc))
  1656. Out << "\\lPostLoad\\l;";
  1657. else if (isa<PostStore>(Loc))
  1658. Out << "\\lPostStore\\l";
  1659. else if (isa<PostLValue>(Loc))
  1660. Out << "\\lPostLValue\\l";
  1661. #if 0
  1662. // FIXME: Replace with a general scheme to determine
  1663. // the name of the check.
  1664. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  1665. Out << "\\|Implicit-Null Dereference.\\l";
  1666. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  1667. Out << "\\|Explicit-Null Dereference.\\l";
  1668. else if (GraphPrintCheckerState->isUndefDeref(N))
  1669. Out << "\\|Dereference of undefialied value.\\l";
  1670. else if (GraphPrintCheckerState->isUndefStore(N))
  1671. Out << "\\|Store to Undefined Loc.";
  1672. else if (GraphPrintCheckerState->isUndefResult(N))
  1673. Out << "\\|Result of operation is undefined.";
  1674. else if (GraphPrintCheckerState->isNoReturnCall(N))
  1675. Out << "\\|Call to function marked \"noreturn\".";
  1676. else if (GraphPrintCheckerState->isBadCall(N))
  1677. Out << "\\|Call to NULL/Undefined.";
  1678. else if (GraphPrintCheckerState->isUndefArg(N))
  1679. Out << "\\|Argument in call is undefined";
  1680. #endif
  1681. break;
  1682. }
  1683. const BlockEdge &E = cast<BlockEdge>(Loc);
  1684. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  1685. << E.getDst()->getBlockID() << ')';
  1686. if (const Stmt *T = E.getSrc()->getTerminator()) {
  1687. SourceLocation SLoc = T->getLocStart();
  1688. Out << "\\|Terminator: ";
  1689. LangOptions LO; // FIXME.
  1690. E.getSrc()->printTerminator(Out, LO);
  1691. if (SLoc.isFileID()) {
  1692. Out << "\\lline="
  1693. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1694. << " col="
  1695. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  1696. }
  1697. if (isa<SwitchStmt>(T)) {
  1698. const Stmt *Label = E.getDst()->getLabel();
  1699. if (Label) {
  1700. if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  1701. Out << "\\lcase ";
  1702. LangOptions LO; // FIXME.
  1703. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  1704. if (const Stmt *RHS = C->getRHS()) {
  1705. Out << " .. ";
  1706. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  1707. }
  1708. Out << ":";
  1709. }
  1710. else {
  1711. assert (isa<DefaultStmt>(Label));
  1712. Out << "\\ldefault:";
  1713. }
  1714. }
  1715. else
  1716. Out << "\\l(implicit) default:";
  1717. }
  1718. else if (isa<IndirectGotoStmt>(T)) {
  1719. // FIXME
  1720. }
  1721. else {
  1722. Out << "\\lCondition: ";
  1723. if (*E.getSrc()->succ_begin() == E.getDst())
  1724. Out << "true";
  1725. else
  1726. Out << "false";
  1727. }
  1728. Out << "\\l";
  1729. }
  1730. #if 0
  1731. // FIXME: Replace with a general scheme to determine
  1732. // the name of the check.
  1733. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  1734. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  1735. }
  1736. #endif
  1737. }
  1738. }
  1739. ProgramStateRef state = N->getState();
  1740. Out << "\\|StateID: " << (void*) state.getPtr()
  1741. << " NodeID: " << (void*) N << "\\|";
  1742. state->printDOT(Out);
  1743. Out << "\\l";
  1744. if (const ProgramPointTag *tag = Loc.getTag()) {
  1745. Out << "\\|Tag: " << tag->getTagDescription();
  1746. Out << "\\l";
  1747. }
  1748. return Out.str();
  1749. }
  1750. };
  1751. } // end llvm namespace
  1752. #endif
  1753. #ifndef NDEBUG
  1754. template <typename ITERATOR>
  1755. ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
  1756. template <> ExplodedNode*
  1757. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  1758. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  1759. return I->first;
  1760. }
  1761. #endif
  1762. void ExprEngine::ViewGraph(bool trim) {
  1763. #ifndef NDEBUG
  1764. if (trim) {
  1765. std::vector<ExplodedNode*> Src;
  1766. // Flush any outstanding reports to make sure we cover all the nodes.
  1767. // This does not cause them to get displayed.
  1768. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  1769. const_cast<BugType*>(*I)->FlushReports(BR);
  1770. // Iterate through the reports and get their nodes.
  1771. for (BugReporter::EQClasses_iterator
  1772. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  1773. ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
  1774. if (N) Src.push_back(N);
  1775. }
  1776. ViewGraph(&Src[0], &Src[0]+Src.size());
  1777. }
  1778. else {
  1779. GraphPrintCheckerState = this;
  1780. GraphPrintSourceManager = &getContext().getSourceManager();
  1781. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  1782. GraphPrintCheckerState = NULL;
  1783. GraphPrintSourceManager = NULL;
  1784. }
  1785. #endif
  1786. }
  1787. void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
  1788. #ifndef NDEBUG
  1789. GraphPrintCheckerState = this;
  1790. GraphPrintSourceManager = &getContext().getSourceManager();
  1791. std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
  1792. if (!TrimmedG.get())
  1793. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  1794. else
  1795. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  1796. GraphPrintCheckerState = NULL;
  1797. GraphPrintSourceManager = NULL;
  1798. #endif
  1799. }