ExprEngine.cpp 72 KB

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