ExprEngine.cpp 66 KB

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