ExprEngine.cpp 67 KB

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