ExprEngine.cpp 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164
  1. //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
  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/PathSensitive/ExprEngine.h"
  16. #include "PrettyStackTraceLocationContext.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ParentMap.h"
  26. #include "clang/AST/PrettyPrinter.h"
  27. #include "clang/AST/Stmt.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/StmtObjC.h"
  30. #include "clang/AST/Type.h"
  31. #include "clang/Analysis/AnalysisDeclContext.h"
  32. #include "clang/Analysis/CFG.h"
  33. #include "clang/Analysis/ConstructionContext.h"
  34. #include "clang/Analysis/ProgramPoint.h"
  35. #include "clang/Basic/IdentifierTable.h"
  36. #include "clang/Basic/LLVM.h"
  37. #include "clang/Basic/LangOptions.h"
  38. #include "clang/Basic/PrettyStackTrace.h"
  39. #include "clang/Basic/SourceLocation.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/Specifiers.h"
  42. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  43. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  44. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  45. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  47. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  48. #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
  49. #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
  50. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  51. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
  52. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
  53. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  54. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  55. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  56. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  57. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  58. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  59. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  60. #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
  61. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  62. #include "llvm/ADT/APSInt.h"
  63. #include "llvm/ADT/DenseMap.h"
  64. #include "llvm/ADT/ImmutableMap.h"
  65. #include "llvm/ADT/ImmutableSet.h"
  66. #include "llvm/ADT/Optional.h"
  67. #include "llvm/ADT/SmallVector.h"
  68. #include "llvm/ADT/Statistic.h"
  69. #include "llvm/Support/Casting.h"
  70. #include "llvm/Support/Compiler.h"
  71. #include "llvm/Support/DOTGraphTraits.h"
  72. #include "llvm/Support/ErrorHandling.h"
  73. #include "llvm/Support/GraphWriter.h"
  74. #include "llvm/Support/SaveAndRestore.h"
  75. #include "llvm/Support/raw_ostream.h"
  76. #include <cassert>
  77. #include <cstdint>
  78. #include <memory>
  79. #include <string>
  80. #include <tuple>
  81. #include <utility>
  82. #include <vector>
  83. using namespace clang;
  84. using namespace ento;
  85. #define DEBUG_TYPE "ExprEngine"
  86. STATISTIC(NumRemoveDeadBindings,
  87. "The # of times RemoveDeadBindings is called");
  88. STATISTIC(NumMaxBlockCountReached,
  89. "The # of aborted paths due to reaching the maximum block count in "
  90. "a top level function");
  91. STATISTIC(NumMaxBlockCountReachedInInlined,
  92. "The # of aborted paths due to reaching the maximum block count in "
  93. "an inlined function");
  94. STATISTIC(NumTimesRetriedWithoutInlining,
  95. "The # of times we re-evaluated a call without inlining");
  96. //===----------------------------------------------------------------------===//
  97. // Internal program state traits.
  98. //===----------------------------------------------------------------------===//
  99. // When modeling a C++ constructor, for a variety of reasons we need to track
  100. // the location of the object for the duration of its ConstructionContext.
  101. // ObjectsUnderConstruction maps statements within the construction context
  102. // to the object's location, so that on every such statement the location
  103. // could have been retrieved.
  104. /// ConstructedObjectKey is used for being able to find the path-sensitive
  105. /// memory region of a freshly constructed object while modeling the AST node
  106. /// that syntactically represents the object that is being constructed.
  107. /// Semantics of such nodes may sometimes require access to the region that's
  108. /// not otherwise present in the program state, or to the very fact that
  109. /// the construction context was present and contained references to these
  110. /// AST nodes.
  111. class ConstructedObjectKey {
  112. typedef std::pair<
  113. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *>,
  114. const LocationContext *> ConstructedObjectKeyImpl;
  115. ConstructedObjectKeyImpl Impl;
  116. const void *getAnyASTNodePtr() const {
  117. if (const Stmt *S = getStmt())
  118. return S;
  119. else
  120. return getCXXCtorInitializer();
  121. }
  122. public:
  123. ConstructedObjectKey(
  124. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  125. const LocationContext *LC)
  126. : Impl(P, LC) {
  127. // This is the full list of statements that require additional actions when
  128. // encountered. This list may be expanded when new actions are implemented.
  129. assert(getCXXCtorInitializer() || isa<DeclStmt>(getStmt()) ||
  130. isa<CXXNewExpr>(getStmt()) || isa<CXXBindTemporaryExpr>(getStmt()) ||
  131. isa<MaterializeTemporaryExpr>(getStmt()));
  132. }
  133. const Stmt *getStmt() const {
  134. return Impl.first.dyn_cast<const Stmt *>();
  135. }
  136. const CXXCtorInitializer *getCXXCtorInitializer() const {
  137. return Impl.first.dyn_cast<const CXXCtorInitializer *>();
  138. }
  139. const LocationContext *getLocationContext() const {
  140. return Impl.second;
  141. }
  142. void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
  143. OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ") ";
  144. if (const Stmt *S = getStmt()) {
  145. S->printPretty(OS, Helper, PP);
  146. } else {
  147. const CXXCtorInitializer *I = getCXXCtorInitializer();
  148. OS << I->getAnyMember()->getNameAsString();
  149. }
  150. }
  151. void Profile(llvm::FoldingSetNodeID &ID) const {
  152. ID.AddPointer(Impl.first.getOpaqueValue());
  153. ID.AddPointer(Impl.second);
  154. }
  155. bool operator==(const ConstructedObjectKey &RHS) const {
  156. return Impl == RHS.Impl;
  157. }
  158. bool operator<(const ConstructedObjectKey &RHS) const {
  159. return Impl < RHS.Impl;
  160. }
  161. };
  162. typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
  163. ObjectsUnderConstructionMap;
  164. REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
  165. ObjectsUnderConstructionMap)
  166. //===----------------------------------------------------------------------===//
  167. // Engine construction and deletion.
  168. //===----------------------------------------------------------------------===//
  169. static const char* TagProviderName = "ExprEngine";
  170. ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
  171. AnalysisManager &mgr, bool gcEnabled,
  172. SetOfConstDecls *VisitedCalleesIn,
  173. FunctionSummariesTy *FS,
  174. InliningModes HowToInlineIn)
  175. : CTU(CTU), AMgr(mgr),
  176. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  177. Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
  178. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  179. mgr.getConstraintManagerCreator(), G.getAllocator(),
  180. this),
  181. SymMgr(StateMgr.getSymbolManager()),
  182. svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
  183. ObjCGCEnabled(gcEnabled), BR(mgr, *this),
  184. VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
  185. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  186. if (TrimInterval != 0) {
  187. // Enable eager node reclaimation when constructing the ExplodedGraph.
  188. G.enableNodeReclamation(TrimInterval);
  189. }
  190. }
  191. ExprEngine::~ExprEngine() {
  192. BR.FlushReports();
  193. }
  194. //===----------------------------------------------------------------------===//
  195. // Utility methods.
  196. //===----------------------------------------------------------------------===//
  197. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  198. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  199. const Decl *D = InitLoc->getDecl();
  200. // Preconditions.
  201. // FIXME: It would be nice if we had a more general mechanism to add
  202. // such preconditions. Some day.
  203. do {
  204. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  205. // Precondition: the first argument of 'main' is an integer guaranteed
  206. // to be > 0.
  207. const IdentifierInfo *II = FD->getIdentifier();
  208. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  209. break;
  210. const ParmVarDecl *PD = FD->getParamDecl(0);
  211. QualType T = PD->getType();
  212. const auto *BT = dyn_cast<BuiltinType>(T);
  213. if (!BT || !BT->isInteger())
  214. break;
  215. const MemRegion *R = state->getRegion(PD, InitLoc);
  216. if (!R)
  217. break;
  218. SVal V = state->getSVal(loc::MemRegionVal(R));
  219. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  220. svalBuilder.makeZeroVal(T),
  221. svalBuilder.getConditionType());
  222. Optional<DefinedOrUnknownSVal> Constraint =
  223. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  224. if (!Constraint)
  225. break;
  226. if (ProgramStateRef newState = state->assume(*Constraint, true))
  227. state = newState;
  228. }
  229. break;
  230. }
  231. while (false);
  232. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  233. // Precondition: 'self' is always non-null upon entry to an Objective-C
  234. // method.
  235. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  236. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  237. SVal V = state->getSVal(loc::MemRegionVal(R));
  238. if (Optional<Loc> LV = V.getAs<Loc>()) {
  239. // Assume that the pointer value in 'self' is non-null.
  240. state = state->assume(*LV, true);
  241. assert(state && "'self' cannot be null");
  242. }
  243. }
  244. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  245. if (!MD->isStatic()) {
  246. // Precondition: 'this' is always non-null upon entry to the
  247. // top-level function. This is our starting assumption for
  248. // analyzing an "open" program.
  249. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  250. if (SFC->getParent() == nullptr) {
  251. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  252. SVal V = state->getSVal(L);
  253. if (Optional<Loc> LV = V.getAs<Loc>()) {
  254. state = state->assume(*LV, true);
  255. assert(state && "'this' cannot be null");
  256. }
  257. }
  258. }
  259. }
  260. return state;
  261. }
  262. ProgramStateRef
  263. ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
  264. const LocationContext *LC,
  265. const Expr *InitWithAdjustments,
  266. const Expr *Result) {
  267. // FIXME: This function is a hack that works around the quirky AST
  268. // we're often having with respect to C++ temporaries. If only we modelled
  269. // the actual execution order of statements properly in the CFG,
  270. // all the hassle with adjustments would not be necessary,
  271. // and perhaps the whole function would be removed.
  272. SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
  273. if (!Result) {
  274. // If we don't have an explicit result expression, we're in "if needed"
  275. // mode. Only create a region if the current value is a NonLoc.
  276. if (!InitValWithAdjustments.getAs<NonLoc>())
  277. return State;
  278. Result = InitWithAdjustments;
  279. } else {
  280. // We need to create a region no matter what. For sanity, make sure we don't
  281. // try to stuff a Loc into a non-pointer temporary region.
  282. assert(!InitValWithAdjustments.getAs<Loc>() ||
  283. Loc::isLocType(Result->getType()) ||
  284. Result->getType()->isMemberPointerType());
  285. }
  286. ProgramStateManager &StateMgr = State->getStateManager();
  287. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  288. StoreManager &StoreMgr = StateMgr.getStoreManager();
  289. // MaterializeTemporaryExpr may appear out of place, after a few field and
  290. // base-class accesses have been made to the object, even though semantically
  291. // it is the whole object that gets materialized and lifetime-extended.
  292. //
  293. // For example:
  294. //
  295. // `-MaterializeTemporaryExpr
  296. // `-MemberExpr
  297. // `-CXXTemporaryObjectExpr
  298. //
  299. // instead of the more natural
  300. //
  301. // `-MemberExpr
  302. // `-MaterializeTemporaryExpr
  303. // `-CXXTemporaryObjectExpr
  304. //
  305. // Use the usual methods for obtaining the expression of the base object,
  306. // and record the adjustments that we need to make to obtain the sub-object
  307. // that the whole expression 'Ex' refers to. This trick is usual,
  308. // in the sense that CodeGen takes a similar route.
  309. SmallVector<const Expr *, 2> CommaLHSs;
  310. SmallVector<SubobjectAdjustment, 2> Adjustments;
  311. const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
  312. CommaLHSs, Adjustments);
  313. // Take the region for Init, i.e. for the whole object. If we do not remember
  314. // the region in which the object originally was constructed, come up with
  315. // a new temporary region out of thin air and copy the contents of the object
  316. // (which are currently present in the Environment, because Init is an rvalue)
  317. // into that region. This is not correct, but it is better than nothing.
  318. bool FoundOriginalMaterializationRegion = false;
  319. const TypedValueRegion *TR = nullptr;
  320. if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
  321. if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
  322. FoundOriginalMaterializationRegion = true;
  323. TR = cast<CXXTempObjectRegion>(V->getAsRegion());
  324. assert(TR);
  325. State = finishObjectConstruction(State, MT, LC);
  326. } else {
  327. StorageDuration SD = MT->getStorageDuration();
  328. // If this object is bound to a reference with static storage duration, we
  329. // put it in a different region to prevent "address leakage" warnings.
  330. if (SD == SD_Static || SD == SD_Thread) {
  331. TR = MRMgr.getCXXStaticTempObjectRegion(Init);
  332. } else {
  333. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  334. }
  335. }
  336. } else {
  337. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  338. }
  339. SVal Reg = loc::MemRegionVal(TR);
  340. SVal BaseReg = Reg;
  341. // Make the necessary adjustments to obtain the sub-object.
  342. for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
  343. const SubobjectAdjustment &Adj = *I;
  344. switch (Adj.Kind) {
  345. case SubobjectAdjustment::DerivedToBaseAdjustment:
  346. Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
  347. break;
  348. case SubobjectAdjustment::FieldAdjustment:
  349. Reg = StoreMgr.getLValueField(Adj.Field, Reg);
  350. break;
  351. case SubobjectAdjustment::MemberPointerAdjustment:
  352. // FIXME: Unimplemented.
  353. State = State->invalidateRegions(Reg, InitWithAdjustments,
  354. currBldrCtx->blockCount(), LC, true,
  355. nullptr, nullptr, nullptr);
  356. return State;
  357. }
  358. }
  359. if (!FoundOriginalMaterializationRegion) {
  360. // What remains is to copy the value of the object to the new region.
  361. // FIXME: In other words, what we should always do is copy value of the
  362. // Init expression (which corresponds to the bigger object) to the whole
  363. // temporary region TR. However, this value is often no longer present
  364. // in the Environment. If it has disappeared, we instead invalidate TR.
  365. // Still, what we can do is assign the value of expression Ex (which
  366. // corresponds to the sub-object) to the TR's sub-region Reg. At least,
  367. // values inside Reg would be correct.
  368. SVal InitVal = State->getSVal(Init, LC);
  369. if (InitVal.isUnknown()) {
  370. InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
  371. currBldrCtx->blockCount());
  372. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  373. // Then we'd need to take the value that certainly exists and bind it
  374. // over.
  375. if (InitValWithAdjustments.isUnknown()) {
  376. // Try to recover some path sensitivity in case we couldn't
  377. // compute the value.
  378. InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
  379. Result, LC, InitWithAdjustments->getType(),
  380. currBldrCtx->blockCount());
  381. }
  382. State =
  383. State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
  384. } else {
  385. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  386. }
  387. }
  388. // The result expression would now point to the correct sub-region of the
  389. // newly created temporary region. Do this last in order to getSVal of Init
  390. // correctly in case (Result == Init).
  391. State = State->BindExpr(Result, LC, Reg);
  392. if (!FoundOriginalMaterializationRegion) {
  393. // Notify checkers once for two bindLoc()s.
  394. State = processRegionChange(State, TR, LC);
  395. }
  396. return State;
  397. }
  398. ProgramStateRef ExprEngine::addObjectUnderConstruction(
  399. ProgramStateRef State,
  400. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  401. const LocationContext *LC, SVal V) {
  402. ConstructedObjectKey Key(P, LC->getCurrentStackFrame());
  403. // FIXME: Currently the state might already contain the marker due to
  404. // incorrect handling of temporaries bound to default parameters.
  405. assert(!State->get<ObjectsUnderConstruction>(Key) ||
  406. isa<CXXBindTemporaryExpr>(Key.getStmt()));
  407. return State->set<ObjectsUnderConstruction>(Key, V);
  408. }
  409. Optional<SVal> ExprEngine::getObjectUnderConstruction(
  410. ProgramStateRef State,
  411. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  412. const LocationContext *LC) {
  413. ConstructedObjectKey Key(P, LC->getCurrentStackFrame());
  414. return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
  415. }
  416. ProgramStateRef ExprEngine::finishObjectConstruction(
  417. ProgramStateRef State,
  418. llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P,
  419. const LocationContext *LC) {
  420. ConstructedObjectKey Key(P, LC->getCurrentStackFrame());
  421. assert(State->contains<ObjectsUnderConstruction>(Key));
  422. return State->remove<ObjectsUnderConstruction>(Key);
  423. }
  424. bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
  425. const LocationContext *FromLC,
  426. const LocationContext *ToLC) {
  427. const LocationContext *LC = FromLC;
  428. while (LC != ToLC) {
  429. assert(LC && "ToLC must be a parent of FromLC!");
  430. for (auto I : State->get<ObjectsUnderConstruction>())
  431. if (I.first.getLocationContext() == LC)
  432. return false;
  433. LC = LC->getParent();
  434. }
  435. return true;
  436. }
  437. //===----------------------------------------------------------------------===//
  438. // Top-level transfer function logic (Dispatcher).
  439. //===----------------------------------------------------------------------===//
  440. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  441. /// logic for handling assumptions on symbolic values.
  442. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  443. SVal cond, bool assumption) {
  444. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  445. }
  446. ProgramStateRef
  447. ExprEngine::processRegionChanges(ProgramStateRef state,
  448. const InvalidatedSymbols *invalidated,
  449. ArrayRef<const MemRegion *> Explicits,
  450. ArrayRef<const MemRegion *> Regions,
  451. const LocationContext *LCtx,
  452. const CallEvent *Call) {
  453. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  454. Explicits, Regions,
  455. LCtx, Call);
  456. }
  457. static void printObjectsUnderConstructionForContext(raw_ostream &Out,
  458. ProgramStateRef State,
  459. const char *NL,
  460. const char *Sep,
  461. const LocationContext *LC) {
  462. PrintingPolicy PP =
  463. LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
  464. for (auto I : State->get<ObjectsUnderConstruction>()) {
  465. ConstructedObjectKey Key = I.first;
  466. SVal Value = I.second;
  467. if (Key.getLocationContext() != LC)
  468. continue;
  469. Key.print(Out, nullptr, PP);
  470. Out << " : " << Value << NL;
  471. }
  472. }
  473. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  474. const char *NL, const char *Sep,
  475. const LocationContext *LCtx) {
  476. if (LCtx) {
  477. if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
  478. Out << Sep << "Objects under construction:" << NL;
  479. LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
  480. printObjectsUnderConstructionForContext(Out, State, NL, Sep, LC);
  481. });
  482. }
  483. }
  484. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  485. }
  486. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  487. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  488. }
  489. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  490. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  491. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  492. currStmtIdx = StmtIdx;
  493. currBldrCtx = Ctx;
  494. switch (E.getKind()) {
  495. case CFGElement::Statement:
  496. case CFGElement::Constructor:
  497. case CFGElement::CXXRecordTypedCall:
  498. ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
  499. return;
  500. case CFGElement::Initializer:
  501. ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
  502. return;
  503. case CFGElement::NewAllocator:
  504. ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
  505. Pred);
  506. return;
  507. case CFGElement::AutomaticObjectDtor:
  508. case CFGElement::DeleteDtor:
  509. case CFGElement::BaseDtor:
  510. case CFGElement::MemberDtor:
  511. case CFGElement::TemporaryDtor:
  512. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  513. return;
  514. case CFGElement::LoopExit:
  515. ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
  516. return;
  517. case CFGElement::LifetimeEnds:
  518. case CFGElement::ScopeBegin:
  519. case CFGElement::ScopeEnd:
  520. return;
  521. }
  522. }
  523. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  524. const Stmt *S,
  525. const ExplodedNode *Pred,
  526. const LocationContext *LC) {
  527. // Are we never purging state values?
  528. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  529. return false;
  530. // Is this the beginning of a basic block?
  531. if (Pred->getLocation().getAs<BlockEntrance>())
  532. return true;
  533. // Is this on a non-expression?
  534. if (!isa<Expr>(S))
  535. return true;
  536. // Run before processing a call.
  537. if (CallEvent::isCallStmt(S))
  538. return true;
  539. // Is this an expression that is consumed by another expression? If so,
  540. // postpone cleaning out the state.
  541. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  542. return !PM.isConsumedExpr(cast<Expr>(S));
  543. }
  544. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  545. const Stmt *ReferenceStmt,
  546. const LocationContext *LC,
  547. const Stmt *DiagnosticStmt,
  548. ProgramPoint::Kind K) {
  549. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  550. ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
  551. && "PostStmt is not generally supported by the SymbolReaper yet");
  552. assert(LC && "Must pass the current (or expiring) LocationContext");
  553. if (!DiagnosticStmt) {
  554. DiagnosticStmt = ReferenceStmt;
  555. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  556. }
  557. NumRemoveDeadBindings++;
  558. ProgramStateRef CleanedState = Pred->getState();
  559. // LC is the location context being destroyed, but SymbolReaper wants a
  560. // location context that is still live. (If this is the top-level stack
  561. // frame, this will be null.)
  562. if (!ReferenceStmt) {
  563. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  564. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  565. LC = LC->getParent();
  566. }
  567. const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : nullptr;
  568. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  569. for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
  570. if (SymbolRef Sym = I.second.getAsSymbol())
  571. SymReaper.markLive(Sym);
  572. if (const MemRegion *MR = I.second.getAsRegion())
  573. SymReaper.markLive(MR);
  574. }
  575. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  576. // Create a state in which dead bindings are removed from the environment
  577. // and the store. TODO: The function should just return new env and store,
  578. // not a new state.
  579. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  580. // Process any special transfer function for dead symbols.
  581. // A tag to track convenience transitions, which can be removed at cleanup.
  582. static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
  583. if (!SymReaper.hasDeadSymbols()) {
  584. // Generate a CleanedNode that has the environment and store cleaned
  585. // up. Since no symbols are dead, we can optimize and not clean out
  586. // the constraint manager.
  587. StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
  588. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
  589. } else {
  590. // Call checkers with the non-cleaned state so that they could query the
  591. // values of the soon to be dead symbols.
  592. ExplodedNodeSet CheckedSet;
  593. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  594. DiagnosticStmt, *this, K);
  595. // For each node in CheckedSet, generate CleanedNodes that have the
  596. // environment, the store, and the constraints cleaned up but have the
  597. // user-supplied states as the predecessors.
  598. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  599. for (const auto I : CheckedSet) {
  600. ProgramStateRef CheckerState = I->getState();
  601. // The constraint manager has not been cleaned up yet, so clean up now.
  602. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  603. SymReaper);
  604. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  605. "Checkers are not allowed to modify the Environment as a part of "
  606. "checkDeadSymbols processing.");
  607. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  608. "Checkers are not allowed to modify the Store as a part of "
  609. "checkDeadSymbols processing.");
  610. // Create a state based on CleanedState with CheckerState GDM and
  611. // generate a transition to that state.
  612. ProgramStateRef CleanedCheckerSt =
  613. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  614. Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
  615. }
  616. }
  617. }
  618. void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
  619. // Reclaim any unnecessary nodes in the ExplodedGraph.
  620. G.reclaimRecentlyAllocatedNodes();
  621. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  622. currStmt->getLocStart(),
  623. "Error evaluating statement");
  624. // Remove dead bindings and symbols.
  625. ExplodedNodeSet CleanedStates;
  626. if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
  627. Pred->getLocationContext())) {
  628. removeDead(Pred, CleanedStates, currStmt,
  629. Pred->getLocationContext());
  630. } else
  631. CleanedStates.Add(Pred);
  632. // Visit the statement.
  633. ExplodedNodeSet Dst;
  634. for (const auto I : CleanedStates) {
  635. ExplodedNodeSet DstI;
  636. // Visit the statement.
  637. Visit(currStmt, I, DstI);
  638. Dst.insert(DstI);
  639. }
  640. // Enqueue the new nodes onto the work list.
  641. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  642. }
  643. void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
  644. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  645. S->getLocStart(),
  646. "Error evaluating end of the loop");
  647. ExplodedNodeSet Dst;
  648. Dst.Add(Pred);
  649. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  650. ProgramStateRef NewState = Pred->getState();
  651. if(AMgr.options.shouldUnrollLoops())
  652. NewState = processLoopEnd(S, NewState);
  653. LoopExit PP(S, Pred->getLocationContext());
  654. Bldr.generateNode(PP, NewState, Pred);
  655. // Enqueue the new nodes onto the work list.
  656. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  657. }
  658. void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
  659. ExplodedNode *Pred) {
  660. const CXXCtorInitializer *BMI = CFGInit.getInitializer();
  661. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  662. const LocationContext *LC = Pred->getLocationContext();
  663. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  664. BMI->getSourceLocation(),
  665. "Error evaluating initializer");
  666. // We don't clean up dead bindings here.
  667. const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
  668. const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
  669. ProgramStateRef State = Pred->getState();
  670. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  671. ExplodedNodeSet Tmp;
  672. SVal FieldLoc;
  673. // Evaluate the initializer, if necessary
  674. if (BMI->isAnyMemberInitializer()) {
  675. // Constructors build the object directly in the field,
  676. // but non-objects must be copied in from the initializer.
  677. if (getObjectUnderConstruction(State, BMI, LC)) {
  678. // The field was directly constructed, so there is no need to bind.
  679. // But we still need to stop tracking the object under construction.
  680. State = finishObjectConstruction(State, BMI, LC);
  681. NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  682. PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
  683. Bldr.generateNode(PS, State, Pred);
  684. } else {
  685. const ValueDecl *Field;
  686. if (BMI->isIndirectMemberInitializer()) {
  687. Field = BMI->getIndirectMember();
  688. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  689. } else {
  690. Field = BMI->getMember();
  691. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  692. }
  693. SVal InitVal;
  694. if (Init->getType()->isArrayType()) {
  695. // Handle arrays of trivial type. We can represent this with a
  696. // primitive load/copy from the base array region.
  697. const ArraySubscriptExpr *ASE;
  698. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  699. Init = ASE->getBase()->IgnoreImplicit();
  700. SVal LValue = State->getSVal(Init, stackFrame);
  701. if (!Field->getType()->isReferenceType())
  702. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  703. InitVal = State->getSVal(*LValueLoc);
  704. // If we fail to get the value for some reason, use a symbolic value.
  705. if (InitVal.isUnknownOrUndef()) {
  706. SValBuilder &SVB = getSValBuilder();
  707. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  708. Field->getType(),
  709. currBldrCtx->blockCount());
  710. }
  711. } else {
  712. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  713. }
  714. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  715. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  716. }
  717. } else {
  718. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  719. Tmp.insert(Pred);
  720. // We already did all the work when visiting the CXXConstructExpr.
  721. }
  722. // Construct PostInitializer nodes whether the state changed or not,
  723. // so that the diagnostics don't get confused.
  724. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  725. ExplodedNodeSet Dst;
  726. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  727. for (const auto I : Tmp) {
  728. ProgramStateRef State = I->getState();
  729. Bldr.generateNode(PP, State, I);
  730. }
  731. // Enqueue the new nodes onto the work list.
  732. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  733. }
  734. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  735. ExplodedNode *Pred) {
  736. ExplodedNodeSet Dst;
  737. switch (D.getKind()) {
  738. case CFGElement::AutomaticObjectDtor:
  739. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  740. break;
  741. case CFGElement::BaseDtor:
  742. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  743. break;
  744. case CFGElement::MemberDtor:
  745. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  746. break;
  747. case CFGElement::TemporaryDtor:
  748. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  749. break;
  750. case CFGElement::DeleteDtor:
  751. ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
  752. break;
  753. default:
  754. llvm_unreachable("Unexpected dtor kind.");
  755. }
  756. // Enqueue the new nodes onto the work list.
  757. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  758. }
  759. void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
  760. ExplodedNode *Pred) {
  761. ExplodedNodeSet Dst;
  762. AnalysisManager &AMgr = getAnalysisManager();
  763. AnalyzerOptions &Opts = AMgr.options;
  764. // TODO: We're not evaluating allocators for all cases just yet as
  765. // we're not handling the return value correctly, which causes false
  766. // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
  767. if (Opts.mayInlineCXXAllocator())
  768. VisitCXXNewAllocatorCall(NE, Pred, Dst);
  769. else {
  770. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  771. const LocationContext *LCtx = Pred->getLocationContext();
  772. PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
  773. Bldr.generateNode(PP, Pred->getState(), Pred);
  774. }
  775. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  776. }
  777. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  778. ExplodedNode *Pred,
  779. ExplodedNodeSet &Dst) {
  780. const VarDecl *varDecl = Dtor.getVarDecl();
  781. QualType varType = varDecl->getType();
  782. ProgramStateRef state = Pred->getState();
  783. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  784. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  785. if (varType->isReferenceType()) {
  786. const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
  787. if (!ValueRegion) {
  788. // FIXME: This should not happen. The language guarantees a presence
  789. // of a valid initializer here, so the reference shall not be undefined.
  790. // It seems that we're calling destructors over variables that
  791. // were not initialized yet.
  792. return;
  793. }
  794. Region = ValueRegion->getBaseRegion();
  795. varType = cast<TypedValueRegion>(Region)->getValueType();
  796. }
  797. // FIXME: We need to run the same destructor on every element of the array.
  798. // This workaround will just run the first destructor (which will still
  799. // invalidate the entire array).
  800. EvalCallOptions CallOpts;
  801. Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
  802. CallOpts.IsArrayCtorOrDtor).getAsRegion();
  803. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  804. Pred, Dst, CallOpts);
  805. }
  806. void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
  807. ExplodedNode *Pred,
  808. ExplodedNodeSet &Dst) {
  809. ProgramStateRef State = Pred->getState();
  810. const LocationContext *LCtx = Pred->getLocationContext();
  811. const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
  812. const Stmt *Arg = DE->getArgument();
  813. QualType DTy = DE->getDestroyedType();
  814. SVal ArgVal = State->getSVal(Arg, LCtx);
  815. // If the argument to delete is known to be a null value,
  816. // don't run destructor.
  817. if (State->isNull(ArgVal).isConstrainedTrue()) {
  818. QualType BTy = getContext().getBaseElementType(DTy);
  819. const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
  820. const CXXDestructorDecl *Dtor = RD->getDestructor();
  821. PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
  822. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  823. Bldr.generateNode(PP, Pred->getState(), Pred);
  824. return;
  825. }
  826. EvalCallOptions CallOpts;
  827. const MemRegion *ArgR = ArgVal.getAsRegion();
  828. if (DE->isArrayForm()) {
  829. // FIXME: We need to run the same destructor on every element of the array.
  830. // This workaround will just run the first destructor (which will still
  831. // invalidate the entire array).
  832. CallOpts.IsArrayCtorOrDtor = true;
  833. // Yes, it may even be a multi-dimensional array.
  834. while (const auto *AT = getContext().getAsArrayType(DTy))
  835. DTy = AT->getElementType();
  836. if (ArgR)
  837. ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
  838. }
  839. VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
  840. }
  841. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  842. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  843. const LocationContext *LCtx = Pred->getLocationContext();
  844. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  845. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  846. LCtx->getCurrentStackFrame());
  847. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  848. // Create the base object region.
  849. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  850. QualType BaseTy = Base->getType();
  851. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  852. Base->isVirtual());
  853. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  854. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
  855. }
  856. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  857. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  858. const FieldDecl *Member = D.getFieldDecl();
  859. QualType T = Member->getType();
  860. ProgramStateRef State = Pred->getState();
  861. const LocationContext *LCtx = Pred->getLocationContext();
  862. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  863. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  864. LCtx->getCurrentStackFrame());
  865. SVal FieldVal =
  866. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  867. // FIXME: We need to run the same destructor on every element of the array.
  868. // This workaround will just run the first destructor (which will still
  869. // invalidate the entire array).
  870. EvalCallOptions CallOpts;
  871. FieldVal = makeZeroElementRegion(State, FieldVal, T,
  872. CallOpts.IsArrayCtorOrDtor);
  873. VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  874. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
  875. }
  876. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  877. ExplodedNode *Pred,
  878. ExplodedNodeSet &Dst) {
  879. ExplodedNodeSet CleanDtorState;
  880. StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
  881. ProgramStateRef State = Pred->getState();
  882. const MemRegion *MR = nullptr;
  883. if (Optional<SVal> V =
  884. getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
  885. Pred->getLocationContext())) {
  886. // FIXME: Currently we insert temporary destructors for default parameters,
  887. // but we don't insert the constructors, so the entry in
  888. // ObjectsUnderConstruction may be missing.
  889. State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
  890. Pred->getLocationContext());
  891. MR = V->getAsRegion();
  892. }
  893. StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
  894. QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
  895. // FIXME: Currently CleanDtorState can be empty here due to temporaries being
  896. // bound to default parameters.
  897. assert(CleanDtorState.size() <= 1);
  898. ExplodedNode *CleanPred =
  899. CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
  900. EvalCallOptions CallOpts;
  901. CallOpts.IsTemporaryCtorOrDtor = true;
  902. if (!MR) {
  903. CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
  904. // If we have no MR, we still need to unwrap the array to avoid destroying
  905. // the whole array at once. Regardless, we'd eventually need to model array
  906. // destructors properly, element-by-element.
  907. while (const ArrayType *AT = getContext().getAsArrayType(T)) {
  908. T = AT->getElementType();
  909. CallOpts.IsArrayCtorOrDtor = true;
  910. }
  911. } else {
  912. // We'd eventually need to makeZeroElementRegion() trick here,
  913. // but for now we don't have the respective construction contexts,
  914. // so MR would always be null in this case. Do nothing for now.
  915. }
  916. VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
  917. /*IsBase=*/false, CleanPred, Dst, CallOpts);
  918. }
  919. void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
  920. NodeBuilderContext &BldCtx,
  921. ExplodedNode *Pred,
  922. ExplodedNodeSet &Dst,
  923. const CFGBlock *DstT,
  924. const CFGBlock *DstF) {
  925. BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
  926. ProgramStateRef State = Pred->getState();
  927. const LocationContext *LC = Pred->getLocationContext();
  928. if (getObjectUnderConstruction(State, BTE, LC)) {
  929. TempDtorBuilder.markInfeasible(false);
  930. TempDtorBuilder.generateNode(State, true, Pred);
  931. } else {
  932. TempDtorBuilder.markInfeasible(true);
  933. TempDtorBuilder.generateNode(State, false, Pred);
  934. }
  935. }
  936. void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
  937. ExplodedNodeSet &PreVisit,
  938. ExplodedNodeSet &Dst) {
  939. // This is a fallback solution in case we didn't have a construction
  940. // context when we were constructing the temporary. Otherwise the map should
  941. // have been populated there.
  942. if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
  943. // In case we don't have temporary destructors in the CFG, do not mark
  944. // the initialization - we would otherwise never clean it up.
  945. Dst = PreVisit;
  946. return;
  947. }
  948. StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
  949. for (ExplodedNode *Node : PreVisit) {
  950. ProgramStateRef State = Node->getState();
  951. const LocationContext *LC = Node->getLocationContext();
  952. if (!getObjectUnderConstruction(State, BTE, LC)) {
  953. // FIXME: Currently the state might also already contain the marker due to
  954. // incorrect handling of temporaries bound to default parameters; for
  955. // those, we currently skip the CXXBindTemporaryExpr but rely on adding
  956. // temporary destructor nodes.
  957. State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
  958. }
  959. StmtBldr.generateNode(BTE, Node, State);
  960. }
  961. }
  962. ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
  963. PointerEscapeKind K) const {
  964. class CollectReachableSymbolsCallback final : public SymbolVisitor {
  965. InvalidatedSymbols Symbols;
  966. public:
  967. explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
  968. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  969. bool VisitSymbol(SymbolRef Sym) override {
  970. Symbols.insert(Sym);
  971. return true;
  972. }
  973. };
  974. const CollectReachableSymbolsCallback &Scanner =
  975. State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
  976. return getCheckerManager().runCheckersForPointerEscape(
  977. State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
  978. }
  979. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  980. ExplodedNodeSet &DstTop) {
  981. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  982. S->getLocStart(),
  983. "Error evaluating statement");
  984. ExplodedNodeSet Dst;
  985. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  986. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  987. switch (S->getStmtClass()) {
  988. // C++, OpenMP and ARC stuff we don't support yet.
  989. case Expr::ObjCIndirectCopyRestoreExprClass:
  990. case Stmt::CXXDependentScopeMemberExprClass:
  991. case Stmt::CXXInheritedCtorInitExprClass:
  992. case Stmt::CXXTryStmtClass:
  993. case Stmt::CXXTypeidExprClass:
  994. case Stmt::CXXUuidofExprClass:
  995. case Stmt::CXXFoldExprClass:
  996. case Stmt::MSPropertyRefExprClass:
  997. case Stmt::MSPropertySubscriptExprClass:
  998. case Stmt::CXXUnresolvedConstructExprClass:
  999. case Stmt::DependentScopeDeclRefExprClass:
  1000. case Stmt::ArrayTypeTraitExprClass:
  1001. case Stmt::ExpressionTraitExprClass:
  1002. case Stmt::UnresolvedLookupExprClass:
  1003. case Stmt::UnresolvedMemberExprClass:
  1004. case Stmt::TypoExprClass:
  1005. case Stmt::CXXNoexceptExprClass:
  1006. case Stmt::PackExpansionExprClass:
  1007. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  1008. case Stmt::FunctionParmPackExprClass:
  1009. case Stmt::CoroutineBodyStmtClass:
  1010. case Stmt::CoawaitExprClass:
  1011. case Stmt::DependentCoawaitExprClass:
  1012. case Stmt::CoreturnStmtClass:
  1013. case Stmt::CoyieldExprClass:
  1014. case Stmt::SEHTryStmtClass:
  1015. case Stmt::SEHExceptStmtClass:
  1016. case Stmt::SEHLeaveStmtClass:
  1017. case Stmt::SEHFinallyStmtClass:
  1018. case Stmt::OMPParallelDirectiveClass:
  1019. case Stmt::OMPSimdDirectiveClass:
  1020. case Stmt::OMPForDirectiveClass:
  1021. case Stmt::OMPForSimdDirectiveClass:
  1022. case Stmt::OMPSectionsDirectiveClass:
  1023. case Stmt::OMPSectionDirectiveClass:
  1024. case Stmt::OMPSingleDirectiveClass:
  1025. case Stmt::OMPMasterDirectiveClass:
  1026. case Stmt::OMPCriticalDirectiveClass:
  1027. case Stmt::OMPParallelForDirectiveClass:
  1028. case Stmt::OMPParallelForSimdDirectiveClass:
  1029. case Stmt::OMPParallelSectionsDirectiveClass:
  1030. case Stmt::OMPTaskDirectiveClass:
  1031. case Stmt::OMPTaskyieldDirectiveClass:
  1032. case Stmt::OMPBarrierDirectiveClass:
  1033. case Stmt::OMPTaskwaitDirectiveClass:
  1034. case Stmt::OMPTaskgroupDirectiveClass:
  1035. case Stmt::OMPFlushDirectiveClass:
  1036. case Stmt::OMPOrderedDirectiveClass:
  1037. case Stmt::OMPAtomicDirectiveClass:
  1038. case Stmt::OMPTargetDirectiveClass:
  1039. case Stmt::OMPTargetDataDirectiveClass:
  1040. case Stmt::OMPTargetEnterDataDirectiveClass:
  1041. case Stmt::OMPTargetExitDataDirectiveClass:
  1042. case Stmt::OMPTargetParallelDirectiveClass:
  1043. case Stmt::OMPTargetParallelForDirectiveClass:
  1044. case Stmt::OMPTargetUpdateDirectiveClass:
  1045. case Stmt::OMPTeamsDirectiveClass:
  1046. case Stmt::OMPCancellationPointDirectiveClass:
  1047. case Stmt::OMPCancelDirectiveClass:
  1048. case Stmt::OMPTaskLoopDirectiveClass:
  1049. case Stmt::OMPTaskLoopSimdDirectiveClass:
  1050. case Stmt::OMPDistributeDirectiveClass:
  1051. case Stmt::OMPDistributeParallelForDirectiveClass:
  1052. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  1053. case Stmt::OMPDistributeSimdDirectiveClass:
  1054. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  1055. case Stmt::OMPTargetSimdDirectiveClass:
  1056. case Stmt::OMPTeamsDistributeDirectiveClass:
  1057. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  1058. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  1059. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  1060. case Stmt::OMPTargetTeamsDirectiveClass:
  1061. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  1062. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  1063. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  1064. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  1065. case Stmt::CapturedStmtClass: {
  1066. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1067. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1068. break;
  1069. }
  1070. case Stmt::ParenExprClass:
  1071. llvm_unreachable("ParenExprs already handled.");
  1072. case Stmt::GenericSelectionExprClass:
  1073. llvm_unreachable("GenericSelectionExprs already handled.");
  1074. // Cases that should never be evaluated simply because they shouldn't
  1075. // appear in the CFG.
  1076. case Stmt::BreakStmtClass:
  1077. case Stmt::CaseStmtClass:
  1078. case Stmt::CompoundStmtClass:
  1079. case Stmt::ContinueStmtClass:
  1080. case Stmt::CXXForRangeStmtClass:
  1081. case Stmt::DefaultStmtClass:
  1082. case Stmt::DoStmtClass:
  1083. case Stmt::ForStmtClass:
  1084. case Stmt::GotoStmtClass:
  1085. case Stmt::IfStmtClass:
  1086. case Stmt::IndirectGotoStmtClass:
  1087. case Stmt::LabelStmtClass:
  1088. case Stmt::NoStmtClass:
  1089. case Stmt::NullStmtClass:
  1090. case Stmt::SwitchStmtClass:
  1091. case Stmt::WhileStmtClass:
  1092. case Expr::MSDependentExistsStmtClass:
  1093. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  1094. case Stmt::ObjCSubscriptRefExprClass:
  1095. case Stmt::ObjCPropertyRefExprClass:
  1096. llvm_unreachable("These are handled by PseudoObjectExpr");
  1097. case Stmt::GNUNullExprClass: {
  1098. // GNU __null is a pointer-width integer, not an actual pointer.
  1099. ProgramStateRef state = Pred->getState();
  1100. state = state->BindExpr(S, Pred->getLocationContext(),
  1101. svalBuilder.makeIntValWithPtrWidth(0, false));
  1102. Bldr.generateNode(S, Pred, state);
  1103. break;
  1104. }
  1105. case Stmt::ObjCAtSynchronizedStmtClass:
  1106. Bldr.takeNodes(Pred);
  1107. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  1108. Bldr.addNodes(Dst);
  1109. break;
  1110. case Stmt::ExprWithCleanupsClass:
  1111. // Handled due to fully linearised CFG.
  1112. break;
  1113. case Stmt::CXXBindTemporaryExprClass: {
  1114. Bldr.takeNodes(Pred);
  1115. ExplodedNodeSet PreVisit;
  1116. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1117. ExplodedNodeSet Next;
  1118. VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
  1119. getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
  1120. Bldr.addNodes(Dst);
  1121. break;
  1122. }
  1123. // Cases not handled yet; but will handle some day.
  1124. case Stmt::DesignatedInitExprClass:
  1125. case Stmt::DesignatedInitUpdateExprClass:
  1126. case Stmt::ArrayInitLoopExprClass:
  1127. case Stmt::ArrayInitIndexExprClass:
  1128. case Stmt::ExtVectorElementExprClass:
  1129. case Stmt::ImaginaryLiteralClass:
  1130. case Stmt::ObjCAtCatchStmtClass:
  1131. case Stmt::ObjCAtFinallyStmtClass:
  1132. case Stmt::ObjCAtTryStmtClass:
  1133. case Stmt::ObjCAutoreleasePoolStmtClass:
  1134. case Stmt::ObjCEncodeExprClass:
  1135. case Stmt::ObjCIsaExprClass:
  1136. case Stmt::ObjCProtocolExprClass:
  1137. case Stmt::ObjCSelectorExprClass:
  1138. case Stmt::ParenListExprClass:
  1139. case Stmt::ShuffleVectorExprClass:
  1140. case Stmt::ConvertVectorExprClass:
  1141. case Stmt::VAArgExprClass:
  1142. case Stmt::CUDAKernelCallExprClass:
  1143. case Stmt::OpaqueValueExprClass:
  1144. case Stmt::AsTypeExprClass:
  1145. // Fall through.
  1146. // Cases we intentionally don't evaluate, since they don't need
  1147. // to be explicitly evaluated.
  1148. case Stmt::PredefinedExprClass:
  1149. case Stmt::AddrLabelExprClass:
  1150. case Stmt::AttributedStmtClass:
  1151. case Stmt::IntegerLiteralClass:
  1152. case Stmt::FixedPointLiteralClass:
  1153. case Stmt::CharacterLiteralClass:
  1154. case Stmt::ImplicitValueInitExprClass:
  1155. case Stmt::CXXScalarValueInitExprClass:
  1156. case Stmt::CXXBoolLiteralExprClass:
  1157. case Stmt::ObjCBoolLiteralExprClass:
  1158. case Stmt::ObjCAvailabilityCheckExprClass:
  1159. case Stmt::FloatingLiteralClass:
  1160. case Stmt::NoInitExprClass:
  1161. case Stmt::SizeOfPackExprClass:
  1162. case Stmt::StringLiteralClass:
  1163. case Stmt::ObjCStringLiteralClass:
  1164. case Stmt::CXXPseudoDestructorExprClass:
  1165. case Stmt::SubstNonTypeTemplateParmExprClass:
  1166. case Stmt::CXXNullPtrLiteralExprClass:
  1167. case Stmt::OMPArraySectionExprClass:
  1168. case Stmt::TypeTraitExprClass: {
  1169. Bldr.takeNodes(Pred);
  1170. ExplodedNodeSet preVisit;
  1171. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1172. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  1173. Bldr.addNodes(Dst);
  1174. break;
  1175. }
  1176. case Stmt::CXXDefaultArgExprClass:
  1177. case Stmt::CXXDefaultInitExprClass: {
  1178. Bldr.takeNodes(Pred);
  1179. ExplodedNodeSet PreVisit;
  1180. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1181. ExplodedNodeSet Tmp;
  1182. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  1183. const Expr *ArgE;
  1184. if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  1185. ArgE = DefE->getExpr();
  1186. else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  1187. ArgE = DefE->getExpr();
  1188. else
  1189. llvm_unreachable("unknown constant wrapper kind");
  1190. bool IsTemporary = false;
  1191. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  1192. ArgE = MTE->GetTemporaryExpr();
  1193. IsTemporary = true;
  1194. }
  1195. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  1196. if (!ConstantVal)
  1197. ConstantVal = UnknownVal();
  1198. const LocationContext *LCtx = Pred->getLocationContext();
  1199. for (const auto I : PreVisit) {
  1200. ProgramStateRef State = I->getState();
  1201. State = State->BindExpr(S, LCtx, *ConstantVal);
  1202. if (IsTemporary)
  1203. State = createTemporaryRegionIfNeeded(State, LCtx,
  1204. cast<Expr>(S),
  1205. cast<Expr>(S));
  1206. Bldr2.generateNode(S, I, State);
  1207. }
  1208. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1209. Bldr.addNodes(Dst);
  1210. break;
  1211. }
  1212. // Cases we evaluate as opaque expressions, conjuring a symbol.
  1213. case Stmt::CXXStdInitializerListExprClass:
  1214. case Expr::ObjCArrayLiteralClass:
  1215. case Expr::ObjCDictionaryLiteralClass:
  1216. case Expr::ObjCBoxedExprClass: {
  1217. Bldr.takeNodes(Pred);
  1218. ExplodedNodeSet preVisit;
  1219. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1220. ExplodedNodeSet Tmp;
  1221. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  1222. const auto *Ex = cast<Expr>(S);
  1223. QualType resultType = Ex->getType();
  1224. for (const auto N : preVisit) {
  1225. const LocationContext *LCtx = N->getLocationContext();
  1226. SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  1227. resultType,
  1228. currBldrCtx->blockCount());
  1229. ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
  1230. // Escape pointers passed into the list, unless it's an ObjC boxed
  1231. // expression which is not a boxable C structure.
  1232. if (!(isa<ObjCBoxedExpr>(Ex) &&
  1233. !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
  1234. ->getType()->isRecordType()))
  1235. for (auto Child : Ex->children()) {
  1236. assert(Child);
  1237. SVal Val = State->getSVal(Child, LCtx);
  1238. State = escapeValue(State, Val, PSK_EscapeOther);
  1239. }
  1240. Bldr2.generateNode(S, N, State);
  1241. }
  1242. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1243. Bldr.addNodes(Dst);
  1244. break;
  1245. }
  1246. case Stmt::ArraySubscriptExprClass:
  1247. Bldr.takeNodes(Pred);
  1248. VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  1249. Bldr.addNodes(Dst);
  1250. break;
  1251. case Stmt::GCCAsmStmtClass:
  1252. Bldr.takeNodes(Pred);
  1253. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  1254. Bldr.addNodes(Dst);
  1255. break;
  1256. case Stmt::MSAsmStmtClass:
  1257. Bldr.takeNodes(Pred);
  1258. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  1259. Bldr.addNodes(Dst);
  1260. break;
  1261. case Stmt::BlockExprClass:
  1262. Bldr.takeNodes(Pred);
  1263. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  1264. Bldr.addNodes(Dst);
  1265. break;
  1266. case Stmt::LambdaExprClass:
  1267. if (AMgr.options.shouldInlineLambdas()) {
  1268. Bldr.takeNodes(Pred);
  1269. VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
  1270. Bldr.addNodes(Dst);
  1271. } else {
  1272. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1273. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1274. }
  1275. break;
  1276. case Stmt::BinaryOperatorClass: {
  1277. const auto *B = cast<BinaryOperator>(S);
  1278. if (B->isLogicalOp()) {
  1279. Bldr.takeNodes(Pred);
  1280. VisitLogicalExpr(B, Pred, Dst);
  1281. Bldr.addNodes(Dst);
  1282. break;
  1283. }
  1284. else if (B->getOpcode() == BO_Comma) {
  1285. ProgramStateRef state = Pred->getState();
  1286. Bldr.generateNode(B, Pred,
  1287. state->BindExpr(B, Pred->getLocationContext(),
  1288. state->getSVal(B->getRHS(),
  1289. Pred->getLocationContext())));
  1290. break;
  1291. }
  1292. Bldr.takeNodes(Pred);
  1293. if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
  1294. (B->isRelationalOp() || B->isEqualityOp())) {
  1295. ExplodedNodeSet Tmp;
  1296. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  1297. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  1298. }
  1299. else
  1300. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1301. Bldr.addNodes(Dst);
  1302. break;
  1303. }
  1304. case Stmt::CXXOperatorCallExprClass: {
  1305. const auto *OCE = cast<CXXOperatorCallExpr>(S);
  1306. // For instance method operators, make sure the 'this' argument has a
  1307. // valid region.
  1308. const Decl *Callee = OCE->getCalleeDecl();
  1309. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  1310. if (MD->isInstance()) {
  1311. ProgramStateRef State = Pred->getState();
  1312. const LocationContext *LCtx = Pred->getLocationContext();
  1313. ProgramStateRef NewState =
  1314. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  1315. if (NewState != State) {
  1316. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
  1317. ProgramPoint::PreStmtKind);
  1318. // Did we cache out?
  1319. if (!Pred)
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. // FALLTHROUGH
  1325. LLVM_FALLTHROUGH;
  1326. }
  1327. case Stmt::CallExprClass:
  1328. case Stmt::CXXMemberCallExprClass:
  1329. case Stmt::UserDefinedLiteralClass:
  1330. Bldr.takeNodes(Pred);
  1331. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  1332. Bldr.addNodes(Dst);
  1333. break;
  1334. case Stmt::CXXCatchStmtClass:
  1335. Bldr.takeNodes(Pred);
  1336. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  1337. Bldr.addNodes(Dst);
  1338. break;
  1339. case Stmt::CXXTemporaryObjectExprClass:
  1340. case Stmt::CXXConstructExprClass:
  1341. Bldr.takeNodes(Pred);
  1342. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  1343. Bldr.addNodes(Dst);
  1344. break;
  1345. case Stmt::CXXNewExprClass: {
  1346. Bldr.takeNodes(Pred);
  1347. ExplodedNodeSet PreVisit;
  1348. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1349. ExplodedNodeSet PostVisit;
  1350. for (const auto i : PreVisit)
  1351. VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
  1352. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1353. Bldr.addNodes(Dst);
  1354. break;
  1355. }
  1356. case Stmt::CXXDeleteExprClass: {
  1357. Bldr.takeNodes(Pred);
  1358. ExplodedNodeSet PreVisit;
  1359. const auto *CDE = cast<CXXDeleteExpr>(S);
  1360. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1361. for (const auto i : PreVisit)
  1362. VisitCXXDeleteExpr(CDE, i, Dst);
  1363. Bldr.addNodes(Dst);
  1364. break;
  1365. }
  1366. // FIXME: ChooseExpr is really a constant. We need to fix
  1367. // the CFG do not model them as explicit control-flow.
  1368. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  1369. Bldr.takeNodes(Pred);
  1370. const auto *C = cast<ChooseExpr>(S);
  1371. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  1372. Bldr.addNodes(Dst);
  1373. break;
  1374. }
  1375. case Stmt::CompoundAssignOperatorClass:
  1376. Bldr.takeNodes(Pred);
  1377. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1378. Bldr.addNodes(Dst);
  1379. break;
  1380. case Stmt::CompoundLiteralExprClass:
  1381. Bldr.takeNodes(Pred);
  1382. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  1383. Bldr.addNodes(Dst);
  1384. break;
  1385. case Stmt::BinaryConditionalOperatorClass:
  1386. case Stmt::ConditionalOperatorClass: { // '?' operator
  1387. Bldr.takeNodes(Pred);
  1388. const auto *C = cast<AbstractConditionalOperator>(S);
  1389. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  1390. Bldr.addNodes(Dst);
  1391. break;
  1392. }
  1393. case Stmt::CXXThisExprClass:
  1394. Bldr.takeNodes(Pred);
  1395. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  1396. Bldr.addNodes(Dst);
  1397. break;
  1398. case Stmt::DeclRefExprClass: {
  1399. Bldr.takeNodes(Pred);
  1400. const auto *DE = cast<DeclRefExpr>(S);
  1401. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  1402. Bldr.addNodes(Dst);
  1403. break;
  1404. }
  1405. case Stmt::DeclStmtClass:
  1406. Bldr.takeNodes(Pred);
  1407. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  1408. Bldr.addNodes(Dst);
  1409. break;
  1410. case Stmt::ImplicitCastExprClass:
  1411. case Stmt::CStyleCastExprClass:
  1412. case Stmt::CXXStaticCastExprClass:
  1413. case Stmt::CXXDynamicCastExprClass:
  1414. case Stmt::CXXReinterpretCastExprClass:
  1415. case Stmt::CXXConstCastExprClass:
  1416. case Stmt::CXXFunctionalCastExprClass:
  1417. case Stmt::ObjCBridgedCastExprClass: {
  1418. Bldr.takeNodes(Pred);
  1419. const auto *C = cast<CastExpr>(S);
  1420. ExplodedNodeSet dstExpr;
  1421. VisitCast(C, C->getSubExpr(), Pred, dstExpr);
  1422. // Handle the postvisit checks.
  1423. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  1424. Bldr.addNodes(Dst);
  1425. break;
  1426. }
  1427. case Expr::MaterializeTemporaryExprClass: {
  1428. Bldr.takeNodes(Pred);
  1429. const auto *MTE = cast<MaterializeTemporaryExpr>(S);
  1430. ExplodedNodeSet dstPrevisit;
  1431. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
  1432. ExplodedNodeSet dstExpr;
  1433. for (const auto i : dstPrevisit)
  1434. CreateCXXTemporaryObject(MTE, i, dstExpr);
  1435. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
  1436. Bldr.addNodes(Dst);
  1437. break;
  1438. }
  1439. case Stmt::InitListExprClass:
  1440. Bldr.takeNodes(Pred);
  1441. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  1442. Bldr.addNodes(Dst);
  1443. break;
  1444. case Stmt::MemberExprClass:
  1445. Bldr.takeNodes(Pred);
  1446. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  1447. Bldr.addNodes(Dst);
  1448. break;
  1449. case Stmt::AtomicExprClass:
  1450. Bldr.takeNodes(Pred);
  1451. VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
  1452. Bldr.addNodes(Dst);
  1453. break;
  1454. case Stmt::ObjCIvarRefExprClass:
  1455. Bldr.takeNodes(Pred);
  1456. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  1457. Bldr.addNodes(Dst);
  1458. break;
  1459. case Stmt::ObjCForCollectionStmtClass:
  1460. Bldr.takeNodes(Pred);
  1461. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  1462. Bldr.addNodes(Dst);
  1463. break;
  1464. case Stmt::ObjCMessageExprClass:
  1465. Bldr.takeNodes(Pred);
  1466. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  1467. Bldr.addNodes(Dst);
  1468. break;
  1469. case Stmt::ObjCAtThrowStmtClass:
  1470. case Stmt::CXXThrowExprClass:
  1471. // FIXME: This is not complete. We basically treat @throw as
  1472. // an abort.
  1473. Bldr.generateSink(S, Pred, Pred->getState());
  1474. break;
  1475. case Stmt::ReturnStmtClass:
  1476. Bldr.takeNodes(Pred);
  1477. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  1478. Bldr.addNodes(Dst);
  1479. break;
  1480. case Stmt::OffsetOfExprClass: {
  1481. Bldr.takeNodes(Pred);
  1482. ExplodedNodeSet PreVisit;
  1483. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1484. ExplodedNodeSet PostVisit;
  1485. for (const auto Node : PreVisit)
  1486. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
  1487. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1488. Bldr.addNodes(Dst);
  1489. break;
  1490. }
  1491. case Stmt::UnaryExprOrTypeTraitExprClass:
  1492. Bldr.takeNodes(Pred);
  1493. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1494. Pred, Dst);
  1495. Bldr.addNodes(Dst);
  1496. break;
  1497. case Stmt::StmtExprClass: {
  1498. const auto *SE = cast<StmtExpr>(S);
  1499. if (SE->getSubStmt()->body_empty()) {
  1500. // Empty statement expression.
  1501. assert(SE->getType() == getContext().VoidTy
  1502. && "Empty statement expression must have void type.");
  1503. break;
  1504. }
  1505. if (const auto *LastExpr =
  1506. dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  1507. ProgramStateRef state = Pred->getState();
  1508. Bldr.generateNode(SE, Pred,
  1509. state->BindExpr(SE, Pred->getLocationContext(),
  1510. state->getSVal(LastExpr,
  1511. Pred->getLocationContext())));
  1512. }
  1513. break;
  1514. }
  1515. case Stmt::UnaryOperatorClass: {
  1516. Bldr.takeNodes(Pred);
  1517. const auto *U = cast<UnaryOperator>(S);
  1518. if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
  1519. ExplodedNodeSet Tmp;
  1520. VisitUnaryOperator(U, Pred, Tmp);
  1521. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  1522. }
  1523. else
  1524. VisitUnaryOperator(U, Pred, Dst);
  1525. Bldr.addNodes(Dst);
  1526. break;
  1527. }
  1528. case Stmt::PseudoObjectExprClass: {
  1529. Bldr.takeNodes(Pred);
  1530. ProgramStateRef state = Pred->getState();
  1531. const auto *PE = cast<PseudoObjectExpr>(S);
  1532. if (const Expr *Result = PE->getResultExpr()) {
  1533. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1534. Bldr.generateNode(S, Pred,
  1535. state->BindExpr(S, Pred->getLocationContext(), V));
  1536. }
  1537. else
  1538. Bldr.generateNode(S, Pred,
  1539. state->BindExpr(S, Pred->getLocationContext(),
  1540. UnknownVal()));
  1541. Bldr.addNodes(Dst);
  1542. break;
  1543. }
  1544. }
  1545. }
  1546. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1547. const LocationContext *CalleeLC) {
  1548. const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1549. const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
  1550. assert(CalleeSF && CallerSF);
  1551. ExplodedNode *BeforeProcessingCall = nullptr;
  1552. const Stmt *CE = CalleeSF->getCallSite();
  1553. // Find the first node before we started processing the call expression.
  1554. while (N) {
  1555. ProgramPoint L = N->getLocation();
  1556. BeforeProcessingCall = N;
  1557. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1558. // Skip the nodes corresponding to the inlined code.
  1559. if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
  1560. continue;
  1561. // We reached the caller. Find the node right before we started
  1562. // processing the call.
  1563. if (L.isPurgeKind())
  1564. continue;
  1565. if (L.getAs<PreImplicitCall>())
  1566. continue;
  1567. if (L.getAs<CallEnter>())
  1568. continue;
  1569. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1570. if (SP->getStmt() == CE)
  1571. continue;
  1572. break;
  1573. }
  1574. if (!BeforeProcessingCall)
  1575. return false;
  1576. // TODO: Clean up the unneeded nodes.
  1577. // Build an Epsilon node from which we will restart the analyzes.
  1578. // Note that CE is permitted to be NULL!
  1579. ProgramPoint NewNodeLoc =
  1580. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1581. // Add the special flag to GDM to signal retrying with no inlining.
  1582. // Note, changing the state ensures that we are not going to cache out.
  1583. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1584. NewNodeState =
  1585. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1586. // Make the new node a successor of BeforeProcessingCall.
  1587. bool IsNew = false;
  1588. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1589. // We cached out at this point. Caching out is common due to us backtracking
  1590. // from the inlined function, which might spawn several paths.
  1591. if (!IsNew)
  1592. return true;
  1593. NewNode->addPredecessor(BeforeProcessingCall, G);
  1594. // Add the new node to the work list.
  1595. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1596. CalleeSF->getIndex());
  1597. NumTimesRetriedWithoutInlining++;
  1598. return true;
  1599. }
  1600. /// Block entrance. (Update counters).
  1601. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1602. NodeBuilderWithSinks &nodeBuilder,
  1603. ExplodedNode *Pred) {
  1604. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1605. // If we reach a loop which has a known bound (and meets
  1606. // other constraints) then consider completely unrolling it.
  1607. if(AMgr.options.shouldUnrollLoops()) {
  1608. unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
  1609. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1610. if (Term) {
  1611. ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
  1612. Pred, maxBlockVisitOnPath);
  1613. if (NewState != Pred->getState()) {
  1614. ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
  1615. if (!UpdatedNode)
  1616. return;
  1617. Pred = UpdatedNode;
  1618. }
  1619. }
  1620. // Is we are inside an unrolled loop then no need the check the counters.
  1621. if(isUnrolledState(Pred->getState()))
  1622. return;
  1623. }
  1624. // If this block is terminated by a loop and it has already been visited the
  1625. // maximum number of times, widen the loop.
  1626. unsigned int BlockCount = nodeBuilder.getContext().blockCount();
  1627. if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
  1628. AMgr.options.shouldWidenLoops()) {
  1629. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1630. if (!(Term &&
  1631. (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
  1632. return;
  1633. // Widen.
  1634. const LocationContext *LCtx = Pred->getLocationContext();
  1635. ProgramStateRef WidenedState =
  1636. getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
  1637. nodeBuilder.generateNode(WidenedState, Pred);
  1638. return;
  1639. }
  1640. // FIXME: Refactor this into a checker.
  1641. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
  1642. static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
  1643. const ExplodedNode *Sink =
  1644. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1645. // Check if we stopped at the top level function or not.
  1646. // Root node should have the location context of the top most function.
  1647. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1648. const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1649. const LocationContext *RootLC =
  1650. (*G.roots_begin())->getLocation().getLocationContext();
  1651. if (RootLC->getCurrentStackFrame() != CalleeSF) {
  1652. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1653. // Re-run the call evaluation without inlining it, by storing the
  1654. // no-inlining policy in the state and enqueuing the new work item on
  1655. // the list. Replay should almost never fail. Use the stats to catch it
  1656. // if it does.
  1657. if ((!AMgr.options.NoRetryExhausted &&
  1658. replayWithoutInlining(Pred, CalleeLC)))
  1659. return;
  1660. NumMaxBlockCountReachedInInlined++;
  1661. } else
  1662. NumMaxBlockCountReached++;
  1663. // Make sink nodes as exhausted(for stats) only if retry failed.
  1664. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1665. }
  1666. }
  1667. //===----------------------------------------------------------------------===//
  1668. // Branch processing.
  1669. //===----------------------------------------------------------------------===//
  1670. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1671. /// to try to recover some path-sensitivity for casts of symbolic
  1672. /// integers that promote their values (which are currently not tracked well).
  1673. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1674. // cast(s) did was sign-extend the original value.
  1675. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  1676. ProgramStateRef state,
  1677. const Stmt *Condition,
  1678. const LocationContext *LCtx,
  1679. ASTContext &Ctx) {
  1680. const auto *Ex = dyn_cast<Expr>(Condition);
  1681. if (!Ex)
  1682. return UnknownVal();
  1683. uint64_t bits = 0;
  1684. bool bitsInit = false;
  1685. while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
  1686. QualType T = CE->getType();
  1687. if (!T->isIntegralOrEnumerationType())
  1688. return UnknownVal();
  1689. uint64_t newBits = Ctx.getTypeSize(T);
  1690. if (!bitsInit || newBits < bits) {
  1691. bitsInit = true;
  1692. bits = newBits;
  1693. }
  1694. Ex = CE->getSubExpr();
  1695. }
  1696. // We reached a non-cast. Is it a symbolic value?
  1697. QualType T = Ex->getType();
  1698. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1699. Ctx.getTypeSize(T) > bits)
  1700. return UnknownVal();
  1701. return state->getSVal(Ex, LCtx);
  1702. }
  1703. #ifndef NDEBUG
  1704. static const Stmt *getRightmostLeaf(const Stmt *Condition) {
  1705. while (Condition) {
  1706. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1707. if (!BO || !BO->isLogicalOp()) {
  1708. return Condition;
  1709. }
  1710. Condition = BO->getRHS()->IgnoreParens();
  1711. }
  1712. return nullptr;
  1713. }
  1714. #endif
  1715. // Returns the condition the branch at the end of 'B' depends on and whose value
  1716. // has been evaluated within 'B'.
  1717. // In most cases, the terminator condition of 'B' will be evaluated fully in
  1718. // the last statement of 'B'; in those cases, the resolved condition is the
  1719. // given 'Condition'.
  1720. // If the condition of the branch is a logical binary operator tree, the CFG is
  1721. // optimized: in that case, we know that the expression formed by all but the
  1722. // rightmost leaf of the logical binary operator tree must be true, and thus
  1723. // the branch condition is at this point equivalent to the truth value of that
  1724. // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
  1725. // expression in its final statement. As the full condition in that case was
  1726. // not evaluated, and is thus not in the SVal cache, we need to use that leaf
  1727. // expression to evaluate the truth value of the condition in the current state
  1728. // space.
  1729. static const Stmt *ResolveCondition(const Stmt *Condition,
  1730. const CFGBlock *B) {
  1731. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1732. Condition = Ex->IgnoreParens();
  1733. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1734. if (!BO || !BO->isLogicalOp())
  1735. return Condition;
  1736. assert(!B->getTerminator().isTemporaryDtorsBranch() &&
  1737. "Temporary destructor branches handled by processBindTemporary.");
  1738. // For logical operations, we still have the case where some branches
  1739. // use the traditional "merge" approach and others sink the branch
  1740. // directly into the basic blocks representing the logical operation.
  1741. // We need to distinguish between those two cases here.
  1742. // The invariants are still shifting, but it is possible that the
  1743. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1744. // CFGStmt as the value of the condition.
  1745. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1746. for (; I != E; ++I) {
  1747. CFGElement Elem = *I;
  1748. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1749. if (!CS)
  1750. continue;
  1751. const Stmt *LastStmt = CS->getStmt();
  1752. assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
  1753. return LastStmt;
  1754. }
  1755. llvm_unreachable("could not resolve condition");
  1756. }
  1757. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1758. NodeBuilderContext& BldCtx,
  1759. ExplodedNode *Pred,
  1760. ExplodedNodeSet &Dst,
  1761. const CFGBlock *DstT,
  1762. const CFGBlock *DstF) {
  1763. assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
  1764. "CXXBindTemporaryExprs are handled by processBindTemporary.");
  1765. const LocationContext *LCtx = Pred->getLocationContext();
  1766. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1767. currBldrCtx = &BldCtx;
  1768. // Check for NULL conditions; e.g. "for(;;)"
  1769. if (!Condition) {
  1770. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1771. NullCondBldr.markInfeasible(false);
  1772. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1773. return;
  1774. }
  1775. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1776. Condition = Ex->IgnoreParens();
  1777. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1778. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1779. Condition->getLocStart(),
  1780. "Error evaluating branch");
  1781. ExplodedNodeSet CheckersOutSet;
  1782. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1783. Pred, *this);
  1784. // We generated only sinks.
  1785. if (CheckersOutSet.empty())
  1786. return;
  1787. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1788. for (const auto PredI : CheckersOutSet) {
  1789. if (PredI->isSink())
  1790. continue;
  1791. ProgramStateRef PrevState = PredI->getState();
  1792. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1793. if (X.isUnknownOrUndef()) {
  1794. // Give it a chance to recover from unknown.
  1795. if (const auto *Ex = dyn_cast<Expr>(Condition)) {
  1796. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1797. // Try to recover some path-sensitivity. Right now casts of symbolic
  1798. // integers that promote their values are currently not tracked well.
  1799. // If 'Condition' is such an expression, try and recover the
  1800. // underlying value and use that instead.
  1801. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1802. PrevState, Condition,
  1803. PredI->getLocationContext(),
  1804. getContext());
  1805. if (!recovered.isUnknown()) {
  1806. X = recovered;
  1807. }
  1808. }
  1809. }
  1810. }
  1811. // If the condition is still unknown, give up.
  1812. if (X.isUnknownOrUndef()) {
  1813. builder.generateNode(PrevState, true, PredI);
  1814. builder.generateNode(PrevState, false, PredI);
  1815. continue;
  1816. }
  1817. DefinedSVal V = X.castAs<DefinedSVal>();
  1818. ProgramStateRef StTrue, StFalse;
  1819. std::tie(StTrue, StFalse) = PrevState->assume(V);
  1820. // Process the true branch.
  1821. if (builder.isFeasible(true)) {
  1822. if (StTrue)
  1823. builder.generateNode(StTrue, true, PredI);
  1824. else
  1825. builder.markInfeasible(true);
  1826. }
  1827. // Process the false branch.
  1828. if (builder.isFeasible(false)) {
  1829. if (StFalse)
  1830. builder.generateNode(StFalse, false, PredI);
  1831. else
  1832. builder.markInfeasible(false);
  1833. }
  1834. }
  1835. currBldrCtx = nullptr;
  1836. }
  1837. /// The GDM component containing the set of global variables which have been
  1838. /// previously initialized with explicit initializers.
  1839. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1840. llvm::ImmutableSet<const VarDecl *>)
  1841. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1842. NodeBuilderContext &BuilderCtx,
  1843. ExplodedNode *Pred,
  1844. ExplodedNodeSet &Dst,
  1845. const CFGBlock *DstT,
  1846. const CFGBlock *DstF) {
  1847. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1848. currBldrCtx = &BuilderCtx;
  1849. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  1850. ProgramStateRef state = Pred->getState();
  1851. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1852. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1853. if (!initHasRun) {
  1854. state = state->add<InitializedGlobalsSet>(VD);
  1855. }
  1856. builder.generateNode(state, initHasRun, Pred);
  1857. builder.markInfeasible(!initHasRun);
  1858. currBldrCtx = nullptr;
  1859. }
  1860. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1861. /// nodes by processing the 'effects' of a computed goto jump.
  1862. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1863. ProgramStateRef state = builder.getState();
  1864. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1865. // Three possibilities:
  1866. //
  1867. // (1) We know the computed label.
  1868. // (2) The label is NULL (or some other constant), or Undefined.
  1869. // (3) We have no clue about the label. Dispatch to all targets.
  1870. //
  1871. using iterator = IndirectGotoNodeBuilder::iterator;
  1872. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1873. const LabelDecl *L = LV->getLabel();
  1874. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1875. if (I.getLabel() == L) {
  1876. builder.generateNode(I, state);
  1877. return;
  1878. }
  1879. }
  1880. llvm_unreachable("No block with label.");
  1881. }
  1882. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1883. // Dispatch to the first target and mark it as a sink.
  1884. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1885. // FIXME: add checker visit.
  1886. // UndefBranches.insert(N);
  1887. return;
  1888. }
  1889. // This is really a catch-all. We don't support symbolics yet.
  1890. // FIXME: Implement dispatch for symbolic pointers.
  1891. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
  1892. builder.generateNode(I, state);
  1893. }
  1894. void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
  1895. ExplodedNode *Pred,
  1896. ExplodedNodeSet &Dst,
  1897. const BlockEdge &L) {
  1898. SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
  1899. getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
  1900. }
  1901. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1902. /// nodes when the control reaches the end of a function.
  1903. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1904. ExplodedNode *Pred,
  1905. const ReturnStmt *RS) {
  1906. // FIXME: We currently cannot assert that temporaries are clear, because
  1907. // lifetime extended temporaries are not always modelled correctly. In some
  1908. // cases when we materialize the temporary, we do
  1909. // createTemporaryRegionIfNeeded(), and the region changes, and also the
  1910. // respective destructor becomes automatic from temporary. So for now clean up
  1911. // the state manually before asserting. Ideally, the code above the assertion
  1912. // should go away, but the assertion should remain.
  1913. {
  1914. ExplodedNodeSet CleanUpObjects;
  1915. NodeBuilder Bldr(Pred, CleanUpObjects, BC);
  1916. ProgramStateRef State = Pred->getState();
  1917. const LocationContext *FromLC = Pred->getLocationContext();
  1918. const LocationContext *ToLC = FromLC->getCurrentStackFrame()->getParent();
  1919. const LocationContext *LC = FromLC;
  1920. while (LC != ToLC) {
  1921. assert(LC && "ToLC must be a parent of FromLC!");
  1922. for (auto I : State->get<ObjectsUnderConstruction>())
  1923. if (I.first.getLocationContext() == LC) {
  1924. // The comment above only pardons us for not cleaning up a
  1925. // CXXBindTemporaryExpr. If any other statements are found here,
  1926. // it must be a separate problem.
  1927. assert(isa<CXXBindTemporaryExpr>(I.first.getStmt()));
  1928. State = State->remove<ObjectsUnderConstruction>(I.first);
  1929. }
  1930. LC = LC->getParent();
  1931. }
  1932. if (State != Pred->getState()) {
  1933. Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
  1934. if (!Pred) {
  1935. // The node with clean temporaries already exists. We might have reached
  1936. // it on a path on which we initialize different temporaries.
  1937. return;
  1938. }
  1939. }
  1940. }
  1941. assert(areAllObjectsFullyConstructed(Pred->getState(),
  1942. Pred->getLocationContext(),
  1943. Pred->getStackFrame()->getParent()));
  1944. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1945. StateMgr.EndPath(Pred->getState());
  1946. ExplodedNodeSet Dst;
  1947. if (Pred->getLocationContext()->inTopFrame()) {
  1948. // Remove dead symbols.
  1949. ExplodedNodeSet AfterRemovedDead;
  1950. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  1951. // Notify checkers.
  1952. for (const auto I : AfterRemovedDead)
  1953. getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this);
  1954. } else {
  1955. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
  1956. }
  1957. Engine.enqueueEndOfFunction(Dst, RS);
  1958. }
  1959. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1960. /// nodes by processing the 'effects' of a switch statement.
  1961. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1962. using iterator = SwitchNodeBuilder::iterator;
  1963. ProgramStateRef state = builder.getState();
  1964. const Expr *CondE = builder.getCondition();
  1965. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1966. if (CondV_untested.isUndef()) {
  1967. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1968. // FIXME: add checker
  1969. //UndefBranches.insert(N);
  1970. return;
  1971. }
  1972. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  1973. ProgramStateRef DefaultSt = state;
  1974. iterator I = builder.begin(), EI = builder.end();
  1975. bool defaultIsFeasible = I == EI;
  1976. for ( ; I != EI; ++I) {
  1977. // Successor may be pruned out during CFG construction.
  1978. if (!I.getBlock())
  1979. continue;
  1980. const CaseStmt *Case = I.getCase();
  1981. // Evaluate the LHS of the case value.
  1982. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  1983. assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
  1984. // Get the RHS of the case, if it exists.
  1985. llvm::APSInt V2;
  1986. if (const Expr *E = Case->getRHS())
  1987. V2 = E->EvaluateKnownConstInt(getContext());
  1988. else
  1989. V2 = V1;
  1990. ProgramStateRef StateCase;
  1991. if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
  1992. std::tie(StateCase, DefaultSt) =
  1993. DefaultSt->assumeInclusiveRange(*NL, V1, V2);
  1994. else // UnknownVal
  1995. StateCase = DefaultSt;
  1996. if (StateCase)
  1997. builder.generateCaseStmtNode(I, StateCase);
  1998. // Now "assume" that the case doesn't match. Add this state
  1999. // to the default state (if it is feasible).
  2000. if (DefaultSt)
  2001. defaultIsFeasible = true;
  2002. else {
  2003. defaultIsFeasible = false;
  2004. break;
  2005. }
  2006. }
  2007. if (!defaultIsFeasible)
  2008. return;
  2009. // If we have switch(enum value), the default branch is not
  2010. // feasible if all of the enum constants not covered by 'case:' statements
  2011. // are not feasible values for the switch condition.
  2012. //
  2013. // Note that this isn't as accurate as it could be. Even if there isn't
  2014. // a case for a particular enum value as long as that enum value isn't
  2015. // feasible then it shouldn't be considered for making 'default:' reachable.
  2016. const SwitchStmt *SS = builder.getSwitch();
  2017. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  2018. if (CondExpr->getType()->getAs<EnumType>()) {
  2019. if (SS->isAllEnumCasesCovered())
  2020. return;
  2021. }
  2022. builder.generateDefaultCaseNode(DefaultSt);
  2023. }
  2024. //===----------------------------------------------------------------------===//
  2025. // Transfer functions: Loads and stores.
  2026. //===----------------------------------------------------------------------===//
  2027. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  2028. ExplodedNode *Pred,
  2029. ExplodedNodeSet &Dst) {
  2030. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2031. ProgramStateRef state = Pred->getState();
  2032. const LocationContext *LCtx = Pred->getLocationContext();
  2033. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2034. // C permits "extern void v", and if you cast the address to a valid type,
  2035. // you can even do things with it. We simply pretend
  2036. assert(Ex->isGLValue() || VD->getType()->isVoidType());
  2037. const LocationContext *LocCtxt = Pred->getLocationContext();
  2038. const Decl *D = LocCtxt->getDecl();
  2039. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  2040. const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
  2041. Optional<std::pair<SVal, QualType>> VInfo;
  2042. if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
  2043. DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
  2044. MD->getParent()->isLambda()) {
  2045. // Lookup the field of the lambda.
  2046. const CXXRecordDecl *CXXRec = MD->getParent();
  2047. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  2048. FieldDecl *LambdaThisCaptureField;
  2049. CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
  2050. // Sema follows a sequence of complex rules to determine whether the
  2051. // variable should be captured.
  2052. if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
  2053. Loc CXXThis =
  2054. svalBuilder.getCXXThis(MD, LocCtxt->getCurrentStackFrame());
  2055. SVal CXXThisVal = state->getSVal(CXXThis);
  2056. VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
  2057. }
  2058. }
  2059. if (!VInfo)
  2060. VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
  2061. SVal V = VInfo->first;
  2062. bool IsReference = VInfo->second->isReferenceType();
  2063. // For references, the 'lvalue' is the pointer address stored in the
  2064. // reference region.
  2065. if (IsReference) {
  2066. if (const MemRegion *R = V.getAsRegion())
  2067. V = state->getSVal(R);
  2068. else
  2069. V = UnknownVal();
  2070. }
  2071. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2072. ProgramPoint::PostLValueKind);
  2073. return;
  2074. }
  2075. if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
  2076. assert(!Ex->isGLValue());
  2077. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  2078. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  2079. return;
  2080. }
  2081. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2082. SVal V = svalBuilder.getFunctionPointer(FD);
  2083. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2084. ProgramPoint::PostLValueKind);
  2085. return;
  2086. }
  2087. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
  2088. // FIXME: Compute lvalue of field pointers-to-member.
  2089. // Right now we just use a non-null void pointer, so that it gives proper
  2090. // results in boolean contexts.
  2091. // FIXME: Maybe delegate this to the surrounding operator&.
  2092. // Note how this expression is lvalue, however pointer-to-member is NonLoc.
  2093. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  2094. currBldrCtx->blockCount());
  2095. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  2096. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2097. ProgramPoint::PostLValueKind);
  2098. return;
  2099. }
  2100. if (isa<BindingDecl>(D)) {
  2101. // FIXME: proper support for bound declarations.
  2102. // For now, let's just prevent crashing.
  2103. return;
  2104. }
  2105. llvm_unreachable("Support for this Decl not implemented.");
  2106. }
  2107. /// VisitArraySubscriptExpr - Transfer function for array accesses
  2108. void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
  2109. ExplodedNode *Pred,
  2110. ExplodedNodeSet &Dst){
  2111. const Expr *Base = A->getBase()->IgnoreParens();
  2112. const Expr *Idx = A->getIdx()->IgnoreParens();
  2113. ExplodedNodeSet CheckerPreStmt;
  2114. getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
  2115. ExplodedNodeSet EvalSet;
  2116. StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
  2117. bool IsVectorType = A->getBase()->getType()->isVectorType();
  2118. // The "like" case is for situations where C standard prohibits the type to
  2119. // be an lvalue, e.g. taking the address of a subscript of an expression of
  2120. // type "void *".
  2121. bool IsGLValueLike = A->isGLValue() ||
  2122. (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
  2123. for (auto *Node : CheckerPreStmt) {
  2124. const LocationContext *LCtx = Node->getLocationContext();
  2125. ProgramStateRef state = Node->getState();
  2126. if (IsGLValueLike) {
  2127. QualType T = A->getType();
  2128. // One of the forbidden LValue types! We still need to have sensible
  2129. // symbolic locations to represent this stuff. Note that arithmetic on
  2130. // void pointers is a GCC extension.
  2131. if (T->isVoidType())
  2132. T = getContext().CharTy;
  2133. SVal V = state->getLValue(T,
  2134. state->getSVal(Idx, LCtx),
  2135. state->getSVal(Base, LCtx));
  2136. Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
  2137. ProgramPoint::PostLValueKind);
  2138. } else if (IsVectorType) {
  2139. // FIXME: non-glvalue vector reads are not modelled.
  2140. Bldr.generateNode(A, Node, state, nullptr);
  2141. } else {
  2142. llvm_unreachable("Array subscript should be an lValue when not \
  2143. a vector and not a forbidden lvalue type");
  2144. }
  2145. }
  2146. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
  2147. }
  2148. /// VisitMemberExpr - Transfer function for member expressions.
  2149. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  2150. ExplodedNodeSet &Dst) {
  2151. // FIXME: Prechecks eventually go in ::Visit().
  2152. ExplodedNodeSet CheckedSet;
  2153. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
  2154. ExplodedNodeSet EvalSet;
  2155. ValueDecl *Member = M->getMemberDecl();
  2156. // Handle static member variables and enum constants accessed via
  2157. // member syntax.
  2158. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  2159. for (const auto I : CheckedSet)
  2160. VisitCommonDeclRefExpr(M, Member, I, EvalSet);
  2161. } else {
  2162. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  2163. ExplodedNodeSet Tmp;
  2164. for (const auto I : CheckedSet) {
  2165. ProgramStateRef state = I->getState();
  2166. const LocationContext *LCtx = I->getLocationContext();
  2167. Expr *BaseExpr = M->getBase();
  2168. // Handle C++ method calls.
  2169. if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
  2170. if (MD->isInstance())
  2171. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  2172. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  2173. state = state->BindExpr(M, LCtx, MDVal);
  2174. Bldr.generateNode(M, I, state);
  2175. continue;
  2176. }
  2177. // Handle regular struct fields / member variables.
  2178. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  2179. SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
  2180. const auto *field = cast<FieldDecl>(Member);
  2181. SVal L = state->getLValue(field, baseExprVal);
  2182. if (M->isGLValue() || M->getType()->isArrayType()) {
  2183. // We special-case rvalues of array type because the analyzer cannot
  2184. // reason about them, since we expect all regions to be wrapped in Locs.
  2185. // We instead treat these as lvalues and assume that they will decay to
  2186. // pointers as soon as they are used.
  2187. if (!M->isGLValue()) {
  2188. assert(M->getType()->isArrayType());
  2189. const auto *PE =
  2190. dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
  2191. if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
  2192. llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
  2193. }
  2194. }
  2195. if (field->getType()->isReferenceType()) {
  2196. if (const MemRegion *R = L.getAsRegion())
  2197. L = state->getSVal(R);
  2198. else
  2199. L = UnknownVal();
  2200. }
  2201. Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
  2202. ProgramPoint::PostLValueKind);
  2203. } else {
  2204. Bldr.takeNodes(I);
  2205. evalLoad(Tmp, M, M, I, state, L);
  2206. Bldr.addNodes(Tmp);
  2207. }
  2208. }
  2209. }
  2210. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
  2211. }
  2212. void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
  2213. ExplodedNodeSet &Dst) {
  2214. ExplodedNodeSet AfterPreSet;
  2215. getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
  2216. // For now, treat all the arguments to C11 atomics as escaping.
  2217. // FIXME: Ideally we should model the behavior of the atomics precisely here.
  2218. ExplodedNodeSet AfterInvalidateSet;
  2219. StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
  2220. for (const auto I : AfterPreSet) {
  2221. ProgramStateRef State = I->getState();
  2222. const LocationContext *LCtx = I->getLocationContext();
  2223. SmallVector<SVal, 8> ValuesToInvalidate;
  2224. for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
  2225. const Expr *SubExpr = AE->getSubExprs()[SI];
  2226. SVal SubExprVal = State->getSVal(SubExpr, LCtx);
  2227. ValuesToInvalidate.push_back(SubExprVal);
  2228. }
  2229. State = State->invalidateRegions(ValuesToInvalidate, AE,
  2230. currBldrCtx->blockCount(),
  2231. LCtx,
  2232. /*CausedByPointerEscape*/true,
  2233. /*Symbols=*/nullptr);
  2234. SVal ResultVal = UnknownVal();
  2235. State = State->BindExpr(AE, LCtx, ResultVal);
  2236. Bldr.generateNode(AE, I, State, nullptr,
  2237. ProgramPoint::PostStmtKind);
  2238. }
  2239. getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
  2240. }
  2241. // A value escapes in three possible cases:
  2242. // (1) We are binding to something that is not a memory region.
  2243. // (2) We are binding to a MemrRegion that does not have stack storage.
  2244. // (3) We are binding to a MemRegion with stack storage that the store
  2245. // does not understand.
  2246. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  2247. SVal Loc,
  2248. SVal Val,
  2249. const LocationContext *LCtx) {
  2250. // Are we storing to something that causes the value to "escape"?
  2251. bool escapes = true;
  2252. // TODO: Move to StoreManager.
  2253. if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
  2254. escapes = !regionLoc->getRegion()->hasStackStorage();
  2255. if (!escapes) {
  2256. // To test (3), generate a new state with the binding added. If it is
  2257. // the same state, then it escapes (since the store cannot represent
  2258. // the binding).
  2259. // Do this only if we know that the store is not supposed to generate the
  2260. // same state.
  2261. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  2262. if (StoredVal != Val)
  2263. escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
  2264. }
  2265. }
  2266. // If our store can represent the binding and we aren't storing to something
  2267. // that doesn't have local storage then just return and have the simulation
  2268. // state continue as is.
  2269. if (!escapes)
  2270. return State;
  2271. // Otherwise, find all symbols referenced by 'val' that we are tracking
  2272. // and stop tracking them.
  2273. State = escapeValue(State, Val, PSK_EscapeOnBind);
  2274. return State;
  2275. }
  2276. ProgramStateRef
  2277. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  2278. const InvalidatedSymbols *Invalidated,
  2279. ArrayRef<const MemRegion *> ExplicitRegions,
  2280. ArrayRef<const MemRegion *> Regions,
  2281. const CallEvent *Call,
  2282. RegionAndSymbolInvalidationTraits &ITraits) {
  2283. if (!Invalidated || Invalidated->empty())
  2284. return State;
  2285. if (!Call)
  2286. return getCheckerManager().runCheckersForPointerEscape(State,
  2287. *Invalidated,
  2288. nullptr,
  2289. PSK_EscapeOther,
  2290. &ITraits);
  2291. // If the symbols were invalidated by a call, we want to find out which ones
  2292. // were invalidated directly due to being arguments to the call.
  2293. InvalidatedSymbols SymbolsDirectlyInvalidated;
  2294. for (const auto I : ExplicitRegions) {
  2295. if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
  2296. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  2297. }
  2298. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  2299. for (const auto &sym : *Invalidated) {
  2300. if (SymbolsDirectlyInvalidated.count(sym))
  2301. continue;
  2302. SymbolsIndirectlyInvalidated.insert(sym);
  2303. }
  2304. if (!SymbolsDirectlyInvalidated.empty())
  2305. State = getCheckerManager().runCheckersForPointerEscape(State,
  2306. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  2307. // Notify about the symbols that get indirectly invalidated by the call.
  2308. if (!SymbolsIndirectlyInvalidated.empty())
  2309. State = getCheckerManager().runCheckersForPointerEscape(State,
  2310. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  2311. return State;
  2312. }
  2313. /// evalBind - Handle the semantics of binding a value to a specific location.
  2314. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  2315. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  2316. ExplodedNode *Pred,
  2317. SVal location, SVal Val,
  2318. bool atDeclInit, const ProgramPoint *PP) {
  2319. const LocationContext *LC = Pred->getLocationContext();
  2320. PostStmt PS(StoreE, LC);
  2321. if (!PP)
  2322. PP = &PS;
  2323. // Do a previsit of the bind.
  2324. ExplodedNodeSet CheckedSet;
  2325. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  2326. StoreE, *this, *PP);
  2327. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  2328. // If the location is not a 'Loc', it will already be handled by
  2329. // the checkers. There is nothing left to do.
  2330. if (!location.getAs<Loc>()) {
  2331. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
  2332. /*tag*/nullptr);
  2333. ProgramStateRef state = Pred->getState();
  2334. state = processPointerEscapedOnBind(state, location, Val, LC);
  2335. Bldr.generateNode(L, state, Pred);
  2336. return;
  2337. }
  2338. for (const auto PredI : CheckedSet) {
  2339. ProgramStateRef state = PredI->getState();
  2340. state = processPointerEscapedOnBind(state, location, Val, LC);
  2341. // When binding the value, pass on the hint that this is a initialization.
  2342. // For initializations, we do not need to inform clients of region
  2343. // changes.
  2344. state = state->bindLoc(location.castAs<Loc>(),
  2345. Val, LC, /* notifyChanges = */ !atDeclInit);
  2346. const MemRegion *LocReg = nullptr;
  2347. if (Optional<loc::MemRegionVal> LocRegVal =
  2348. location.getAs<loc::MemRegionVal>()) {
  2349. LocReg = LocRegVal->getRegion();
  2350. }
  2351. const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
  2352. Bldr.generateNode(L, state, PredI);
  2353. }
  2354. }
  2355. /// evalStore - Handle the semantics of a store via an assignment.
  2356. /// @param Dst The node set to store generated state nodes
  2357. /// @param AssignE The assignment expression if the store happens in an
  2358. /// assignment.
  2359. /// @param LocationE The location expression that is stored to.
  2360. /// @param state The current simulation state
  2361. /// @param location The location to store the value
  2362. /// @param Val The value to be stored
  2363. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  2364. const Expr *LocationE,
  2365. ExplodedNode *Pred,
  2366. ProgramStateRef state, SVal location, SVal Val,
  2367. const ProgramPointTag *tag) {
  2368. // Proceed with the store. We use AssignE as the anchor for the PostStore
  2369. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  2370. const Expr *StoreE = AssignE ? AssignE : LocationE;
  2371. // Evaluate the location (checks for bad dereferences).
  2372. ExplodedNodeSet Tmp;
  2373. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  2374. if (Tmp.empty())
  2375. return;
  2376. if (location.isUndef())
  2377. return;
  2378. for (const auto I : Tmp)
  2379. evalBind(Dst, StoreE, I, location, Val, false);
  2380. }
  2381. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  2382. const Expr *NodeEx,
  2383. const Expr *BoundEx,
  2384. ExplodedNode *Pred,
  2385. ProgramStateRef state,
  2386. SVal location,
  2387. const ProgramPointTag *tag,
  2388. QualType LoadTy) {
  2389. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  2390. assert(NodeEx);
  2391. assert(BoundEx);
  2392. // Evaluate the location (checks for bad dereferences).
  2393. ExplodedNodeSet Tmp;
  2394. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  2395. if (Tmp.empty())
  2396. return;
  2397. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  2398. if (location.isUndef())
  2399. return;
  2400. // Proceed with the load.
  2401. for (const auto I : Tmp) {
  2402. state = I->getState();
  2403. const LocationContext *LCtx = I->getLocationContext();
  2404. SVal V = UnknownVal();
  2405. if (location.isValid()) {
  2406. if (LoadTy.isNull())
  2407. LoadTy = BoundEx->getType();
  2408. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  2409. }
  2410. Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
  2411. ProgramPoint::PostLoadKind);
  2412. }
  2413. }
  2414. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  2415. const Stmt *NodeEx,
  2416. const Stmt *BoundEx,
  2417. ExplodedNode *Pred,
  2418. ProgramStateRef state,
  2419. SVal location,
  2420. const ProgramPointTag *tag,
  2421. bool isLoad) {
  2422. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  2423. // Early checks for performance reason.
  2424. if (location.isUnknown()) {
  2425. return;
  2426. }
  2427. ExplodedNodeSet Src;
  2428. BldrTop.takeNodes(Pred);
  2429. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  2430. if (Pred->getState() != state) {
  2431. // Associate this new state with an ExplodedNode.
  2432. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  2433. // int *p;
  2434. // p = 0;
  2435. // *p = 0xDEADBEEF;
  2436. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  2437. // instead "int *p" is noted as
  2438. // "Variable 'p' initialized to a null pointer value"
  2439. static SimpleProgramPointTag tag(TagProviderName, "Location");
  2440. Bldr.generateNode(NodeEx, Pred, state, &tag);
  2441. }
  2442. ExplodedNodeSet Tmp;
  2443. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  2444. NodeEx, BoundEx, *this);
  2445. BldrTop.addNodes(Tmp);
  2446. }
  2447. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  2448. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  2449. static SimpleProgramPointTag
  2450. eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
  2451. "Eagerly Assume True"),
  2452. eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
  2453. "Eagerly Assume False");
  2454. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  2455. &eagerlyAssumeBinOpBifurcationFalse);
  2456. }
  2457. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  2458. ExplodedNodeSet &Src,
  2459. const Expr *Ex) {
  2460. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  2461. for (const auto Pred : Src) {
  2462. // Test if the previous node was as the same expression. This can happen
  2463. // when the expression fails to evaluate to anything meaningful and
  2464. // (as an optimization) we don't generate a node.
  2465. ProgramPoint P = Pred->getLocation();
  2466. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  2467. continue;
  2468. }
  2469. ProgramStateRef state = Pred->getState();
  2470. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  2471. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  2472. if (SEV && SEV->isExpression()) {
  2473. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  2474. geteagerlyAssumeBinOpBifurcationTags();
  2475. ProgramStateRef StateTrue, StateFalse;
  2476. std::tie(StateTrue, StateFalse) = state->assume(*SEV);
  2477. // First assume that the condition is true.
  2478. if (StateTrue) {
  2479. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  2480. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  2481. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  2482. }
  2483. // Next, assume that the condition is false.
  2484. if (StateFalse) {
  2485. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  2486. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  2487. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  2488. }
  2489. }
  2490. }
  2491. }
  2492. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  2493. ExplodedNodeSet &Dst) {
  2494. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2495. // We have processed both the inputs and the outputs. All of the outputs
  2496. // should evaluate to Locs. Nuke all of their values.
  2497. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2498. // which interprets the inline asm and stores proper results in the
  2499. // outputs.
  2500. ProgramStateRef state = Pred->getState();
  2501. for (const Expr *O : A->outputs()) {
  2502. SVal X = state->getSVal(O, Pred->getLocationContext());
  2503. assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  2504. if (Optional<Loc> LV = X.getAs<Loc>())
  2505. state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
  2506. }
  2507. Bldr.generateNode(A, Pred, state);
  2508. }
  2509. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  2510. ExplodedNodeSet &Dst) {
  2511. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2512. Bldr.generateNode(A, Pred, Pred->getState());
  2513. }
  2514. //===----------------------------------------------------------------------===//
  2515. // Visualization.
  2516. //===----------------------------------------------------------------------===//
  2517. #ifndef NDEBUG
  2518. static ExprEngine* GraphPrintCheckerState;
  2519. static SourceManager* GraphPrintSourceManager;
  2520. namespace llvm {
  2521. template<>
  2522. struct DOTGraphTraits<ExplodedNode*> : public DefaultDOTGraphTraits {
  2523. DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  2524. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  2525. // work.
  2526. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  2527. return {};
  2528. }
  2529. // De-duplicate some source location pretty-printing.
  2530. static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
  2531. if (SLoc.isFileID()) {
  2532. Out << "\\lline="
  2533. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2534. << " col="
  2535. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  2536. << "\\l";
  2537. }
  2538. }
  2539. static std::string getNodeLabel(const ExplodedNode *N, void*){
  2540. std::string sbuf;
  2541. llvm::raw_string_ostream Out(sbuf);
  2542. // Program Location.
  2543. ProgramPoint Loc = N->getLocation();
  2544. switch (Loc.getKind()) {
  2545. case ProgramPoint::BlockEntranceKind:
  2546. Out << "Block Entrance: B"
  2547. << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
  2548. break;
  2549. case ProgramPoint::BlockExitKind:
  2550. assert(false);
  2551. break;
  2552. case ProgramPoint::CallEnterKind:
  2553. Out << "CallEnter";
  2554. break;
  2555. case ProgramPoint::CallExitBeginKind:
  2556. Out << "CallExitBegin";
  2557. break;
  2558. case ProgramPoint::CallExitEndKind:
  2559. Out << "CallExitEnd";
  2560. break;
  2561. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  2562. Out << "PostStmtPurgeDeadSymbols";
  2563. break;
  2564. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  2565. Out << "PreStmtPurgeDeadSymbols";
  2566. break;
  2567. case ProgramPoint::EpsilonKind:
  2568. Out << "Epsilon Point";
  2569. break;
  2570. case ProgramPoint::LoopExitKind: {
  2571. LoopExit LE = Loc.castAs<LoopExit>();
  2572. Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
  2573. break;
  2574. }
  2575. case ProgramPoint::PreImplicitCallKind: {
  2576. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  2577. Out << "PreCall: ";
  2578. // FIXME: Get proper printing options.
  2579. PC.getDecl()->print(Out, LangOptions());
  2580. printLocation(Out, PC.getLocation());
  2581. break;
  2582. }
  2583. case ProgramPoint::PostImplicitCallKind: {
  2584. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  2585. Out << "PostCall: ";
  2586. // FIXME: Get proper printing options.
  2587. PC.getDecl()->print(Out, LangOptions());
  2588. printLocation(Out, PC.getLocation());
  2589. break;
  2590. }
  2591. case ProgramPoint::PostInitializerKind: {
  2592. Out << "PostInitializer: ";
  2593. const CXXCtorInitializer *Init =
  2594. Loc.castAs<PostInitializer>().getInitializer();
  2595. if (const FieldDecl *FD = Init->getAnyMember())
  2596. Out << *FD;
  2597. else {
  2598. QualType Ty = Init->getTypeSourceInfo()->getType();
  2599. Ty = Ty.getLocalUnqualifiedType();
  2600. LangOptions LO; // FIXME.
  2601. Ty.print(Out, LO);
  2602. }
  2603. break;
  2604. }
  2605. case ProgramPoint::BlockEdgeKind: {
  2606. const BlockEdge &E = Loc.castAs<BlockEdge>();
  2607. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  2608. << E.getDst()->getBlockID() << ')';
  2609. if (const Stmt *T = E.getSrc()->getTerminator()) {
  2610. SourceLocation SLoc = T->getLocStart();
  2611. Out << "\\|Terminator: ";
  2612. LangOptions LO; // FIXME.
  2613. E.getSrc()->printTerminator(Out, LO);
  2614. if (SLoc.isFileID()) {
  2615. Out << "\\lline="
  2616. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2617. << " col="
  2618. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  2619. }
  2620. if (isa<SwitchStmt>(T)) {
  2621. const Stmt *Label = E.getDst()->getLabel();
  2622. if (Label) {
  2623. if (const auto *C = dyn_cast<CaseStmt>(Label)) {
  2624. Out << "\\lcase ";
  2625. LangOptions LO; // FIXME.
  2626. if (C->getLHS())
  2627. C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
  2628. if (const Stmt *RHS = C->getRHS()) {
  2629. Out << " .. ";
  2630. RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
  2631. }
  2632. Out << ":";
  2633. }
  2634. else {
  2635. assert(isa<DefaultStmt>(Label));
  2636. Out << "\\ldefault:";
  2637. }
  2638. }
  2639. else
  2640. Out << "\\l(implicit) default:";
  2641. }
  2642. else if (isa<IndirectGotoStmt>(T)) {
  2643. // FIXME
  2644. }
  2645. else {
  2646. Out << "\\lCondition: ";
  2647. if (*E.getSrc()->succ_begin() == E.getDst())
  2648. Out << "true";
  2649. else
  2650. Out << "false";
  2651. }
  2652. Out << "\\l";
  2653. }
  2654. break;
  2655. }
  2656. default: {
  2657. const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
  2658. assert(S != nullptr && "Expecting non-null Stmt");
  2659. Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
  2660. LangOptions LO; // FIXME.
  2661. S->printPretty(Out, nullptr, PrintingPolicy(LO));
  2662. printLocation(Out, S->getLocStart());
  2663. if (Loc.getAs<PreStmt>())
  2664. Out << "\\lPreStmt\\l;";
  2665. else if (Loc.getAs<PostLoad>())
  2666. Out << "\\lPostLoad\\l;";
  2667. else if (Loc.getAs<PostStore>())
  2668. Out << "\\lPostStore\\l";
  2669. else if (Loc.getAs<PostLValue>())
  2670. Out << "\\lPostLValue\\l";
  2671. else if (Loc.getAs<PostAllocatorCall>())
  2672. Out << "\\lPostAllocatorCall\\l";
  2673. break;
  2674. }
  2675. }
  2676. ProgramStateRef state = N->getState();
  2677. Out << "\\|StateID: " << (const void*) state.get()
  2678. << " NodeID: " << (const void*) N << "\\|";
  2679. state->printDOT(Out, N->getLocationContext());
  2680. Out << "\\l";
  2681. if (const ProgramPointTag *tag = Loc.getTag()) {
  2682. Out << "\\|Tag: " << tag->getTagDescription();
  2683. Out << "\\l";
  2684. }
  2685. return Out.str();
  2686. }
  2687. };
  2688. } // namespace llvm
  2689. #endif
  2690. void ExprEngine::ViewGraph(bool trim) {
  2691. #ifndef NDEBUG
  2692. if (trim) {
  2693. std::vector<const ExplodedNode *> Src;
  2694. // Flush any outstanding reports to make sure we cover all the nodes.
  2695. // This does not cause them to get displayed.
  2696. for (const auto I : BR)
  2697. const_cast<BugType *>(I)->FlushReports(BR);
  2698. // Iterate through the reports and get their nodes.
  2699. for (BugReporter::EQClasses_iterator
  2700. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2701. const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
  2702. if (N) Src.push_back(N);
  2703. }
  2704. ViewGraph(Src);
  2705. }
  2706. else {
  2707. GraphPrintCheckerState = this;
  2708. GraphPrintSourceManager = &getContext().getSourceManager();
  2709. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2710. GraphPrintCheckerState = nullptr;
  2711. GraphPrintSourceManager = nullptr;
  2712. }
  2713. #endif
  2714. }
  2715. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2716. #ifndef NDEBUG
  2717. GraphPrintCheckerState = this;
  2718. GraphPrintSourceManager = &getContext().getSourceManager();
  2719. std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2720. if (!TrimmedG.get())
  2721. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2722. else
  2723. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2724. GraphPrintCheckerState = nullptr;
  2725. GraphPrintSourceManager = nullptr;
  2726. #endif
  2727. }