ExprEngine.cpp 124 KB

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