ExprEngine.cpp 74 KB

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