ExprEngine.cpp 73 KB

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