ExprEngine.cpp 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104
  1. //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines a meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h"
  20. #include "clang/AST/CharUnits.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/Basic/Builtins.h"
  25. #include "clang/Basic/SourceManager.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/PrettyStackTrace.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/ADT/ImmutableList.h"
  30. #ifndef NDEBUG
  31. #include "llvm/Support/GraphWriter.h"
  32. #endif
  33. using namespace clang;
  34. using namespace ento;
  35. using llvm::APSInt;
  36. namespace {
  37. // Trait class for recording returned expression in the state.
  38. struct ReturnExpr {
  39. static int TagInt;
  40. typedef const Stmt *data_type;
  41. };
  42. int ReturnExpr::TagInt;
  43. }
  44. //===----------------------------------------------------------------------===//
  45. // Utility functions.
  46. //===----------------------------------------------------------------------===//
  47. static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
  48. IdentifierInfo* II = &Ctx.Idents.get(name);
  49. return Ctx.Selectors.getSelector(0, &II);
  50. }
  51. //===----------------------------------------------------------------------===//
  52. // Engine construction and deletion.
  53. //===----------------------------------------------------------------------===//
  54. ExprEngine::ExprEngine(AnalysisManager &mgr, TransferFuncs *tf)
  55. : AMgr(mgr),
  56. Engine(*this),
  57. G(Engine.getGraph()),
  58. Builder(NULL),
  59. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  60. mgr.getConstraintManagerCreator(), G.getAllocator(),
  61. *this),
  62. SymMgr(StateMgr.getSymbolManager()),
  63. svalBuilder(StateMgr.getSValBuilder()),
  64. EntryNode(NULL), currentStmt(NULL),
  65. NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
  66. RaiseSel(GetNullarySelector("raise", getContext())),
  67. BR(mgr, *this), TF(tf) {
  68. // FIXME: Eventually remove the TF object entirely.
  69. TF->RegisterChecks(*this);
  70. TF->RegisterPrinters(getStateManager().Printers);
  71. if (mgr.shouldEagerlyTrimExplodedGraph()) {
  72. // Enable eager node reclaimation when constructing the ExplodedGraph.
  73. G.enableNodeReclamation();
  74. }
  75. }
  76. ExprEngine::~ExprEngine() {
  77. BR.FlushReports();
  78. delete [] NSExceptionInstanceRaiseSelectors;
  79. }
  80. //===----------------------------------------------------------------------===//
  81. // Utility methods.
  82. //===----------------------------------------------------------------------===//
  83. const GRState* ExprEngine::getInitialState(const LocationContext *InitLoc) {
  84. const GRState *state = StateMgr.getInitialState(InitLoc);
  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. const Decl *D = InitLoc->getDecl();
  90. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  91. // Precondition: the first argument of 'main' is an integer guaranteed
  92. // to be > 0.
  93. const IdentifierInfo *II = FD->getIdentifier();
  94. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  95. break;
  96. const ParmVarDecl *PD = FD->getParamDecl(0);
  97. QualType T = PD->getType();
  98. if (!T->isIntegerType())
  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. DefinedOrUnknownSVal *Constraint =
  108. dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
  109. if (!Constraint)
  110. break;
  111. if (const GRState *newState = state->assume(*Constraint, true))
  112. state = newState;
  113. break;
  114. }
  115. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  116. // Precondition: 'self' is always non-null upon entry to an Objective-C
  117. // method.
  118. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  119. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  120. SVal V = state->getSVal(loc::MemRegionVal(R));
  121. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  122. // Assume that the pointer value in 'self' is non-null.
  123. state = state->assume(*LV, true);
  124. assert(state && "'self' cannot be null");
  125. }
  126. }
  127. } while (0);
  128. return state;
  129. }
  130. bool
  131. ExprEngine::doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const
  132. {
  133. if (callOrMessage.isFunctionCall() && !callOrMessage.isCXXCall()) {
  134. SVal calleeV = callOrMessage.getFunctionCallee();
  135. if (const FunctionTextRegion *codeR =
  136. dyn_cast_or_null<FunctionTextRegion>(calleeV.getAsRegion())) {
  137. const FunctionDecl *fd = codeR->getDecl();
  138. if (const IdentifierInfo *ii = fd->getIdentifier()) {
  139. StringRef fname = ii->getName();
  140. if (fname == "strlen")
  141. return false;
  142. }
  143. }
  144. }
  145. // The conservative answer: invalidates globals.
  146. return true;
  147. }
  148. //===----------------------------------------------------------------------===//
  149. // Top-level transfer function logic (Dispatcher).
  150. //===----------------------------------------------------------------------===//
  151. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  152. /// logic for handling assumptions on symbolic values.
  153. const GRState *ExprEngine::processAssume(const GRState *state, SVal cond,
  154. bool assumption) {
  155. state = getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  156. // If the state is infeasible at this point, bail out.
  157. if (!state)
  158. return NULL;
  159. return TF->evalAssume(state, cond, assumption);
  160. }
  161. bool ExprEngine::wantsRegionChangeUpdate(const GRState* state) {
  162. return getCheckerManager().wantsRegionChangeUpdate(state);
  163. }
  164. const GRState *
  165. ExprEngine::processRegionChanges(const GRState *state,
  166. const StoreManager::InvalidatedSymbols *invalidated,
  167. const MemRegion * const *Begin,
  168. const MemRegion * const *End) {
  169. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  170. Begin, End);
  171. }
  172. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  173. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  174. }
  175. void ExprEngine::processCFGElement(const CFGElement E,
  176. StmtNodeBuilder& builder) {
  177. switch (E.getKind()) {
  178. case CFGElement::Invalid:
  179. llvm_unreachable("Unexpected CFGElement kind.");
  180. case CFGElement::Statement:
  181. ProcessStmt(E.getAs<CFGStmt>()->getStmt(), builder);
  182. return;
  183. case CFGElement::Initializer:
  184. ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), builder);
  185. return;
  186. case CFGElement::AutomaticObjectDtor:
  187. case CFGElement::BaseDtor:
  188. case CFGElement::MemberDtor:
  189. case CFGElement::TemporaryDtor:
  190. ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), builder);
  191. return;
  192. }
  193. }
  194. void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) {
  195. // TODO: Use RAII to remove the unnecessary, tagged nodes.
  196. //RegisterCreatedNodes registerCreatedNodes(getGraph());
  197. // Reclaim any unnecessary nodes in the ExplodedGraph.
  198. G.reclaimRecentlyAllocatedNodes();
  199. // Recycle any unused states in the GRStateManager.
  200. StateMgr.recycleUnusedStates();
  201. currentStmt = S.getStmt();
  202. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  203. currentStmt->getLocStart(),
  204. "Error evaluating statement");
  205. // A tag to track convenience transitions, which can be removed at cleanup.
  206. static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
  207. Builder = &builder;
  208. EntryNode = builder.getPredecessor();
  209. const GRState *EntryState = EntryNode->getState();
  210. CleanedState = EntryState;
  211. ExplodedNode *CleanedNode = 0;
  212. // Create the cleaned state.
  213. const LocationContext *LC = EntryNode->getLocationContext();
  214. SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager());
  215. if (AMgr.shouldPurgeDead()) {
  216. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  217. const StackFrameContext *SFC = LC->getCurrentStackFrame();
  218. // Create a state in which dead bindings are removed from the environment
  219. // and the store. TODO: The function should just return new env and store,
  220. // not a new state.
  221. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  222. }
  223. // Process any special transfer function for dead symbols.
  224. ExplodedNodeSet Tmp;
  225. if (!SymReaper.hasDeadSymbols()) {
  226. // Generate a CleanedNode that has the environment and store cleaned
  227. // up. Since no symbols are dead, we can optimize and not clean out
  228. // the constraint manager.
  229. CleanedNode =
  230. Builder->generateNode(currentStmt, CleanedState, EntryNode, &cleanupTag);
  231. Tmp.Add(CleanedNode);
  232. } else {
  233. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  234. SaveOr OldHasGen(Builder->hasGeneratedNode);
  235. SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols);
  236. Builder->PurgingDeadSymbols = true;
  237. // Call checkers with the non-cleaned state so that they could query the
  238. // values of the soon to be dead symbols.
  239. // FIXME: This should soon be removed.
  240. ExplodedNodeSet Tmp2;
  241. getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode,
  242. EntryState, SymReaper);
  243. ExplodedNodeSet Tmp3;
  244. getCheckerManager().runCheckersForDeadSymbols(Tmp3, Tmp2,
  245. SymReaper, currentStmt, *this);
  246. // For each node in Tmp3, generate CleanedNodes that have the environment,
  247. // the store, and the constraints cleaned up but have the user supplied
  248. // states as the predecessors.
  249. for (ExplodedNodeSet::const_iterator I = Tmp3.begin(), E = Tmp3.end();
  250. I != E; ++I) {
  251. const GRState *CheckerState = (*I)->getState();
  252. // The constraint manager has not been cleaned up yet, so clean up now.
  253. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  254. SymReaper);
  255. assert(StateMgr.haveEqualEnvironments(CheckerState, EntryState) &&
  256. "Checkers are not allowed to modify the Environment as a part of "
  257. "checkDeadSymbols processing.");
  258. assert(StateMgr.haveEqualStores(CheckerState, EntryState) &&
  259. "Checkers are not allowed to modify the Store as a part of "
  260. "checkDeadSymbols processing.");
  261. // Create a state based on CleanedState with CheckerState GDM and
  262. // generate a transition to that state.
  263. const GRState *CleanedCheckerSt =
  264. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  265. ExplodedNode *CleanedNode = Builder->generateNode(currentStmt,
  266. CleanedCheckerSt, *I,
  267. &cleanupTag);
  268. Tmp.Add(CleanedNode);
  269. }
  270. }
  271. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  272. // TODO: Remove Dest set, it's no longer needed.
  273. ExplodedNodeSet Dst;
  274. // Visit the statement.
  275. Visit(currentStmt, *I, Dst);
  276. }
  277. // NULL out these variables to cleanup.
  278. CleanedState = NULL;
  279. EntryNode = NULL;
  280. currentStmt = 0;
  281. Builder = NULL;
  282. }
  283. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  284. StmtNodeBuilder &builder) {
  285. // We don't set EntryNode and currentStmt. And we don't clean up state.
  286. const CXXCtorInitializer *BMI = Init.getInitializer();
  287. ExplodedNode *pred = builder.getPredecessor();
  288. const StackFrameContext *stackFrame = cast<StackFrameContext>(pred->getLocationContext());
  289. const CXXConstructorDecl *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
  290. const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame);
  291. SVal thisVal = pred->getState()->getSVal(thisReg);
  292. if (BMI->isAnyMemberInitializer()) {
  293. ExplodedNodeSet Dst;
  294. // Evaluate the initializer.
  295. Visit(BMI->getInit(), pred, Dst);
  296. for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){
  297. ExplodedNode *Pred = *I;
  298. const GRState *state = Pred->getState();
  299. const FieldDecl *FD = BMI->getAnyMember();
  300. SVal FieldLoc = state->getLValue(FD, thisVal);
  301. SVal InitVal = state->getSVal(BMI->getInit());
  302. state = state->bindLoc(FieldLoc, InitVal);
  303. // Use a custom node building process.
  304. PostInitializer PP(BMI, stackFrame);
  305. // Builder automatically add the generated node to the deferred set,
  306. // which are processed in the builder's dtor.
  307. builder.generateNode(PP, state, Pred);
  308. }
  309. return;
  310. }
  311. assert(BMI->isBaseInitializer());
  312. // Get the base class declaration.
  313. const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
  314. // Create the base object region.
  315. SVal baseVal =
  316. getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
  317. const MemRegion *baseReg = baseVal.getAsRegion();
  318. assert(baseReg);
  319. Builder = &builder;
  320. ExplodedNodeSet dst;
  321. VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst);
  322. }
  323. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  324. StmtNodeBuilder &builder) {
  325. Builder = &builder;
  326. switch (D.getKind()) {
  327. case CFGElement::AutomaticObjectDtor:
  328. ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder);
  329. break;
  330. case CFGElement::BaseDtor:
  331. ProcessBaseDtor(cast<CFGBaseDtor>(D), builder);
  332. break;
  333. case CFGElement::MemberDtor:
  334. ProcessMemberDtor(cast<CFGMemberDtor>(D), builder);
  335. break;
  336. case CFGElement::TemporaryDtor:
  337. ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder);
  338. break;
  339. default:
  340. llvm_unreachable("Unexpected dtor kind.");
  341. }
  342. }
  343. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor,
  344. StmtNodeBuilder &builder) {
  345. ExplodedNode *pred = builder.getPredecessor();
  346. const GRState *state = pred->getState();
  347. const VarDecl *varDecl = dtor.getVarDecl();
  348. QualType varType = varDecl->getType();
  349. if (const ReferenceType *refType = varType->getAs<ReferenceType>())
  350. varType = refType->getPointeeType();
  351. const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
  352. assert(recordDecl && "get CXXRecordDecl fail");
  353. const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
  354. Loc dest = state->getLValue(varDecl, pred->getLocationContext());
  355. ExplodedNodeSet dstSet;
  356. VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
  357. dtor.getTriggerStmt(), pred, dstSet);
  358. }
  359. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  360. StmtNodeBuilder &builder) {
  361. }
  362. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  363. StmtNodeBuilder &builder) {
  364. }
  365. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  366. StmtNodeBuilder &builder) {
  367. }
  368. void ExprEngine::Visit(const Stmt* S, ExplodedNode* Pred,
  369. ExplodedNodeSet& Dst) {
  370. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  371. S->getLocStart(),
  372. "Error evaluating statement");
  373. // Expressions to ignore.
  374. if (const Expr *Ex = dyn_cast<Expr>(S))
  375. S = Ex->IgnoreParens();
  376. // FIXME: add metadata to the CFG so that we can disable
  377. // this check when we KNOW that there is no block-level subexpression.
  378. // The motivation is that this check requires a hashtable lookup.
  379. if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) {
  380. Dst.Add(Pred);
  381. return;
  382. }
  383. switch (S->getStmtClass()) {
  384. // C++ and ARC stuff we don't support yet.
  385. case Expr::ObjCIndirectCopyRestoreExprClass:
  386. case Stmt::CXXBindTemporaryExprClass:
  387. case Stmt::CXXCatchStmtClass:
  388. case Stmt::CXXDependentScopeMemberExprClass:
  389. case Stmt::CXXForRangeStmtClass:
  390. case Stmt::CXXPseudoDestructorExprClass:
  391. case Stmt::CXXTemporaryObjectExprClass:
  392. case Stmt::CXXThrowExprClass:
  393. case Stmt::CXXTryStmtClass:
  394. case Stmt::CXXTypeidExprClass:
  395. case Stmt::CXXUuidofExprClass:
  396. case Stmt::CXXUnresolvedConstructExprClass:
  397. case Stmt::CXXScalarValueInitExprClass:
  398. case Stmt::DependentScopeDeclRefExprClass:
  399. case Stmt::UnaryTypeTraitExprClass:
  400. case Stmt::BinaryTypeTraitExprClass:
  401. case Stmt::ArrayTypeTraitExprClass:
  402. case Stmt::ExpressionTraitExprClass:
  403. case Stmt::UnresolvedLookupExprClass:
  404. case Stmt::UnresolvedMemberExprClass:
  405. case Stmt::CXXNoexceptExprClass:
  406. case Stmt::PackExpansionExprClass:
  407. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  408. case Stmt::SEHTryStmtClass:
  409. case Stmt::SEHExceptStmtClass:
  410. case Stmt::SEHFinallyStmtClass:
  411. {
  412. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  413. Builder->BuildSinks = true;
  414. const ExplodedNode *node = MakeNode(Dst, S, Pred, Pred->getState());
  415. Engine.addAbortedBlock(node, Builder->getBlock());
  416. break;
  417. }
  418. // We don't handle default arguments either yet, but we can fake it
  419. // for now by just skipping them.
  420. case Stmt::SubstNonTypeTemplateParmExprClass:
  421. case Stmt::CXXDefaultArgExprClass: {
  422. Dst.Add(Pred);
  423. break;
  424. }
  425. case Stmt::ParenExprClass:
  426. llvm_unreachable("ParenExprs already handled.");
  427. case Stmt::GenericSelectionExprClass:
  428. llvm_unreachable("GenericSelectionExprs already handled.");
  429. // Cases that should never be evaluated simply because they shouldn't
  430. // appear in the CFG.
  431. case Stmt::BreakStmtClass:
  432. case Stmt::CaseStmtClass:
  433. case Stmt::CompoundStmtClass:
  434. case Stmt::ContinueStmtClass:
  435. case Stmt::DefaultStmtClass:
  436. case Stmt::DoStmtClass:
  437. case Stmt::ForStmtClass:
  438. case Stmt::GotoStmtClass:
  439. case Stmt::IfStmtClass:
  440. case Stmt::IndirectGotoStmtClass:
  441. case Stmt::LabelStmtClass:
  442. case Stmt::NoStmtClass:
  443. case Stmt::NullStmtClass:
  444. case Stmt::SwitchStmtClass:
  445. case Stmt::WhileStmtClass:
  446. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  447. break;
  448. case Stmt::GNUNullExprClass: {
  449. // GNU __null is a pointer-width integer, not an actual pointer.
  450. const GRState *state = Pred->getState();
  451. state = state->BindExpr(S, svalBuilder.makeIntValWithPtrWidth(0, false));
  452. MakeNode(Dst, S, Pred, state);
  453. break;
  454. }
  455. case Stmt::ObjCAtSynchronizedStmtClass:
  456. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  457. break;
  458. case Stmt::ObjCPropertyRefExprClass:
  459. VisitObjCPropertyRefExpr(cast<ObjCPropertyRefExpr>(S), Pred, Dst);
  460. break;
  461. case Stmt::ImplicitValueInitExprClass: {
  462. const GRState *state = Pred->getState();
  463. QualType ty = cast<ImplicitValueInitExpr>(S)->getType();
  464. SVal val = svalBuilder.makeZeroVal(ty);
  465. MakeNode(Dst, S, Pred, state->BindExpr(S, val));
  466. break;
  467. }
  468. case Stmt::ExprWithCleanupsClass: {
  469. Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst);
  470. break;
  471. }
  472. // Cases not handled yet; but will handle some day.
  473. case Stmt::DesignatedInitExprClass:
  474. case Stmt::ExtVectorElementExprClass:
  475. case Stmt::ImaginaryLiteralClass:
  476. case Stmt::ObjCAtCatchStmtClass:
  477. case Stmt::ObjCAtFinallyStmtClass:
  478. case Stmt::ObjCAtTryStmtClass:
  479. case Stmt::ObjCAutoreleasePoolStmtClass:
  480. case Stmt::ObjCEncodeExprClass:
  481. case Stmt::ObjCIsaExprClass:
  482. case Stmt::ObjCProtocolExprClass:
  483. case Stmt::ObjCSelectorExprClass:
  484. case Stmt::ObjCStringLiteralClass:
  485. case Stmt::ParenListExprClass:
  486. case Stmt::PredefinedExprClass:
  487. case Stmt::ShuffleVectorExprClass:
  488. case Stmt::VAArgExprClass:
  489. case Stmt::CUDAKernelCallExprClass:
  490. case Stmt::OpaqueValueExprClass:
  491. case Stmt::AsTypeExprClass:
  492. // Fall through.
  493. // Cases we intentionally don't evaluate, since they don't need
  494. // to be explicitly evaluated.
  495. case Stmt::AddrLabelExprClass:
  496. case Stmt::IntegerLiteralClass:
  497. case Stmt::CharacterLiteralClass:
  498. case Stmt::CXXBoolLiteralExprClass:
  499. case Stmt::FloatingLiteralClass:
  500. case Stmt::SizeOfPackExprClass:
  501. case Stmt::CXXNullPtrLiteralExprClass:
  502. Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
  503. break;
  504. case Stmt::ArraySubscriptExprClass:
  505. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  506. break;
  507. case Stmt::AsmStmtClass:
  508. VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
  509. break;
  510. case Stmt::BlockDeclRefExprClass: {
  511. const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S);
  512. VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst);
  513. break;
  514. }
  515. case Stmt::BlockExprClass:
  516. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  517. break;
  518. case Stmt::BinaryOperatorClass: {
  519. const BinaryOperator* B = cast<BinaryOperator>(S);
  520. if (B->isLogicalOp()) {
  521. VisitLogicalExpr(B, Pred, Dst);
  522. break;
  523. }
  524. else if (B->getOpcode() == BO_Comma) {
  525. const GRState* state = Pred->getState();
  526. MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS())));
  527. break;
  528. }
  529. if (AMgr.shouldEagerlyAssume() &&
  530. (B->isRelationalOp() || B->isEqualityOp())) {
  531. ExplodedNodeSet Tmp;
  532. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  533. evalEagerlyAssume(Dst, Tmp, cast<Expr>(S));
  534. }
  535. else
  536. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  537. break;
  538. }
  539. case Stmt::CallExprClass:
  540. case Stmt::CXXOperatorCallExprClass:
  541. case Stmt::CXXMemberCallExprClass: {
  542. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  543. break;
  544. }
  545. case Stmt::CXXConstructExprClass: {
  546. const CXXConstructExpr *C = cast<CXXConstructExpr>(S);
  547. // For block-level CXXConstructExpr, we don't have a destination region.
  548. // Let VisitCXXConstructExpr() create one.
  549. VisitCXXConstructExpr(C, 0, Pred, Dst);
  550. break;
  551. }
  552. case Stmt::CXXNewExprClass: {
  553. const CXXNewExpr *NE = cast<CXXNewExpr>(S);
  554. VisitCXXNewExpr(NE, Pred, Dst);
  555. break;
  556. }
  557. case Stmt::CXXDeleteExprClass: {
  558. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  559. VisitCXXDeleteExpr(CDE, Pred, Dst);
  560. break;
  561. }
  562. // FIXME: ChooseExpr is really a constant. We need to fix
  563. // the CFG do not model them as explicit control-flow.
  564. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  565. const ChooseExpr* C = cast<ChooseExpr>(S);
  566. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  567. break;
  568. }
  569. case Stmt::CompoundAssignOperatorClass:
  570. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  571. break;
  572. case Stmt::CompoundLiteralExprClass:
  573. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  574. break;
  575. case Stmt::BinaryConditionalOperatorClass:
  576. case Stmt::ConditionalOperatorClass: { // '?' operator
  577. const AbstractConditionalOperator *C
  578. = cast<AbstractConditionalOperator>(S);
  579. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  580. break;
  581. }
  582. case Stmt::CXXThisExprClass:
  583. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  584. break;
  585. case Stmt::DeclRefExprClass: {
  586. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  587. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  588. break;
  589. }
  590. case Stmt::DeclStmtClass:
  591. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  592. break;
  593. case Stmt::ImplicitCastExprClass:
  594. case Stmt::CStyleCastExprClass:
  595. case Stmt::CXXStaticCastExprClass:
  596. case Stmt::CXXDynamicCastExprClass:
  597. case Stmt::CXXReinterpretCastExprClass:
  598. case Stmt::CXXConstCastExprClass:
  599. case Stmt::CXXFunctionalCastExprClass:
  600. case Stmt::ObjCBridgedCastExprClass: {
  601. const CastExpr* C = cast<CastExpr>(S);
  602. // Handle the previsit checks.
  603. ExplodedNodeSet dstPrevisit;
  604. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
  605. // Handle the expression itself.
  606. ExplodedNodeSet dstExpr;
  607. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  608. e = dstPrevisit.end(); i != e ; ++i) {
  609. VisitCast(C, C->getSubExpr(), *i, dstExpr);
  610. }
  611. // Handle the postvisit checks.
  612. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  613. break;
  614. }
  615. case Expr::MaterializeTemporaryExprClass: {
  616. const MaterializeTemporaryExpr *Materialize
  617. = cast<MaterializeTemporaryExpr>(S);
  618. if (!Materialize->getType()->isRecordType())
  619. CreateCXXTemporaryObject(Materialize, Pred, Dst);
  620. else
  621. Visit(Materialize->GetTemporaryExpr(), Pred, Dst);
  622. break;
  623. }
  624. case Stmt::InitListExprClass:
  625. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  626. break;
  627. case Stmt::MemberExprClass:
  628. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  629. break;
  630. case Stmt::ObjCIvarRefExprClass:
  631. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  632. break;
  633. case Stmt::ObjCForCollectionStmtClass:
  634. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  635. break;
  636. case Stmt::ObjCMessageExprClass:
  637. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  638. break;
  639. case Stmt::ObjCAtThrowStmtClass: {
  640. // FIXME: This is not complete. We basically treat @throw as
  641. // an abort.
  642. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  643. Builder->BuildSinks = true;
  644. MakeNode(Dst, S, Pred, Pred->getState());
  645. break;
  646. }
  647. case Stmt::ReturnStmtClass:
  648. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  649. break;
  650. case Stmt::OffsetOfExprClass:
  651. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  652. break;
  653. case Stmt::UnaryExprOrTypeTraitExprClass:
  654. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  655. Pred, Dst);
  656. break;
  657. case Stmt::StmtExprClass: {
  658. const StmtExpr* SE = cast<StmtExpr>(S);
  659. if (SE->getSubStmt()->body_empty()) {
  660. // Empty statement expression.
  661. assert(SE->getType() == getContext().VoidTy
  662. && "Empty statement expression must have void type.");
  663. Dst.Add(Pred);
  664. break;
  665. }
  666. if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  667. const GRState* state = Pred->getState();
  668. MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr)));
  669. }
  670. else
  671. Dst.Add(Pred);
  672. break;
  673. }
  674. case Stmt::StringLiteralClass: {
  675. const GRState* state = Pred->getState();
  676. SVal V = state->getLValue(cast<StringLiteral>(S));
  677. MakeNode(Dst, S, Pred, state->BindExpr(S, V));
  678. return;
  679. }
  680. case Stmt::UnaryOperatorClass: {
  681. const UnaryOperator *U = cast<UnaryOperator>(S);
  682. if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) {
  683. ExplodedNodeSet Tmp;
  684. VisitUnaryOperator(U, Pred, Tmp);
  685. evalEagerlyAssume(Dst, Tmp, U);
  686. }
  687. else
  688. VisitUnaryOperator(U, Pred, Dst);
  689. break;
  690. }
  691. }
  692. }
  693. //===----------------------------------------------------------------------===//
  694. // Block entrance. (Update counters).
  695. //===----------------------------------------------------------------------===//
  696. void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
  697. GenericNodeBuilder<BlockEntrance> &nodeBuilder){
  698. // FIXME: Refactor this into a checker.
  699. const CFGBlock *block = nodeBuilder.getProgramPoint().getBlock();
  700. ExplodedNode *pred = nodeBuilder.getPredecessor();
  701. if (nodeBuilder.getBlockCounter().getNumVisited(
  702. pred->getLocationContext()->getCurrentStackFrame(),
  703. block->getBlockID()) >= AMgr.getMaxVisit()) {
  704. static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
  705. nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
  706. }
  707. }
  708. //===----------------------------------------------------------------------===//
  709. // Generic node creation.
  710. //===----------------------------------------------------------------------===//
  711. ExplodedNode* ExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S,
  712. ExplodedNode* Pred, const GRState* St,
  713. ProgramPoint::Kind K,
  714. const ProgramPointTag *tag) {
  715. assert (Builder && "StmtNodeBuilder not present.");
  716. SaveAndRestore<const ProgramPointTag*> OldTag(Builder->Tag);
  717. Builder->Tag = tag;
  718. return Builder->MakeNode(Dst, S, Pred, St, K);
  719. }
  720. //===----------------------------------------------------------------------===//
  721. // Branch processing.
  722. //===----------------------------------------------------------------------===//
  723. const GRState* ExprEngine::MarkBranch(const GRState* state,
  724. const Stmt* Terminator,
  725. bool branchTaken) {
  726. switch (Terminator->getStmtClass()) {
  727. default:
  728. return state;
  729. case Stmt::BinaryOperatorClass: { // '&&' and '||'
  730. const BinaryOperator* B = cast<BinaryOperator>(Terminator);
  731. BinaryOperator::Opcode Op = B->getOpcode();
  732. assert (Op == BO_LAnd || Op == BO_LOr);
  733. // For &&, if we take the true branch, then the value of the whole
  734. // expression is that of the RHS expression.
  735. //
  736. // For ||, if we take the false branch, then the value of the whole
  737. // expression is that of the RHS expression.
  738. const Expr* Ex = (Op == BO_LAnd && branchTaken) ||
  739. (Op == BO_LOr && !branchTaken)
  740. ? B->getRHS() : B->getLHS();
  741. return state->BindExpr(B, UndefinedVal(Ex));
  742. }
  743. case Stmt::BinaryConditionalOperatorClass:
  744. case Stmt::ConditionalOperatorClass: { // ?:
  745. const AbstractConditionalOperator* C
  746. = cast<AbstractConditionalOperator>(Terminator);
  747. // For ?, if branchTaken == true then the value is either the LHS or
  748. // the condition itself. (GNU extension).
  749. const Expr* Ex;
  750. if (branchTaken)
  751. Ex = C->getTrueExpr();
  752. else
  753. Ex = C->getFalseExpr();
  754. return state->BindExpr(C, UndefinedVal(Ex));
  755. }
  756. case Stmt::ChooseExprClass: { // ?:
  757. const ChooseExpr* C = cast<ChooseExpr>(Terminator);
  758. const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS();
  759. return state->BindExpr(C, UndefinedVal(Ex));
  760. }
  761. }
  762. }
  763. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  764. /// to try to recover some path-sensitivity for casts of symbolic
  765. /// integers that promote their values (which are currently not tracked well).
  766. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  767. // cast(s) did was sign-extend the original value.
  768. static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state,
  769. const Stmt* Condition, ASTContext& Ctx) {
  770. const Expr *Ex = dyn_cast<Expr>(Condition);
  771. if (!Ex)
  772. return UnknownVal();
  773. uint64_t bits = 0;
  774. bool bitsInit = false;
  775. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  776. QualType T = CE->getType();
  777. if (!T->isIntegerType())
  778. return UnknownVal();
  779. uint64_t newBits = Ctx.getTypeSize(T);
  780. if (!bitsInit || newBits < bits) {
  781. bitsInit = true;
  782. bits = newBits;
  783. }
  784. Ex = CE->getSubExpr();
  785. }
  786. // We reached a non-cast. Is it a symbolic value?
  787. QualType T = Ex->getType();
  788. if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
  789. return UnknownVal();
  790. return state->getSVal(Ex);
  791. }
  792. void ExprEngine::processBranch(const Stmt* Condition, const Stmt* Term,
  793. BranchNodeBuilder& builder) {
  794. // Check for NULL conditions; e.g. "for(;;)"
  795. if (!Condition) {
  796. builder.markInfeasible(false);
  797. return;
  798. }
  799. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  800. Condition->getLocStart(),
  801. "Error evaluating branch");
  802. getCheckerManager().runCheckersForBranchCondition(Condition, builder, *this);
  803. // If the branch condition is undefined, return;
  804. if (!builder.isFeasible(true) && !builder.isFeasible(false))
  805. return;
  806. const GRState* PrevState = builder.getState();
  807. SVal X = PrevState->getSVal(Condition);
  808. if (X.isUnknownOrUndef()) {
  809. // Give it a chance to recover from unknown.
  810. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  811. if (Ex->getType()->isIntegerType()) {
  812. // Try to recover some path-sensitivity. Right now casts of symbolic
  813. // integers that promote their values are currently not tracked well.
  814. // If 'Condition' is such an expression, try and recover the
  815. // underlying value and use that instead.
  816. SVal recovered = RecoverCastedSymbol(getStateManager(),
  817. builder.getState(), Condition,
  818. getContext());
  819. if (!recovered.isUnknown()) {
  820. X = recovered;
  821. }
  822. }
  823. }
  824. // If the condition is still unknown, give up.
  825. if (X.isUnknownOrUndef()) {
  826. builder.generateNode(MarkBranch(PrevState, Term, true), true);
  827. builder.generateNode(MarkBranch(PrevState, Term, false), false);
  828. return;
  829. }
  830. }
  831. DefinedSVal V = cast<DefinedSVal>(X);
  832. // Process the true branch.
  833. if (builder.isFeasible(true)) {
  834. if (const GRState *state = PrevState->assume(V, true))
  835. builder.generateNode(MarkBranch(state, Term, true), true);
  836. else
  837. builder.markInfeasible(true);
  838. }
  839. // Process the false branch.
  840. if (builder.isFeasible(false)) {
  841. if (const GRState *state = PrevState->assume(V, false))
  842. builder.generateNode(MarkBranch(state, Term, false), false);
  843. else
  844. builder.markInfeasible(false);
  845. }
  846. }
  847. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  848. /// nodes by processing the 'effects' of a computed goto jump.
  849. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  850. const GRState *state = builder.getState();
  851. SVal V = state->getSVal(builder.getTarget());
  852. // Three possibilities:
  853. //
  854. // (1) We know the computed label.
  855. // (2) The label is NULL (or some other constant), or Undefined.
  856. // (3) We have no clue about the label. Dispatch to all targets.
  857. //
  858. typedef IndirectGotoNodeBuilder::iterator iterator;
  859. if (isa<loc::GotoLabel>(V)) {
  860. const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
  861. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  862. if (I.getLabel() == L) {
  863. builder.generateNode(I, state);
  864. return;
  865. }
  866. }
  867. assert(false && "No block with label.");
  868. return;
  869. }
  870. if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
  871. // Dispatch to the first target and mark it as a sink.
  872. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  873. // FIXME: add checker visit.
  874. // UndefBranches.insert(N);
  875. return;
  876. }
  877. // This is really a catch-all. We don't support symbolics yet.
  878. // FIXME: Implement dispatch for symbolic pointers.
  879. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  880. builder.generateNode(I, state);
  881. }
  882. void ExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L,
  883. const Expr* R,
  884. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  885. assert(Ex == currentStmt &&
  886. Pred->getLocationContext()->getCFG()->isBlkExpr(Ex));
  887. const GRState* state = Pred->getState();
  888. SVal X = state->getSVal(Ex);
  889. assert (X.isUndef());
  890. const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
  891. assert(SE);
  892. X = state->getSVal(SE);
  893. // Make sure that we invalidate the previous binding.
  894. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true));
  895. }
  896. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  897. /// nodes when the control reaches the end of a function.
  898. void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) {
  899. getTF().evalEndPath(*this, builder);
  900. StateMgr.EndPath(builder.getState());
  901. getCheckerManager().runCheckersForEndPath(builder, *this);
  902. }
  903. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  904. /// nodes by processing the 'effects' of a switch statement.
  905. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  906. typedef SwitchNodeBuilder::iterator iterator;
  907. const GRState* state = builder.getState();
  908. const Expr* CondE = builder.getCondition();
  909. SVal CondV_untested = state->getSVal(CondE);
  910. if (CondV_untested.isUndef()) {
  911. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  912. // FIXME: add checker
  913. //UndefBranches.insert(N);
  914. return;
  915. }
  916. DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
  917. const GRState *DefaultSt = state;
  918. iterator I = builder.begin(), EI = builder.end();
  919. bool defaultIsFeasible = I == EI;
  920. for ( ; I != EI; ++I) {
  921. // Successor may be pruned out during CFG construction.
  922. if (!I.getBlock())
  923. continue;
  924. const CaseStmt* Case = I.getCase();
  925. // Evaluate the LHS of the case value.
  926. Expr::EvalResult V1;
  927. bool b = Case->getLHS()->Evaluate(V1, getContext());
  928. // Sanity checks. These go away in Release builds.
  929. assert(b && V1.Val.isInt() && !V1.HasSideEffects
  930. && "Case condition must evaluate to an integer constant.");
  931. (void)b; // silence unused variable warning
  932. assert(V1.Val.getInt().getBitWidth() ==
  933. getContext().getTypeSize(CondE->getType()));
  934. // Get the RHS of the case, if it exists.
  935. Expr::EvalResult V2;
  936. if (const Expr* E = Case->getRHS()) {
  937. b = E->Evaluate(V2, getContext());
  938. assert(b && V2.Val.isInt() && !V2.HasSideEffects
  939. && "Case condition must evaluate to an integer constant.");
  940. (void)b; // silence unused variable warning
  941. }
  942. else
  943. V2 = V1;
  944. // FIXME: Eventually we should replace the logic below with a range
  945. // comparison, rather than concretize the values within the range.
  946. // This should be easy once we have "ranges" for NonLVals.
  947. do {
  948. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt()));
  949. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  950. CondV, CaseVal);
  951. // Now "assume" that the case matches.
  952. if (const GRState* stateNew = state->assume(Res, true)) {
  953. builder.generateCaseStmtNode(I, stateNew);
  954. // If CondV evaluates to a constant, then we know that this
  955. // is the *only* case that we can take, so stop evaluating the
  956. // others.
  957. if (isa<nonloc::ConcreteInt>(CondV))
  958. return;
  959. }
  960. // Now "assume" that the case doesn't match. Add this state
  961. // to the default state (if it is feasible).
  962. if (DefaultSt) {
  963. if (const GRState *stateNew = DefaultSt->assume(Res, false)) {
  964. defaultIsFeasible = true;
  965. DefaultSt = stateNew;
  966. }
  967. else {
  968. defaultIsFeasible = false;
  969. DefaultSt = NULL;
  970. }
  971. }
  972. // Concretize the next value in the range.
  973. if (V1.Val.getInt() == V2.Val.getInt())
  974. break;
  975. ++V1.Val.getInt();
  976. assert (V1.Val.getInt() <= V2.Val.getInt());
  977. } while (true);
  978. }
  979. if (!defaultIsFeasible)
  980. return;
  981. // If we have switch(enum value), the default branch is not
  982. // feasible if all of the enum constants not covered by 'case:' statements
  983. // are not feasible values for the switch condition.
  984. //
  985. // Note that this isn't as accurate as it could be. Even if there isn't
  986. // a case for a particular enum value as long as that enum value isn't
  987. // feasible then it shouldn't be considered for making 'default:' reachable.
  988. const SwitchStmt *SS = builder.getSwitch();
  989. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  990. if (CondExpr->getType()->getAs<EnumType>()) {
  991. if (SS->isAllEnumCasesCovered())
  992. return;
  993. }
  994. builder.generateDefaultCaseNode(DefaultSt);
  995. }
  996. void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) {
  997. const GRState *state = B.getState()->enterStackFrame(B.getCalleeContext());
  998. B.generateNode(state);
  999. }
  1000. void ExprEngine::processCallExit(CallExitNodeBuilder &B) {
  1001. const GRState *state = B.getState();
  1002. const ExplodedNode *Pred = B.getPredecessor();
  1003. const StackFrameContext *calleeCtx =
  1004. cast<StackFrameContext>(Pred->getLocationContext());
  1005. const Stmt *CE = calleeCtx->getCallSite();
  1006. // If the callee returns an expression, bind its value to CallExpr.
  1007. const Stmt *ReturnedExpr = state->get<ReturnExpr>();
  1008. if (ReturnedExpr) {
  1009. SVal RetVal = state->getSVal(ReturnedExpr);
  1010. state = state->BindExpr(CE, RetVal);
  1011. // Clear the return expr GDM.
  1012. state = state->remove<ReturnExpr>();
  1013. }
  1014. // Bind the constructed object value to CXXConstructExpr.
  1015. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
  1016. const CXXThisRegion *ThisR =
  1017. getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx);
  1018. SVal ThisV = state->getSVal(ThisR);
  1019. // Always bind the region to the CXXConstructExpr.
  1020. state = state->BindExpr(CCE, ThisV);
  1021. }
  1022. B.generateNode(state);
  1023. }
  1024. //===----------------------------------------------------------------------===//
  1025. // Transfer functions: logical operations ('&&', '||').
  1026. //===----------------------------------------------------------------------===//
  1027. void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred,
  1028. ExplodedNodeSet& Dst) {
  1029. assert(B->getOpcode() == BO_LAnd ||
  1030. B->getOpcode() == BO_LOr);
  1031. assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B));
  1032. const GRState* state = Pred->getState();
  1033. SVal X = state->getSVal(B);
  1034. assert(X.isUndef());
  1035. const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
  1036. assert(Ex);
  1037. if (Ex == B->getRHS()) {
  1038. X = state->getSVal(Ex);
  1039. // Handle undefined values.
  1040. if (X.isUndef()) {
  1041. MakeNode(Dst, B, Pred, state->BindExpr(B, X));
  1042. return;
  1043. }
  1044. DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
  1045. // We took the RHS. Because the value of the '&&' or '||' expression must
  1046. // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
  1047. // or 1. Alternatively, we could take a lazy approach, and calculate this
  1048. // value later when necessary. We don't have the machinery in place for
  1049. // this right now, and since most logical expressions are used for branches,
  1050. // the payoff is not likely to be large. Instead, we do eager evaluation.
  1051. if (const GRState *newState = state->assume(XD, true))
  1052. MakeNode(Dst, B, Pred,
  1053. newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType())));
  1054. if (const GRState *newState = state->assume(XD, false))
  1055. MakeNode(Dst, B, Pred,
  1056. newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType())));
  1057. }
  1058. else {
  1059. // We took the LHS expression. Depending on whether we are '&&' or
  1060. // '||' we know what the value of the expression is via properties of
  1061. // the short-circuiting.
  1062. X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
  1063. B->getType());
  1064. MakeNode(Dst, B, Pred, state->BindExpr(B, X));
  1065. }
  1066. }
  1067. //===----------------------------------------------------------------------===//
  1068. // Transfer functions: Loads and stores.
  1069. //===----------------------------------------------------------------------===//
  1070. void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
  1071. ExplodedNodeSet &Dst) {
  1072. ExplodedNodeSet Tmp;
  1073. CanQualType T = getContext().getCanonicalType(BE->getType());
  1074. SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
  1075. Pred->getLocationContext());
  1076. MakeNode(Tmp, BE, Pred, Pred->getState()->BindExpr(BE, V),
  1077. ProgramPoint::PostLValueKind);
  1078. // Post-visit the BlockExpr.
  1079. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
  1080. }
  1081. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1082. ExplodedNode *Pred,
  1083. ExplodedNodeSet &Dst) {
  1084. const GRState *state = Pred->getState();
  1085. if (const VarDecl* VD = dyn_cast<VarDecl>(D)) {
  1086. assert(Ex->isLValue());
  1087. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1088. // For references, the 'lvalue' is the pointer address stored in the
  1089. // reference region.
  1090. if (VD->getType()->isReferenceType()) {
  1091. if (const MemRegion *R = V.getAsRegion())
  1092. V = state->getSVal(R);
  1093. else
  1094. V = UnknownVal();
  1095. }
  1096. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
  1097. ProgramPoint::PostLValueKind);
  1098. return;
  1099. }
  1100. if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) {
  1101. assert(!Ex->isLValue());
  1102. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1103. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V));
  1104. return;
  1105. }
  1106. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) {
  1107. SVal V = svalBuilder.getFunctionPointer(FD);
  1108. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
  1109. ProgramPoint::PostLValueKind);
  1110. return;
  1111. }
  1112. assert (false &&
  1113. "ValueDecl support for this ValueDecl not implemented.");
  1114. }
  1115. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1116. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A,
  1117. ExplodedNode* Pred,
  1118. ExplodedNodeSet& Dst){
  1119. const Expr* Base = A->getBase()->IgnoreParens();
  1120. const Expr* Idx = A->getIdx()->IgnoreParens();
  1121. ExplodedNodeSet checkerPreStmt;
  1122. getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
  1123. for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
  1124. ei = checkerPreStmt.end(); it != ei; ++it) {
  1125. const GRState* state = (*it)->getState();
  1126. SVal V = state->getLValue(A->getType(), state->getSVal(Idx),
  1127. state->getSVal(Base));
  1128. assert(A->isLValue());
  1129. MakeNode(Dst, A, *it, state->BindExpr(A, V), ProgramPoint::PostLValueKind);
  1130. }
  1131. }
  1132. /// VisitMemberExpr - Transfer function for member expressions.
  1133. void ExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode *Pred,
  1134. ExplodedNodeSet& Dst) {
  1135. FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl());
  1136. if (!field) // FIXME: skipping member expressions for non-fields
  1137. return;
  1138. Expr *baseExpr = M->getBase()->IgnoreParens();
  1139. const GRState* state = Pred->getState();
  1140. SVal baseExprVal = state->getSVal(baseExpr);
  1141. if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
  1142. isa<nonloc::CompoundVal>(baseExprVal) ||
  1143. // FIXME: This can originate by conjuring a symbol for an unknown
  1144. // temporary struct object, see test/Analysis/fields.c:
  1145. // (p = getit()).x
  1146. isa<nonloc::SymbolVal>(baseExprVal)) {
  1147. MakeNode(Dst, M, Pred, state->BindExpr(M, UnknownVal()));
  1148. return;
  1149. }
  1150. // FIXME: Should we insert some assumption logic in here to determine
  1151. // if "Base" is a valid piece of memory? Before we put this assumption
  1152. // later when using FieldOffset lvals (which we no longer have).
  1153. // For all other cases, compute an lvalue.
  1154. SVal L = state->getLValue(field, baseExprVal);
  1155. if (M->isLValue())
  1156. MakeNode(Dst, M, Pred, state->BindExpr(M, L), ProgramPoint::PostLValueKind);
  1157. else
  1158. evalLoad(Dst, M, Pred, state, L);
  1159. }
  1160. /// evalBind - Handle the semantics of binding a value to a specific location.
  1161. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1162. void ExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE,
  1163. ExplodedNode* Pred, const GRState* state,
  1164. SVal location, SVal Val, bool atDeclInit) {
  1165. // Do a previsit of the bind.
  1166. ExplodedNodeSet CheckedSet, Src;
  1167. Src.Add(Pred);
  1168. getCheckerManager().runCheckersForBind(CheckedSet, Src, location, Val, StoreE,
  1169. *this);
  1170. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1171. I!=E; ++I) {
  1172. if (Pred != *I)
  1173. state = (*I)->getState();
  1174. const GRState* newState = 0;
  1175. if (atDeclInit) {
  1176. const VarRegion *VR =
  1177. cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
  1178. newState = state->bindDecl(VR, Val);
  1179. }
  1180. else {
  1181. if (location.isUnknown()) {
  1182. // We know that the new state will be the same as the old state since
  1183. // the location of the binding is "unknown". Consequently, there
  1184. // is no reason to just create a new node.
  1185. newState = state;
  1186. }
  1187. else {
  1188. // We are binding to a value other than 'unknown'. Perform the binding
  1189. // using the StoreManager.
  1190. newState = state->bindLoc(cast<Loc>(location), Val);
  1191. }
  1192. }
  1193. // The next thing to do is check if the TransferFuncs object wants to
  1194. // update the state based on the new binding. If the GRTransferFunc object
  1195. // doesn't do anything, just auto-propagate the current state.
  1196. // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE'
  1197. // is non-NULL. Checkers typically care about
  1198. StmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE,
  1199. true);
  1200. getTF().evalBind(BuilderRef, location, Val);
  1201. }
  1202. }
  1203. /// evalStore - Handle the semantics of a store via an assignment.
  1204. /// @param Dst The node set to store generated state nodes
  1205. /// @param AssignE The assignment expression if the store happens in an
  1206. /// assignment.
  1207. /// @param LocatioinE The location expression that is stored to.
  1208. /// @param state The current simulation state
  1209. /// @param location The location to store the value
  1210. /// @param Val The value to be stored
  1211. void ExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE,
  1212. const Expr* LocationE,
  1213. ExplodedNode* Pred,
  1214. const GRState* state, SVal location, SVal Val,
  1215. const ProgramPointTag *tag) {
  1216. assert(Builder && "StmtNodeBuilder must be defined.");
  1217. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1218. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1219. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1220. if (isa<loc::ObjCPropRef>(location)) {
  1221. loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
  1222. return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(),
  1223. StoreE, Val), Pred, Dst);
  1224. }
  1225. // Evaluate the location (checks for bad dereferences).
  1226. ExplodedNodeSet Tmp;
  1227. evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
  1228. if (Tmp.empty())
  1229. return;
  1230. if (location.isUndef())
  1231. return;
  1232. SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind,
  1233. ProgramPoint::PostStoreKind);
  1234. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1235. evalBind(Dst, StoreE, *NI, (*NI)->getState(), location, Val);
  1236. }
  1237. void ExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex,
  1238. ExplodedNode* Pred,
  1239. const GRState* state, SVal location,
  1240. const ProgramPointTag *tag, QualType LoadTy) {
  1241. assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
  1242. if (isa<loc::ObjCPropRef>(location)) {
  1243. loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
  1244. return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex),
  1245. Pred, Dst);
  1246. }
  1247. // Are we loading from a region? This actually results in two loads; one
  1248. // to fetch the address of the referenced value and one to fetch the
  1249. // referenced value.
  1250. if (const TypedValueRegion *TR =
  1251. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  1252. QualType ValTy = TR->getValueType();
  1253. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1254. static SimpleProgramPointTag
  1255. loadReferenceTag("ExprEngine : Load Reference");
  1256. ExplodedNodeSet Tmp;
  1257. evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
  1258. getContext().getPointerType(RT->getPointeeType()));
  1259. // Perform the load from the referenced value.
  1260. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1261. state = (*I)->getState();
  1262. location = state->getSVal(Ex);
  1263. evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
  1264. }
  1265. return;
  1266. }
  1267. }
  1268. evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
  1269. }
  1270. void ExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex,
  1271. ExplodedNode* Pred,
  1272. const GRState* state, SVal location,
  1273. const ProgramPointTag *tag, QualType LoadTy) {
  1274. // Evaluate the location (checks for bad dereferences).
  1275. ExplodedNodeSet Tmp;
  1276. evalLocation(Tmp, Ex, Pred, state, location, tag, true);
  1277. if (Tmp.empty())
  1278. return;
  1279. if (location.isUndef())
  1280. return;
  1281. SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind);
  1282. // Proceed with the load.
  1283. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1284. state = (*NI)->getState();
  1285. if (location.isUnknown()) {
  1286. // This is important. We must nuke the old binding.
  1287. MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()),
  1288. ProgramPoint::PostLoadKind, tag);
  1289. }
  1290. else {
  1291. if (LoadTy.isNull())
  1292. LoadTy = Ex->getType();
  1293. SVal V = state->getSVal(cast<Loc>(location), LoadTy);
  1294. MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V),
  1295. ProgramPoint::PostLoadKind, tag);
  1296. }
  1297. }
  1298. }
  1299. void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
  1300. ExplodedNode* Pred,
  1301. const GRState* state, SVal location,
  1302. const ProgramPointTag *tag, bool isLoad) {
  1303. // Early checks for performance reason.
  1304. if (location.isUnknown()) {
  1305. Dst.Add(Pred);
  1306. return;
  1307. }
  1308. ExplodedNodeSet Src;
  1309. if (Pred->getState() == state) {
  1310. Src.Add(Pred);
  1311. } else {
  1312. // Associate this new state with an ExplodedNode.
  1313. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  1314. // int *p;
  1315. // p = 0;
  1316. // *p = 0xDEADBEEF;
  1317. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  1318. // instead "int *p" is noted as
  1319. // "Variable 'p' initialized to a null pointer value"
  1320. // FIXME: why is 'tag' not used instead of etag?
  1321. static SimpleProgramPointTag etag("ExprEngine: Location");
  1322. ExplodedNode *N = Builder->generateNode(S, state, Pred, &etag);
  1323. Src.Add(N ? N : Pred);
  1324. }
  1325. getCheckerManager().runCheckersForLocation(Dst, Src, location, isLoad, S,
  1326. *this);
  1327. }
  1328. bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE,
  1329. ExplodedNode *Pred) {
  1330. return false;
  1331. // Inlining isn't correct right now because we:
  1332. // (a) don't generate CallExit nodes.
  1333. // (b) we need a way to postpone doing post-visits of CallExprs until
  1334. // the CallExit. This means we need CallExits for the non-inline
  1335. // cases as well.
  1336. #if 0
  1337. const GRState *state = Pred->getState();
  1338. const Expr *Callee = CE->getCallee();
  1339. SVal L = state->getSVal(Callee);
  1340. const FunctionDecl *FD = L.getAsFunctionDecl();
  1341. if (!FD)
  1342. return false;
  1343. // Specially handle CXXMethods.
  1344. const CXXMethodDecl *methodDecl = 0;
  1345. switch (CE->getStmtClass()) {
  1346. default: break;
  1347. case Stmt::CXXOperatorCallExprClass: {
  1348. const CXXOperatorCallExpr *opCall = cast<CXXOperatorCallExpr>(CE);
  1349. methodDecl =
  1350. dyn_cast_or_null<CXXMethodDecl>(opCall->getCalleeDecl());
  1351. break;
  1352. }
  1353. case Stmt::CXXMemberCallExprClass: {
  1354. const CXXMemberCallExpr *memberCall = cast<CXXMemberCallExpr>(CE);
  1355. const MemberExpr *memberExpr =
  1356. cast<MemberExpr>(memberCall->getCallee()->IgnoreParens());
  1357. methodDecl = cast<CXXMethodDecl>(memberExpr->getMemberDecl());
  1358. break;
  1359. }
  1360. }
  1361. // Check if the function definition is in the same translation unit.
  1362. if (FD->hasBody(FD)) {
  1363. const StackFrameContext *stackFrame =
  1364. AMgr.getStackFrame(AMgr.getAnalysisContext(FD),
  1365. Pred->getLocationContext(),
  1366. CE, Builder->getBlock(), Builder->getIndex());
  1367. // Now we have the definition of the callee, create a CallEnter node.
  1368. CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
  1369. ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
  1370. Dst.Add(N);
  1371. return true;
  1372. }
  1373. // Check if we can find the function definition in other translation units.
  1374. if (AMgr.hasIndexer()) {
  1375. AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD);
  1376. if (C == 0)
  1377. return false;
  1378. const StackFrameContext *stackFrame =
  1379. AMgr.getStackFrame(C, Pred->getLocationContext(),
  1380. CE, Builder->getBlock(), Builder->getIndex());
  1381. CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
  1382. ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
  1383. Dst.Add(N);
  1384. return true;
  1385. }
  1386. // Generate the CallExit node.
  1387. return false;
  1388. #endif
  1389. }
  1390. void ExprEngine::VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred,
  1391. ExplodedNodeSet& dst) {
  1392. // Perform the previsit of the CallExpr.
  1393. ExplodedNodeSet dstPreVisit;
  1394. getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
  1395. // Now evaluate the call itself.
  1396. class DefaultEval : public GraphExpander {
  1397. ExprEngine &Eng;
  1398. const CallExpr *CE;
  1399. public:
  1400. DefaultEval(ExprEngine &eng, const CallExpr *ce)
  1401. : Eng(eng), CE(ce) {}
  1402. virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) {
  1403. // Should we inline the call?
  1404. if (Eng.getAnalysisManager().shouldInlineCall() &&
  1405. Eng.InlineCall(Dst, CE, Pred)) {
  1406. return;
  1407. }
  1408. StmtNodeBuilder &Builder = Eng.getBuilder();
  1409. assert(&Builder && "StmtNodeBuilder must be defined.");
  1410. // Dispatch to the plug-in transfer function.
  1411. unsigned oldSize = Dst.size();
  1412. SaveOr OldHasGen(Builder.hasGeneratedNode);
  1413. // Dispatch to transfer function logic to handle the call itself.
  1414. const Expr* Callee = CE->getCallee()->IgnoreParens();
  1415. const GRState* state = Pred->getState();
  1416. SVal L = state->getSVal(Callee);
  1417. Eng.getTF().evalCall(Dst, Eng, Builder, CE, L, Pred);
  1418. // Handle the case where no nodes where generated. Auto-generate that
  1419. // contains the updated state if we aren't generating sinks.
  1420. if (!Builder.BuildSinks && Dst.size() == oldSize &&
  1421. !Builder.hasGeneratedNode)
  1422. Eng.MakeNode(Dst, CE, Pred, state);
  1423. }
  1424. };
  1425. // Finally, evaluate the function call. We try each of the checkers
  1426. // to see if the can evaluate the function call.
  1427. ExplodedNodeSet dstCallEvaluated;
  1428. DefaultEval defEval(*this, CE);
  1429. getCheckerManager().runCheckersForEvalCall(dstCallEvaluated,
  1430. dstPreVisit,
  1431. CE, *this, &defEval);
  1432. // Finally, perform the post-condition check of the CallExpr and store
  1433. // the created nodes in 'Dst'.
  1434. getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
  1435. *this);
  1436. }
  1437. //===----------------------------------------------------------------------===//
  1438. // Transfer function: Objective-C dot-syntax to access a property.
  1439. //===----------------------------------------------------------------------===//
  1440. void ExprEngine::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Ex,
  1441. ExplodedNode *Pred,
  1442. ExplodedNodeSet &Dst) {
  1443. MakeNode(Dst, Ex, Pred, Pred->getState()->BindExpr(Ex, loc::ObjCPropRef(Ex)));
  1444. }
  1445. //===----------------------------------------------------------------------===//
  1446. // Transfer function: Objective-C ivar references.
  1447. //===----------------------------------------------------------------------===//
  1448. static std::pair<const void*,const void*> EagerlyAssumeTag
  1449. = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0));
  1450. void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
  1451. const Expr *Ex) {
  1452. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1453. ExplodedNode *Pred = *I;
  1454. // Test if the previous node was as the same expression. This can happen
  1455. // when the expression fails to evaluate to anything meaningful and
  1456. // (as an optimization) we don't generate a node.
  1457. ProgramPoint P = Pred->getLocation();
  1458. if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
  1459. Dst.Add(Pred);
  1460. continue;
  1461. }
  1462. const GRState* state = Pred->getState();
  1463. SVal V = state->getSVal(Ex);
  1464. if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) {
  1465. // First assume that the condition is true.
  1466. if (const GRState *stateTrue = state->assume(*SEV, true)) {
  1467. stateTrue = stateTrue->BindExpr(Ex,
  1468. svalBuilder.makeIntVal(1U, Ex->getType()));
  1469. Dst.Add(Builder->generateNode(PostStmtCustom(Ex,
  1470. &EagerlyAssumeTag, Pred->getLocationContext()),
  1471. stateTrue, Pred));
  1472. }
  1473. // Next, assume that the condition is false.
  1474. if (const GRState *stateFalse = state->assume(*SEV, false)) {
  1475. stateFalse = stateFalse->BindExpr(Ex,
  1476. svalBuilder.makeIntVal(0U, Ex->getType()));
  1477. Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag,
  1478. Pred->getLocationContext()),
  1479. stateFalse, Pred));
  1480. }
  1481. }
  1482. else
  1483. Dst.Add(Pred);
  1484. }
  1485. }
  1486. //===----------------------------------------------------------------------===//
  1487. // Transfer function: Objective-C @synchronized.
  1488. //===----------------------------------------------------------------------===//
  1489. void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
  1490. ExplodedNode *Pred,
  1491. ExplodedNodeSet &Dst) {
  1492. getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
  1493. }
  1494. //===----------------------------------------------------------------------===//
  1495. // Transfer function: Objective-C ivar references.
  1496. //===----------------------------------------------------------------------===//
  1497. void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex,
  1498. ExplodedNode* Pred,
  1499. ExplodedNodeSet& Dst) {
  1500. const GRState *state = Pred->getState();
  1501. SVal baseVal = state->getSVal(Ex->getBase());
  1502. SVal location = state->getLValue(Ex->getDecl(), baseVal);
  1503. ExplodedNodeSet dstIvar;
  1504. MakeNode(dstIvar, Ex, Pred, state->BindExpr(Ex, location));
  1505. // Perform the post-condition check of the ObjCIvarRefExpr and store
  1506. // the created nodes in 'Dst'.
  1507. getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
  1508. }
  1509. //===----------------------------------------------------------------------===//
  1510. // Transfer function: Objective-C fast enumeration 'for' statements.
  1511. //===----------------------------------------------------------------------===//
  1512. void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S,
  1513. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  1514. // ObjCForCollectionStmts are processed in two places. This method
  1515. // handles the case where an ObjCForCollectionStmt* occurs as one of the
  1516. // statements within a basic block. This transfer function does two things:
  1517. //
  1518. // (1) binds the next container value to 'element'. This creates a new
  1519. // node in the ExplodedGraph.
  1520. //
  1521. // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
  1522. // whether or not the container has any more elements. This value
  1523. // will be tested in ProcessBranch. We need to explicitly bind
  1524. // this value because a container can contain nil elements.
  1525. //
  1526. // FIXME: Eventually this logic should actually do dispatches to
  1527. // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
  1528. // This will require simulating a temporary NSFastEnumerationState, either
  1529. // through an SVal or through the use of MemRegions. This value can
  1530. // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
  1531. // terminates we reclaim the temporary (it goes out of scope) and we
  1532. // we can test if the SVal is 0 or if the MemRegion is null (depending
  1533. // on what approach we take).
  1534. //
  1535. // For now: simulate (1) by assigning either a symbol or nil if the
  1536. // container is empty. Thus this transfer function will by default
  1537. // result in state splitting.
  1538. const Stmt* elem = S->getElement();
  1539. const GRState *state = Pred->getState();
  1540. SVal elementV;
  1541. if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) {
  1542. const VarDecl* elemD = cast<VarDecl>(DS->getSingleDecl());
  1543. assert(elemD->getInit() == 0);
  1544. elementV = state->getLValue(elemD, Pred->getLocationContext());
  1545. }
  1546. else {
  1547. elementV = state->getSVal(elem);
  1548. }
  1549. ExplodedNodeSet dstLocation;
  1550. evalLocation(dstLocation, elem, Pred, state, elementV, NULL, false);
  1551. if (dstLocation.empty())
  1552. return;
  1553. for (ExplodedNodeSet::iterator NI = dstLocation.begin(),
  1554. NE = dstLocation.end(); NI!=NE; ++NI) {
  1555. Pred = *NI;
  1556. const GRState *state = Pred->getState();
  1557. // Handle the case where the container still has elements.
  1558. SVal TrueV = svalBuilder.makeTruthVal(1);
  1559. const GRState *hasElems = state->BindExpr(S, TrueV);
  1560. // Handle the case where the container has no elements.
  1561. SVal FalseV = svalBuilder.makeTruthVal(0);
  1562. const GRState *noElems = state->BindExpr(S, FalseV);
  1563. if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV))
  1564. if (const TypedValueRegion *R =
  1565. dyn_cast<TypedValueRegion>(MV->getRegion())) {
  1566. // FIXME: The proper thing to do is to really iterate over the
  1567. // container. We will do this with dispatch logic to the store.
  1568. // For now, just 'conjure' up a symbolic value.
  1569. QualType T = R->getValueType();
  1570. assert(Loc::isLocType(T));
  1571. unsigned Count = Builder->getCurrentBlockCount();
  1572. SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count);
  1573. SVal V = svalBuilder.makeLoc(Sym);
  1574. hasElems = hasElems->bindLoc(elementV, V);
  1575. // Bind the location to 'nil' on the false branch.
  1576. SVal nilV = svalBuilder.makeIntVal(0, T);
  1577. noElems = noElems->bindLoc(elementV, nilV);
  1578. }
  1579. // Create the new nodes.
  1580. MakeNode(Dst, S, Pred, hasElems);
  1581. MakeNode(Dst, S, Pred, noElems);
  1582. }
  1583. }
  1584. //===----------------------------------------------------------------------===//
  1585. // Transfer function: Objective-C message expressions.
  1586. //===----------------------------------------------------------------------===//
  1587. void ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
  1588. ExplodedNode *Pred, ExplodedNodeSet& Dst) {
  1589. // Handle the previsits checks.
  1590. ExplodedNodeSet dstPrevisit;
  1591. getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
  1592. msg, *this);
  1593. // Proceed with evaluate the message expression.
  1594. ExplodedNodeSet dstEval;
  1595. for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(),
  1596. DE = dstPrevisit.end(); DI != DE; ++DI) {
  1597. ExplodedNode *Pred = *DI;
  1598. bool RaisesException = false;
  1599. unsigned oldSize = dstEval.size();
  1600. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  1601. SaveOr OldHasGen(Builder->hasGeneratedNode);
  1602. if (const Expr *Receiver = msg.getInstanceReceiver()) {
  1603. const GRState *state = Pred->getState();
  1604. SVal recVal = state->getSVal(Receiver);
  1605. if (!recVal.isUndef()) {
  1606. // Bifurcate the state into nil and non-nil ones.
  1607. DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
  1608. const GRState *notNilState, *nilState;
  1609. llvm::tie(notNilState, nilState) = state->assume(receiverVal);
  1610. // There are three cases: can be nil or non-nil, must be nil, must be
  1611. // non-nil. We ignore must be nil, and merge the rest two into non-nil.
  1612. if (nilState && !notNilState) {
  1613. dstEval.insert(Pred);
  1614. continue;
  1615. }
  1616. // Check if the "raise" message was sent.
  1617. assert(notNilState);
  1618. if (msg.getSelector() == RaiseSel)
  1619. RaisesException = true;
  1620. // Check if we raise an exception. For now treat these as sinks.
  1621. // Eventually we will want to handle exceptions properly.
  1622. if (RaisesException)
  1623. Builder->BuildSinks = true;
  1624. // Dispatch to plug-in transfer function.
  1625. evalObjCMessage(dstEval, msg, Pred, notNilState);
  1626. }
  1627. }
  1628. else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
  1629. IdentifierInfo* ClsName = Iface->getIdentifier();
  1630. Selector S = msg.getSelector();
  1631. // Check for special instance methods.
  1632. if (!NSExceptionII) {
  1633. ASTContext& Ctx = getContext();
  1634. NSExceptionII = &Ctx.Idents.get("NSException");
  1635. }
  1636. if (ClsName == NSExceptionII) {
  1637. enum { NUM_RAISE_SELECTORS = 2 };
  1638. // Lazily create a cache of the selectors.
  1639. if (!NSExceptionInstanceRaiseSelectors) {
  1640. ASTContext& Ctx = getContext();
  1641. NSExceptionInstanceRaiseSelectors =
  1642. new Selector[NUM_RAISE_SELECTORS];
  1643. SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
  1644. unsigned idx = 0;
  1645. // raise:format:
  1646. II.push_back(&Ctx.Idents.get("raise"));
  1647. II.push_back(&Ctx.Idents.get("format"));
  1648. NSExceptionInstanceRaiseSelectors[idx++] =
  1649. Ctx.Selectors.getSelector(II.size(), &II[0]);
  1650. // raise:format::arguments:
  1651. II.push_back(&Ctx.Idents.get("arguments"));
  1652. NSExceptionInstanceRaiseSelectors[idx++] =
  1653. Ctx.Selectors.getSelector(II.size(), &II[0]);
  1654. }
  1655. for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i)
  1656. if (S == NSExceptionInstanceRaiseSelectors[i]) {
  1657. RaisesException = true;
  1658. break;
  1659. }
  1660. }
  1661. // Check if we raise an exception. For now treat these as sinks.
  1662. // Eventually we will want to handle exceptions properly.
  1663. if (RaisesException)
  1664. Builder->BuildSinks = true;
  1665. // Dispatch to plug-in transfer function.
  1666. evalObjCMessage(dstEval, msg, Pred, Pred->getState());
  1667. }
  1668. // Handle the case where no nodes where generated. Auto-generate that
  1669. // contains the updated state if we aren't generating sinks.
  1670. if (!Builder->BuildSinks && dstEval.size() == oldSize &&
  1671. !Builder->hasGeneratedNode)
  1672. MakeNode(dstEval, msg.getOriginExpr(), Pred, Pred->getState());
  1673. }
  1674. // Finally, perform the post-condition check of the ObjCMessageExpr and store
  1675. // the created nodes in 'Dst'.
  1676. getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this);
  1677. }
  1678. //===----------------------------------------------------------------------===//
  1679. // Transfer functions: Miscellaneous statements.
  1680. //===----------------------------------------------------------------------===//
  1681. void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
  1682. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  1683. ExplodedNodeSet dstPreStmt;
  1684. getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
  1685. if (CastE->getCastKind() == CK_LValueToRValue ||
  1686. CastE->getCastKind() == CK_GetObjCProperty) {
  1687. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  1688. I!=E; ++I) {
  1689. ExplodedNode *subExprNode = *I;
  1690. const GRState *state = subExprNode->getState();
  1691. evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
  1692. }
  1693. return;
  1694. }
  1695. // All other casts.
  1696. QualType T = CastE->getType();
  1697. QualType ExTy = Ex->getType();
  1698. if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
  1699. T = ExCast->getTypeAsWritten();
  1700. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  1701. I != E; ++I) {
  1702. Pred = *I;
  1703. switch (CastE->getCastKind()) {
  1704. case CK_LValueToRValue:
  1705. assert(false && "LValueToRValue casts handled earlier.");
  1706. case CK_GetObjCProperty:
  1707. assert(false && "GetObjCProperty casts handled earlier.");
  1708. case CK_ToVoid:
  1709. Dst.Add(Pred);
  1710. continue;
  1711. // The analyzer doesn't do anything special with these casts,
  1712. // since it understands retain/release semantics already.
  1713. case CK_ObjCProduceObject:
  1714. case CK_ObjCConsumeObject:
  1715. case CK_ObjCReclaimReturnedObject: // Fall-through.
  1716. // True no-ops.
  1717. case CK_NoOp:
  1718. case CK_FunctionToPointerDecay: {
  1719. // Copy the SVal of Ex to CastE.
  1720. const GRState *state = Pred->getState();
  1721. SVal V = state->getSVal(Ex);
  1722. state = state->BindExpr(CastE, V);
  1723. MakeNode(Dst, CastE, Pred, state);
  1724. continue;
  1725. }
  1726. case CK_Dependent:
  1727. case CK_ArrayToPointerDecay:
  1728. case CK_BitCast:
  1729. case CK_LValueBitCast:
  1730. case CK_IntegralCast:
  1731. case CK_NullToPointer:
  1732. case CK_IntegralToPointer:
  1733. case CK_PointerToIntegral:
  1734. case CK_PointerToBoolean:
  1735. case CK_IntegralToBoolean:
  1736. case CK_IntegralToFloating:
  1737. case CK_FloatingToIntegral:
  1738. case CK_FloatingToBoolean:
  1739. case CK_FloatingCast:
  1740. case CK_FloatingRealToComplex:
  1741. case CK_FloatingComplexToReal:
  1742. case CK_FloatingComplexToBoolean:
  1743. case CK_FloatingComplexCast:
  1744. case CK_FloatingComplexToIntegralComplex:
  1745. case CK_IntegralRealToComplex:
  1746. case CK_IntegralComplexToReal:
  1747. case CK_IntegralComplexToBoolean:
  1748. case CK_IntegralComplexCast:
  1749. case CK_IntegralComplexToFloatingComplex:
  1750. case CK_AnyPointerToObjCPointerCast:
  1751. case CK_AnyPointerToBlockPointerCast:
  1752. case CK_ObjCObjectLValueCast: {
  1753. // Delegate to SValBuilder to process.
  1754. const GRState* state = Pred->getState();
  1755. SVal V = state->getSVal(Ex);
  1756. V = svalBuilder.evalCast(V, T, ExTy);
  1757. state = state->BindExpr(CastE, V);
  1758. MakeNode(Dst, CastE, Pred, state);
  1759. continue;
  1760. }
  1761. case CK_DerivedToBase:
  1762. case CK_UncheckedDerivedToBase: {
  1763. // For DerivedToBase cast, delegate to the store manager.
  1764. const GRState *state = Pred->getState();
  1765. SVal val = state->getSVal(Ex);
  1766. val = getStoreManager().evalDerivedToBase(val, T);
  1767. state = state->BindExpr(CastE, val);
  1768. MakeNode(Dst, CastE, Pred, state);
  1769. continue;
  1770. }
  1771. // Various C++ casts that are not handled yet.
  1772. case CK_Dynamic:
  1773. case CK_ToUnion:
  1774. case CK_BaseToDerived:
  1775. case CK_NullToMemberPointer:
  1776. case CK_BaseToDerivedMemberPointer:
  1777. case CK_DerivedToBaseMemberPointer:
  1778. case CK_UserDefinedConversion:
  1779. case CK_ConstructorConversion:
  1780. case CK_VectorSplat:
  1781. case CK_MemberPointerToBoolean: {
  1782. // Recover some path-sensitivty by conjuring a new value.
  1783. QualType resultType = CastE->getType();
  1784. if (CastE->isLValue())
  1785. resultType = getContext().getPointerType(resultType);
  1786. SVal result =
  1787. svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
  1788. Builder->getCurrentBlockCount());
  1789. const GRState *state = Pred->getState()->BindExpr(CastE, result);
  1790. MakeNode(Dst, CastE, Pred, state);
  1791. continue;
  1792. }
  1793. }
  1794. }
  1795. }
  1796. void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL,
  1797. ExplodedNode* Pred,
  1798. ExplodedNodeSet& Dst) {
  1799. const InitListExpr* ILE
  1800. = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
  1801. const GRState* state = Pred->getState();
  1802. SVal ILV = state->getSVal(ILE);
  1803. const LocationContext *LC = Pred->getLocationContext();
  1804. state = state->bindCompoundLiteral(CL, LC, ILV);
  1805. if (CL->isLValue()) {
  1806. MakeNode(Dst, CL, Pred, state->BindExpr(CL, state->getLValue(CL, LC)));
  1807. }
  1808. else
  1809. MakeNode(Dst, CL, Pred, state->BindExpr(CL, ILV));
  1810. }
  1811. void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
  1812. ExplodedNodeSet& Dst) {
  1813. // FIXME: static variables may have an initializer, but the second
  1814. // time a function is called those values may not be current.
  1815. // This may need to be reflected in the CFG.
  1816. // Assumption: The CFG has one DeclStmt per Decl.
  1817. const Decl* D = *DS->decl_begin();
  1818. if (!D || !isa<VarDecl>(D))
  1819. return;
  1820. ExplodedNodeSet dstPreVisit;
  1821. getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
  1822. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1823. for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
  1824. I!=E; ++I)
  1825. {
  1826. ExplodedNode *N = *I;
  1827. const GRState *state = N->getState();
  1828. // Decls without InitExpr are not initialized explicitly.
  1829. const LocationContext *LC = N->getLocationContext();
  1830. if (const Expr *InitEx = VD->getInit()) {
  1831. SVal InitVal = state->getSVal(InitEx);
  1832. // We bound the temp obj region to the CXXConstructExpr. Now recover
  1833. // the lazy compound value when the variable is not a reference.
  1834. if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
  1835. !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
  1836. InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
  1837. assert(isa<nonloc::LazyCompoundVal>(InitVal));
  1838. }
  1839. // Recover some path-sensitivity if a scalar value evaluated to
  1840. // UnknownVal.
  1841. if ((InitVal.isUnknown() ||
  1842. !getConstraintManager().canReasonAbout(InitVal)) &&
  1843. !VD->getType()->isReferenceType()) {
  1844. InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
  1845. Builder->getCurrentBlockCount());
  1846. }
  1847. evalBind(Dst, DS, N, state,
  1848. loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true);
  1849. }
  1850. else {
  1851. MakeNode(Dst, DS, N, state->bindDeclWithNoInit(state->getRegion(VD, LC)));
  1852. }
  1853. }
  1854. }
  1855. void ExprEngine::VisitInitListExpr(const InitListExpr *IE, ExplodedNode *Pred,
  1856. ExplodedNodeSet& Dst) {
  1857. const GRState* state = Pred->getState();
  1858. QualType T = getContext().getCanonicalType(IE->getType());
  1859. unsigned NumInitElements = IE->getNumInits();
  1860. if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
  1861. llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
  1862. // Handle base case where the initializer has no elements.
  1863. // e.g: static int* myArray[] = {};
  1864. if (NumInitElements == 0) {
  1865. SVal V = svalBuilder.makeCompoundVal(T, vals);
  1866. MakeNode(Dst, IE, Pred, state->BindExpr(IE, V));
  1867. return;
  1868. }
  1869. for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
  1870. ei = IE->rend(); it != ei; ++it) {
  1871. vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it)), vals);
  1872. }
  1873. MakeNode(Dst, IE, Pred,
  1874. state->BindExpr(IE, svalBuilder.makeCompoundVal(T, vals)));
  1875. return;
  1876. }
  1877. if (Loc::isLocType(T) || T->isIntegerType()) {
  1878. assert(IE->getNumInits() == 1);
  1879. const Expr *initEx = IE->getInit(0);
  1880. MakeNode(Dst, IE, Pred, state->BindExpr(IE, state->getSVal(initEx)));
  1881. return;
  1882. }
  1883. llvm_unreachable("unprocessed InitListExpr type");
  1884. }
  1885. /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof(type).
  1886. void ExprEngine::VisitUnaryExprOrTypeTraitExpr(
  1887. const UnaryExprOrTypeTraitExpr* Ex,
  1888. ExplodedNode* Pred,
  1889. ExplodedNodeSet& Dst) {
  1890. QualType T = Ex->getTypeOfArgument();
  1891. if (Ex->getKind() == UETT_SizeOf) {
  1892. if (!T->isIncompleteType() && !T->isConstantSizeType()) {
  1893. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  1894. // FIXME: Add support for VLA type arguments, not just VLA expressions.
  1895. // When that happens, we should probably refactor VLASizeChecker's code.
  1896. if (Ex->isArgumentType()) {
  1897. Dst.Add(Pred);
  1898. return;
  1899. }
  1900. // Get the size by getting the extent of the sub-expression.
  1901. // First, visit the sub-expression to find its region.
  1902. const Expr *Arg = Ex->getArgumentExpr();
  1903. const GRState *state = Pred->getState();
  1904. const MemRegion *MR = state->getSVal(Arg).getAsRegion();
  1905. // If the subexpression can't be resolved to a region, we don't know
  1906. // anything about its size. Just leave the state as is and continue.
  1907. if (!MR) {
  1908. Dst.Add(Pred);
  1909. return;
  1910. }
  1911. // The result is the extent of the VLA.
  1912. SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder);
  1913. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, Extent));
  1914. return;
  1915. }
  1916. else if (T->getAs<ObjCObjectType>()) {
  1917. // Some code tries to take the sizeof an ObjCObjectType, relying that
  1918. // the compiler has laid out its representation. Just report Unknown
  1919. // for these.
  1920. Dst.Add(Pred);
  1921. return;
  1922. }
  1923. }
  1924. Expr::EvalResult Result;
  1925. Ex->Evaluate(Result, getContext());
  1926. CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue());
  1927. MakeNode(Dst, Ex, Pred,
  1928. Pred->getState()->BindExpr(Ex,
  1929. svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType())));
  1930. }
  1931. void ExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE,
  1932. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  1933. Expr::EvalResult Res;
  1934. if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) {
  1935. const APSInt &IV = Res.Val.getInt();
  1936. assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
  1937. assert(OOE->getType()->isIntegerType());
  1938. assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
  1939. SVal X = svalBuilder.makeIntVal(IV);
  1940. MakeNode(Dst, OOE, Pred, Pred->getState()->BindExpr(OOE, X));
  1941. return;
  1942. }
  1943. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  1944. Dst.Add(Pred);
  1945. }
  1946. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
  1947. ExplodedNode* Pred,
  1948. ExplodedNodeSet& Dst) {
  1949. switch (U->getOpcode()) {
  1950. default:
  1951. break;
  1952. case UO_Real: {
  1953. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  1954. ExplodedNodeSet Tmp;
  1955. Visit(Ex, Pred, Tmp);
  1956. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  1957. // FIXME: We don't have complex SValues yet.
  1958. if (Ex->getType()->isAnyComplexType()) {
  1959. // Just report "Unknown."
  1960. Dst.Add(*I);
  1961. continue;
  1962. }
  1963. // For all other types, UO_Real is an identity operation.
  1964. assert (U->getType() == Ex->getType());
  1965. const GRState* state = (*I)->getState();
  1966. MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
  1967. }
  1968. return;
  1969. }
  1970. case UO_Imag: {
  1971. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  1972. ExplodedNodeSet Tmp;
  1973. Visit(Ex, Pred, Tmp);
  1974. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  1975. // FIXME: We don't have complex SValues yet.
  1976. if (Ex->getType()->isAnyComplexType()) {
  1977. // Just report "Unknown."
  1978. Dst.Add(*I);
  1979. continue;
  1980. }
  1981. // For all other types, UO_Imag returns 0.
  1982. const GRState* state = (*I)->getState();
  1983. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  1984. MakeNode(Dst, U, *I, state->BindExpr(U, X));
  1985. }
  1986. return;
  1987. }
  1988. case UO_Plus:
  1989. assert(!U->isLValue());
  1990. // FALL-THROUGH.
  1991. case UO_Deref:
  1992. case UO_AddrOf:
  1993. case UO_Extension: {
  1994. // Unary "+" is a no-op, similar to a parentheses. We still have places
  1995. // where it may be a block-level expression, so we need to
  1996. // generate an extra node that just propagates the value of the
  1997. // subexpression.
  1998. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  1999. ExplodedNodeSet Tmp;
  2000. Visit(Ex, Pred, Tmp);
  2001. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2002. const GRState* state = (*I)->getState();
  2003. MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
  2004. }
  2005. return;
  2006. }
  2007. case UO_LNot:
  2008. case UO_Minus:
  2009. case UO_Not: {
  2010. assert (!U->isLValue());
  2011. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2012. ExplodedNodeSet Tmp;
  2013. Visit(Ex, Pred, Tmp);
  2014. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2015. const GRState* state = (*I)->getState();
  2016. // Get the value of the subexpression.
  2017. SVal V = state->getSVal(Ex);
  2018. if (V.isUnknownOrUndef()) {
  2019. MakeNode(Dst, U, *I, state->BindExpr(U, V));
  2020. continue;
  2021. }
  2022. // QualType DstT = getContext().getCanonicalType(U->getType());
  2023. // QualType SrcT = getContext().getCanonicalType(Ex->getType());
  2024. //
  2025. // if (DstT != SrcT) // Perform promotions.
  2026. // V = evalCast(V, DstT);
  2027. //
  2028. // if (V.isUnknownOrUndef()) {
  2029. // MakeNode(Dst, U, *I, BindExpr(St, U, V));
  2030. // continue;
  2031. // }
  2032. switch (U->getOpcode()) {
  2033. default:
  2034. assert(false && "Invalid Opcode.");
  2035. break;
  2036. case UO_Not:
  2037. // FIXME: Do we need to handle promotions?
  2038. state = state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
  2039. break;
  2040. case UO_Minus:
  2041. // FIXME: Do we need to handle promotions?
  2042. state = state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
  2043. break;
  2044. case UO_LNot:
  2045. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  2046. //
  2047. // Note: technically we do "E == 0", but this is the same in the
  2048. // transfer functions as "0 == E".
  2049. SVal Result;
  2050. if (isa<Loc>(V)) {
  2051. Loc X = svalBuilder.makeNull();
  2052. Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
  2053. U->getType());
  2054. }
  2055. else {
  2056. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  2057. Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
  2058. U->getType());
  2059. }
  2060. state = state->BindExpr(U, Result);
  2061. break;
  2062. }
  2063. MakeNode(Dst, U, *I, state);
  2064. }
  2065. return;
  2066. }
  2067. }
  2068. // Handle ++ and -- (both pre- and post-increment).
  2069. assert (U->isIncrementDecrementOp());
  2070. ExplodedNodeSet Tmp;
  2071. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2072. Visit(Ex, Pred, Tmp);
  2073. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
  2074. const GRState* state = (*I)->getState();
  2075. SVal loc = state->getSVal(Ex);
  2076. // Perform a load.
  2077. ExplodedNodeSet Tmp2;
  2078. evalLoad(Tmp2, Ex, *I, state, loc);
  2079. for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
  2080. state = (*I2)->getState();
  2081. SVal V2_untested = state->getSVal(Ex);
  2082. // Propagate unknown and undefined values.
  2083. if (V2_untested.isUnknownOrUndef()) {
  2084. MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested));
  2085. continue;
  2086. }
  2087. DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
  2088. // Handle all other values.
  2089. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
  2090. : BO_Sub;
  2091. // If the UnaryOperator has non-location type, use its type to create the
  2092. // constant value. If the UnaryOperator has location type, create the
  2093. // constant with int type and pointer width.
  2094. SVal RHS;
  2095. if (U->getType()->isAnyPointerType())
  2096. RHS = svalBuilder.makeArrayIndex(1);
  2097. else
  2098. RHS = svalBuilder.makeIntVal(1, U->getType());
  2099. SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
  2100. // Conjure a new symbol if necessary to recover precision.
  2101. if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){
  2102. DefinedOrUnknownSVal SymVal =
  2103. svalBuilder.getConjuredSymbolVal(NULL, Ex,
  2104. Builder->getCurrentBlockCount());
  2105. Result = SymVal;
  2106. // If the value is a location, ++/-- should always preserve
  2107. // non-nullness. Check if the original value was non-null, and if so
  2108. // propagate that constraint.
  2109. if (Loc::isLocType(U->getType())) {
  2110. DefinedOrUnknownSVal Constraint =
  2111. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  2112. if (!state->assume(Constraint, true)) {
  2113. // It isn't feasible for the original value to be null.
  2114. // Propagate this constraint.
  2115. Constraint = svalBuilder.evalEQ(state, SymVal,
  2116. svalBuilder.makeZeroVal(U->getType()));
  2117. state = state->assume(Constraint, false);
  2118. assert(state);
  2119. }
  2120. }
  2121. }
  2122. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  2123. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  2124. if (U->isLValue())
  2125. state = state->BindExpr(U, loc);
  2126. else
  2127. state = state->BindExpr(U, U->isPostfix() ? V2 : Result);
  2128. // Perform the store.
  2129. evalStore(Dst, NULL, U, *I2, state, loc, Result);
  2130. }
  2131. }
  2132. }
  2133. void ExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred,
  2134. ExplodedNodeSet& Dst) {
  2135. VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst);
  2136. }
  2137. void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A,
  2138. AsmStmt::const_outputs_iterator I,
  2139. AsmStmt::const_outputs_iterator E,
  2140. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  2141. if (I == E) {
  2142. VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst);
  2143. return;
  2144. }
  2145. ExplodedNodeSet Tmp;
  2146. Visit(*I, Pred, Tmp);
  2147. ++I;
  2148. for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI)
  2149. VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst);
  2150. }
  2151. void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A,
  2152. AsmStmt::const_inputs_iterator I,
  2153. AsmStmt::const_inputs_iterator E,
  2154. ExplodedNode* Pred,
  2155. ExplodedNodeSet& Dst) {
  2156. if (I == E) {
  2157. // We have processed both the inputs and the outputs. All of the outputs
  2158. // should evaluate to Locs. Nuke all of their values.
  2159. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2160. // which interprets the inline asm and stores proper results in the
  2161. // outputs.
  2162. const GRState* state = Pred->getState();
  2163. for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  2164. OE = A->end_outputs(); OI != OE; ++OI) {
  2165. SVal X = state->getSVal(*OI);
  2166. assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
  2167. if (isa<Loc>(X))
  2168. state = state->bindLoc(cast<Loc>(X), UnknownVal());
  2169. }
  2170. MakeNode(Dst, A, Pred, state);
  2171. return;
  2172. }
  2173. ExplodedNodeSet Tmp;
  2174. Visit(*I, Pred, Tmp);
  2175. ++I;
  2176. for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI)
  2177. VisitAsmStmtHelperInputs(A, I, E, *NI, Dst);
  2178. }
  2179. void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
  2180. ExplodedNodeSet &Dst) {
  2181. ExplodedNodeSet Src;
  2182. if (const Expr *RetE = RS->getRetValue()) {
  2183. // Record the returned expression in the state. It will be used in
  2184. // processCallExit to bind the return value to the call expr.
  2185. {
  2186. static SimpleProgramPointTag tag("ExprEngine: ReturnStmt");
  2187. const GRState *state = Pred->getState();
  2188. state = state->set<ReturnExpr>(RetE);
  2189. Pred = Builder->generateNode(RetE, state, Pred, &tag);
  2190. }
  2191. // We may get a NULL Pred because we generated a cached node.
  2192. if (Pred)
  2193. Visit(RetE, Pred, Src);
  2194. }
  2195. else {
  2196. Src.Add(Pred);
  2197. }
  2198. ExplodedNodeSet CheckedSet;
  2199. getCheckerManager().runCheckersForPreStmt(CheckedSet, Src, RS, *this);
  2200. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  2201. I != E; ++I) {
  2202. assert(Builder && "StmtNodeBuilder must be defined.");
  2203. Pred = *I;
  2204. unsigned size = Dst.size();
  2205. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  2206. SaveOr OldHasGen(Builder->hasGeneratedNode);
  2207. getTF().evalReturn(Dst, *this, *Builder, RS, Pred);
  2208. // Handle the case where no nodes where generated.
  2209. if (!Builder->BuildSinks && Dst.size() == size &&
  2210. !Builder->hasGeneratedNode)
  2211. MakeNode(Dst, RS, Pred, Pred->getState());
  2212. }
  2213. }
  2214. //===----------------------------------------------------------------------===//
  2215. // Transfer functions: Binary operators.
  2216. //===----------------------------------------------------------------------===//
  2217. void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
  2218. ExplodedNode* Pred,
  2219. ExplodedNodeSet& Dst) {
  2220. ExplodedNodeSet Tmp1;
  2221. Expr* LHS = B->getLHS()->IgnoreParens();
  2222. Expr* RHS = B->getRHS()->IgnoreParens();
  2223. Visit(LHS, Pred, Tmp1);
  2224. ExplodedNodeSet Tmp3;
  2225. for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) {
  2226. SVal LeftV = (*I1)->getState()->getSVal(LHS);
  2227. ExplodedNodeSet Tmp2;
  2228. Visit(RHS, *I1, Tmp2);
  2229. ExplodedNodeSet CheckedSet;
  2230. getCheckerManager().runCheckersForPreStmt(CheckedSet, Tmp2, B, *this);
  2231. // With both the LHS and RHS evaluated, process the operation itself.
  2232. for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end();
  2233. I2 != E2; ++I2) {
  2234. const GRState *state = (*I2)->getState();
  2235. SVal RightV = state->getSVal(RHS);
  2236. BinaryOperator::Opcode Op = B->getOpcode();
  2237. if (Op == BO_Assign) {
  2238. // EXPERIMENTAL: "Conjured" symbols.
  2239. // FIXME: Handle structs.
  2240. if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV))
  2241. {
  2242. unsigned Count = Builder->getCurrentBlockCount();
  2243. RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
  2244. }
  2245. SVal ExprVal = B->isLValue() ? LeftV : RightV;
  2246. // Simulate the effects of a "store": bind the value of the RHS
  2247. // to the L-Value represented by the LHS.
  2248. evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV);
  2249. continue;
  2250. }
  2251. if (!B->isAssignmentOp()) {
  2252. // Process non-assignments except commas or short-circuited
  2253. // logical expressions (LAnd and LOr).
  2254. SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
  2255. if (Result.isUnknown()) {
  2256. MakeNode(Tmp3, B, *I2, state);
  2257. continue;
  2258. }
  2259. state = state->BindExpr(B, Result);
  2260. MakeNode(Tmp3, B, *I2, state);
  2261. continue;
  2262. }
  2263. assert (B->isCompoundAssignmentOp());
  2264. switch (Op) {
  2265. default:
  2266. assert(0 && "Invalid opcode for compound assignment.");
  2267. case BO_MulAssign: Op = BO_Mul; break;
  2268. case BO_DivAssign: Op = BO_Div; break;
  2269. case BO_RemAssign: Op = BO_Rem; break;
  2270. case BO_AddAssign: Op = BO_Add; break;
  2271. case BO_SubAssign: Op = BO_Sub; break;
  2272. case BO_ShlAssign: Op = BO_Shl; break;
  2273. case BO_ShrAssign: Op = BO_Shr; break;
  2274. case BO_AndAssign: Op = BO_And; break;
  2275. case BO_XorAssign: Op = BO_Xor; break;
  2276. case BO_OrAssign: Op = BO_Or; break;
  2277. }
  2278. // Perform a load (the LHS). This performs the checks for
  2279. // null dereferences, and so on.
  2280. ExplodedNodeSet Tmp4;
  2281. SVal location = state->getSVal(LHS);
  2282. evalLoad(Tmp4, LHS, *I2, state, location);
  2283. for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4;
  2284. ++I4) {
  2285. state = (*I4)->getState();
  2286. SVal V = state->getSVal(LHS);
  2287. // Get the computation type.
  2288. QualType CTy =
  2289. cast<CompoundAssignOperator>(B)->getComputationResultType();
  2290. CTy = getContext().getCanonicalType(CTy);
  2291. QualType CLHSTy =
  2292. cast<CompoundAssignOperator>(B)->getComputationLHSType();
  2293. CLHSTy = getContext().getCanonicalType(CLHSTy);
  2294. QualType LTy = getContext().getCanonicalType(LHS->getType());
  2295. // Promote LHS.
  2296. V = svalBuilder.evalCast(V, CLHSTy, LTy);
  2297. // Compute the result of the operation.
  2298. SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
  2299. B->getType(), CTy);
  2300. // EXPERIMENTAL: "Conjured" symbols.
  2301. // FIXME: Handle structs.
  2302. SVal LHSVal;
  2303. if (Result.isUnknown() ||
  2304. !getConstraintManager().canReasonAbout(Result)) {
  2305. unsigned Count = Builder->getCurrentBlockCount();
  2306. // The symbolic value is actually for the type of the left-hand side
  2307. // expression, not the computation type, as this is the value the
  2308. // LValue on the LHS will bind to.
  2309. LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count);
  2310. // However, we need to convert the symbol to the computation type.
  2311. Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
  2312. }
  2313. else {
  2314. // The left-hand side may bind to a different value then the
  2315. // computation type.
  2316. LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
  2317. }
  2318. // In C++, assignment and compound assignment operators return an
  2319. // lvalue.
  2320. if (B->isLValue())
  2321. state = state->BindExpr(B, location);
  2322. else
  2323. state = state->BindExpr(B, Result);
  2324. evalStore(Tmp3, B, LHS, *I4, state, location, LHSVal);
  2325. }
  2326. }
  2327. }
  2328. getCheckerManager().runCheckersForPostStmt(Dst, Tmp3, B, *this);
  2329. }
  2330. //===----------------------------------------------------------------------===//
  2331. // Visualization.
  2332. //===----------------------------------------------------------------------===//
  2333. #ifndef NDEBUG
  2334. static ExprEngine* GraphPrintCheckerState;
  2335. static SourceManager* GraphPrintSourceManager;
  2336. namespace llvm {
  2337. template<>
  2338. struct DOTGraphTraits<ExplodedNode*> :
  2339. public DefaultDOTGraphTraits {
  2340. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  2341. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  2342. // work.
  2343. static std::string getNodeAttributes(const ExplodedNode* N, void*) {
  2344. #if 0
  2345. // FIXME: Replace with a general scheme to tell if the node is
  2346. // an error node.
  2347. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  2348. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  2349. GraphPrintCheckerState->isUndefDeref(N) ||
  2350. GraphPrintCheckerState->isUndefStore(N) ||
  2351. GraphPrintCheckerState->isUndefControlFlow(N) ||
  2352. GraphPrintCheckerState->isUndefResult(N) ||
  2353. GraphPrintCheckerState->isBadCall(N) ||
  2354. GraphPrintCheckerState->isUndefArg(N))
  2355. return "color=\"red\",style=\"filled\"";
  2356. if (GraphPrintCheckerState->isNoReturnCall(N))
  2357. return "color=\"blue\",style=\"filled\"";
  2358. #endif
  2359. return "";
  2360. }
  2361. static std::string getNodeLabel(const ExplodedNode* N, void*){
  2362. std::string sbuf;
  2363. llvm::raw_string_ostream Out(sbuf);
  2364. // Program Location.
  2365. ProgramPoint Loc = N->getLocation();
  2366. switch (Loc.getKind()) {
  2367. case ProgramPoint::BlockEntranceKind:
  2368. Out << "Block Entrance: B"
  2369. << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
  2370. break;
  2371. case ProgramPoint::BlockExitKind:
  2372. assert (false);
  2373. break;
  2374. case ProgramPoint::CallEnterKind:
  2375. Out << "CallEnter";
  2376. break;
  2377. case ProgramPoint::CallExitKind:
  2378. Out << "CallExit";
  2379. break;
  2380. default: {
  2381. if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
  2382. const Stmt* S = L->getStmt();
  2383. SourceLocation SLoc = S->getLocStart();
  2384. Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
  2385. LangOptions LO; // FIXME.
  2386. S->printPretty(Out, 0, PrintingPolicy(LO));
  2387. if (SLoc.isFileID()) {
  2388. Out << "\\lline="
  2389. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2390. << " col="
  2391. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  2392. << "\\l";
  2393. }
  2394. if (isa<PreStmt>(Loc))
  2395. Out << "\\lPreStmt\\l;";
  2396. else if (isa<PostLoad>(Loc))
  2397. Out << "\\lPostLoad\\l;";
  2398. else if (isa<PostStore>(Loc))
  2399. Out << "\\lPostStore\\l";
  2400. else if (isa<PostLValue>(Loc))
  2401. Out << "\\lPostLValue\\l";
  2402. #if 0
  2403. // FIXME: Replace with a general scheme to determine
  2404. // the name of the check.
  2405. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  2406. Out << "\\|Implicit-Null Dereference.\\l";
  2407. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  2408. Out << "\\|Explicit-Null Dereference.\\l";
  2409. else if (GraphPrintCheckerState->isUndefDeref(N))
  2410. Out << "\\|Dereference of undefialied value.\\l";
  2411. else if (GraphPrintCheckerState->isUndefStore(N))
  2412. Out << "\\|Store to Undefined Loc.";
  2413. else if (GraphPrintCheckerState->isUndefResult(N))
  2414. Out << "\\|Result of operation is undefined.";
  2415. else if (GraphPrintCheckerState->isNoReturnCall(N))
  2416. Out << "\\|Call to function marked \"noreturn\".";
  2417. else if (GraphPrintCheckerState->isBadCall(N))
  2418. Out << "\\|Call to NULL/Undefined.";
  2419. else if (GraphPrintCheckerState->isUndefArg(N))
  2420. Out << "\\|Argument in call is undefined";
  2421. #endif
  2422. break;
  2423. }
  2424. const BlockEdge& E = cast<BlockEdge>(Loc);
  2425. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  2426. << E.getDst()->getBlockID() << ')';
  2427. if (const Stmt* T = E.getSrc()->getTerminator()) {
  2428. SourceLocation SLoc = T->getLocStart();
  2429. Out << "\\|Terminator: ";
  2430. LangOptions LO; // FIXME.
  2431. E.getSrc()->printTerminator(Out, LO);
  2432. if (SLoc.isFileID()) {
  2433. Out << "\\lline="
  2434. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2435. << " col="
  2436. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  2437. }
  2438. if (isa<SwitchStmt>(T)) {
  2439. const Stmt* Label = E.getDst()->getLabel();
  2440. if (Label) {
  2441. if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
  2442. Out << "\\lcase ";
  2443. LangOptions LO; // FIXME.
  2444. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  2445. if (const Stmt* RHS = C->getRHS()) {
  2446. Out << " .. ";
  2447. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  2448. }
  2449. Out << ":";
  2450. }
  2451. else {
  2452. assert (isa<DefaultStmt>(Label));
  2453. Out << "\\ldefault:";
  2454. }
  2455. }
  2456. else
  2457. Out << "\\l(implicit) default:";
  2458. }
  2459. else if (isa<IndirectGotoStmt>(T)) {
  2460. // FIXME
  2461. }
  2462. else {
  2463. Out << "\\lCondition: ";
  2464. if (*E.getSrc()->succ_begin() == E.getDst())
  2465. Out << "true";
  2466. else
  2467. Out << "false";
  2468. }
  2469. Out << "\\l";
  2470. }
  2471. #if 0
  2472. // FIXME: Replace with a general scheme to determine
  2473. // the name of the check.
  2474. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  2475. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  2476. }
  2477. #endif
  2478. }
  2479. }
  2480. const GRState *state = N->getState();
  2481. Out << "\\|StateID: " << (void*) state
  2482. << " NodeID: " << (void*) N << "\\|";
  2483. state->printDOT(Out, *N->getLocationContext()->getCFG());
  2484. Out << "\\l";
  2485. if (const ProgramPointTag *tag = Loc.getTag()) {
  2486. Out << "\\|Tag: " << tag->getTagDescription();
  2487. Out << "\\l";
  2488. }
  2489. return Out.str();
  2490. }
  2491. };
  2492. } // end llvm namespace
  2493. #endif
  2494. #ifndef NDEBUG
  2495. template <typename ITERATOR>
  2496. ExplodedNode* GetGraphNode(ITERATOR I) { return *I; }
  2497. template <> ExplodedNode*
  2498. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  2499. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  2500. return I->first;
  2501. }
  2502. #endif
  2503. void ExprEngine::ViewGraph(bool trim) {
  2504. #ifndef NDEBUG
  2505. if (trim) {
  2506. std::vector<ExplodedNode*> Src;
  2507. // Flush any outstanding reports to make sure we cover all the nodes.
  2508. // This does not cause them to get displayed.
  2509. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  2510. const_cast<BugType*>(*I)->FlushReports(BR);
  2511. // Iterate through the reports and get their nodes.
  2512. for (BugReporter::EQClasses_iterator
  2513. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2514. BugReportEquivClass& EQ = *EI;
  2515. const BugReport &R = **EQ.begin();
  2516. ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode());
  2517. if (N) Src.push_back(N);
  2518. }
  2519. ViewGraph(&Src[0], &Src[0]+Src.size());
  2520. }
  2521. else {
  2522. GraphPrintCheckerState = this;
  2523. GraphPrintSourceManager = &getContext().getSourceManager();
  2524. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2525. GraphPrintCheckerState = NULL;
  2526. GraphPrintSourceManager = NULL;
  2527. }
  2528. #endif
  2529. }
  2530. void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
  2531. #ifndef NDEBUG
  2532. GraphPrintCheckerState = this;
  2533. GraphPrintSourceManager = &getContext().getSourceManager();
  2534. std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
  2535. if (!TrimmedG.get())
  2536. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2537. else
  2538. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2539. GraphPrintCheckerState = NULL;
  2540. GraphPrintSourceManager = NULL;
  2541. #endif
  2542. }