ExprEngine.cpp 90 KB

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