ExprEngine.cpp 118 KB

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