CFG.cpp 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569
  1. #include "clang/Analysis/CFG.h"
  2. #include "clang/AST/ASTContext.h"
  3. #include "clang/AST/Attr.h"
  4. #include "clang/AST/CharUnits.h"
  5. #include "clang/AST/DeclCXX.h"
  6. #include "clang/AST/PrettyPrinter.h"
  7. #include "clang/AST/StmtVisitor.h"
  8. #include "clang/Basic/Builtins.h"
  9. #include "llvm/ADT/DenseMap.h"
  10. #include <memory>
  11. #include "llvm/ADT/SmallPtrSet.h"
  12. #include "llvm/Support/Allocator.h"
  13. #include "llvm/Support/Format.h"
  14. #include "llvm/Support/GraphWriter.h"
  15. #include "llvm/Support/SaveAndRestore.h"
  16. using namespace clang;
  17. namespace {
  18. static SourceLocation GetEndLoc(Decl *D) {
  19. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  20. if (Expr *Ex = VD->getInit())
  21. return Ex->getSourceRange().getEnd();
  22. return D->getLocation();
  23. }
  24. class CFGBuilder;
  25. /// The CFG builder uses a recursive algorithm to build the CFG. When
  26. /// we process an expression, sometimes we know that we must add the
  27. /// subexpressions as block-level expressions. For example:
  28. ///
  29. /// exp1 || exp2
  30. ///
  31. /// When processing the '||' expression, we know that exp1 and exp2
  32. /// need to be added as block-level expressions, even though they
  33. /// might not normally need to be. AddStmtChoice records this
  34. /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
  35. /// the builder has an option not to add a subexpression as a
  36. /// block-level expression.
  37. ///
  38. class AddStmtChoice {
  39. public:
  40. enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
  41. AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
  42. bool alwaysAdd(CFGBuilder &builder,
  43. const Stmt *stmt) const;
  44. /// Return a copy of this object, except with the 'always-add' bit
  45. /// set as specified.
  46. AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
  47. return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
  48. }
  49. private:
  50. Kind kind;
  51. };
  52. /// LocalScope - Node in tree of local scopes created for C++ implicit
  53. /// destructor calls generation. It contains list of automatic variables
  54. /// declared in the scope and link to position in previous scope this scope
  55. /// began in.
  56. ///
  57. /// The process of creating local scopes is as follows:
  58. /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
  59. /// - Before processing statements in scope (e.g. CompoundStmt) create
  60. /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
  61. /// and set CFGBuilder::ScopePos to the end of new scope,
  62. /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
  63. /// at this VarDecl,
  64. /// - For every normal (without jump) end of scope add to CFGBlock destructors
  65. /// for objects in the current scope,
  66. /// - For every jump add to CFGBlock destructors for objects
  67. /// between CFGBuilder::ScopePos and local scope position saved for jump
  68. /// target. Thanks to C++ restrictions on goto jumps we can be sure that
  69. /// jump target position will be on the path to root from CFGBuilder::ScopePos
  70. /// (adding any variable that doesn't need constructor to be called to
  71. /// LocalScope can break this assumption),
  72. ///
  73. class LocalScope {
  74. public:
  75. typedef BumpVector<VarDecl*> AutomaticVarsTy;
  76. /// const_iterator - Iterates local scope backwards and jumps to previous
  77. /// scope on reaching the beginning of currently iterated scope.
  78. class const_iterator {
  79. const LocalScope* Scope;
  80. /// VarIter is guaranteed to be greater then 0 for every valid iterator.
  81. /// Invalid iterator (with null Scope) has VarIter equal to 0.
  82. unsigned VarIter;
  83. public:
  84. /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
  85. /// Incrementing invalid iterator is allowed and will result in invalid
  86. /// iterator.
  87. const_iterator()
  88. : Scope(nullptr), VarIter(0) {}
  89. /// Create valid iterator. In case when S.Prev is an invalid iterator and
  90. /// I is equal to 0, this will create invalid iterator.
  91. const_iterator(const LocalScope& S, unsigned I)
  92. : Scope(&S), VarIter(I) {
  93. // Iterator to "end" of scope is not allowed. Handle it by going up
  94. // in scopes tree possibly up to invalid iterator in the root.
  95. if (VarIter == 0 && Scope)
  96. *this = Scope->Prev;
  97. }
  98. VarDecl *const* operator->() const {
  99. assert (Scope && "Dereferencing invalid iterator is not allowed");
  100. assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
  101. return &Scope->Vars[VarIter - 1];
  102. }
  103. VarDecl *operator*() const {
  104. return *this->operator->();
  105. }
  106. const_iterator &operator++() {
  107. if (!Scope)
  108. return *this;
  109. assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
  110. --VarIter;
  111. if (VarIter == 0)
  112. *this = Scope->Prev;
  113. return *this;
  114. }
  115. const_iterator operator++(int) {
  116. const_iterator P = *this;
  117. ++*this;
  118. return P;
  119. }
  120. bool operator==(const const_iterator &rhs) const {
  121. return Scope == rhs.Scope && VarIter == rhs.VarIter;
  122. }
  123. bool operator!=(const const_iterator &rhs) const {
  124. return !(*this == rhs);
  125. }
  126. explicit operator bool() const {
  127. return *this != const_iterator();
  128. }
  129. int distance(const_iterator L);
  130. };
  131. friend class const_iterator;
  132. private:
  133. BumpVectorContext ctx;
  134. /// Automatic variables in order of declaration.
  135. AutomaticVarsTy Vars;
  136. /// Iterator to variable in previous scope that was declared just before
  137. /// begin of this scope.
  138. const_iterator Prev;
  139. public:
  140. /// Constructs empty scope linked to previous scope in specified place.
  141. LocalScope(BumpVectorContext &ctx, const_iterator P)
  142. : ctx(ctx), Vars(ctx, 4), Prev(P) {}
  143. /// Begin of scope in direction of CFG building (backwards).
  144. const_iterator begin() const { return const_iterator(*this, Vars.size()); }
  145. void addVar(VarDecl *VD) {
  146. Vars.push_back(VD, ctx);
  147. }
  148. };
  149. /// distance - Calculates distance from this to L. L must be reachable from this
  150. /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
  151. /// number of scopes between this and L.
  152. int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
  153. int D = 0;
  154. const_iterator F = *this;
  155. while (F.Scope != L.Scope) {
  156. assert (F != const_iterator()
  157. && "L iterator is not reachable from F iterator.");
  158. D += F.VarIter;
  159. F = F.Scope->Prev;
  160. }
  161. D += F.VarIter - L.VarIter;
  162. return D;
  163. }
  164. /// Structure for specifying position in CFG during its build process. It
  165. /// consists of CFGBlock that specifies position in CFG and
  166. /// LocalScope::const_iterator that specifies position in LocalScope graph.
  167. struct BlockScopePosPair {
  168. BlockScopePosPair() : block(nullptr) {}
  169. BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
  170. : block(b), scopePosition(scopePos) {}
  171. CFGBlock *block;
  172. LocalScope::const_iterator scopePosition;
  173. };
  174. /// TryResult - a class representing a variant over the values
  175. /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
  176. /// and is used by the CFGBuilder to decide if a branch condition
  177. /// can be decided up front during CFG construction.
  178. class TryResult {
  179. int X;
  180. public:
  181. TryResult(bool b) : X(b ? 1 : 0) {}
  182. TryResult() : X(-1) {}
  183. bool isTrue() const { return X == 1; }
  184. bool isFalse() const { return X == 0; }
  185. bool isKnown() const { return X >= 0; }
  186. void negate() {
  187. assert(isKnown());
  188. X ^= 0x1;
  189. }
  190. };
  191. TryResult bothKnownTrue(TryResult R1, TryResult R2) {
  192. if (!R1.isKnown() || !R2.isKnown())
  193. return TryResult();
  194. return TryResult(R1.isTrue() && R2.isTrue());
  195. }
  196. class reverse_children {
  197. llvm::SmallVector<Stmt *, 12> childrenBuf;
  198. ArrayRef<Stmt*> children;
  199. public:
  200. reverse_children(Stmt *S);
  201. typedef ArrayRef<Stmt*>::reverse_iterator iterator;
  202. iterator begin() const { return children.rbegin(); }
  203. iterator end() const { return children.rend(); }
  204. };
  205. reverse_children::reverse_children(Stmt *S) {
  206. if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  207. children = CE->getRawSubExprs();
  208. return;
  209. }
  210. switch (S->getStmtClass()) {
  211. // Note: Fill in this switch with more cases we want to optimize.
  212. case Stmt::InitListExprClass: {
  213. InitListExpr *IE = cast<InitListExpr>(S);
  214. children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
  215. IE->getNumInits());
  216. return;
  217. }
  218. default:
  219. break;
  220. }
  221. // Default case for all other statements.
  222. for (Stmt *SubStmt : S->children())
  223. childrenBuf.push_back(SubStmt);
  224. // This needs to be done *after* childrenBuf has been populated.
  225. children = childrenBuf;
  226. }
  227. /// CFGBuilder - This class implements CFG construction from an AST.
  228. /// The builder is stateful: an instance of the builder should be used to only
  229. /// construct a single CFG.
  230. ///
  231. /// Example usage:
  232. ///
  233. /// CFGBuilder builder;
  234. /// CFG* cfg = builder.BuildAST(stmt1);
  235. ///
  236. /// CFG construction is done via a recursive walk of an AST. We actually parse
  237. /// the AST in reverse order so that the successor of a basic block is
  238. /// constructed prior to its predecessor. This allows us to nicely capture
  239. /// implicit fall-throughs without extra basic blocks.
  240. ///
  241. class CFGBuilder {
  242. typedef BlockScopePosPair JumpTarget;
  243. typedef BlockScopePosPair JumpSource;
  244. ASTContext *Context;
  245. std::unique_ptr<CFG> cfg;
  246. CFGBlock *Block;
  247. CFGBlock *Succ;
  248. JumpTarget ContinueJumpTarget;
  249. JumpTarget BreakJumpTarget;
  250. CFGBlock *SwitchTerminatedBlock;
  251. CFGBlock *DefaultCaseBlock;
  252. CFGBlock *TryTerminatedBlock;
  253. // Current position in local scope.
  254. LocalScope::const_iterator ScopePos;
  255. // LabelMap records the mapping from Label expressions to their jump targets.
  256. typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
  257. LabelMapTy LabelMap;
  258. // A list of blocks that end with a "goto" that must be backpatched to their
  259. // resolved targets upon completion of CFG construction.
  260. typedef std::vector<JumpSource> BackpatchBlocksTy;
  261. BackpatchBlocksTy BackpatchBlocks;
  262. // A list of labels whose address has been taken (for indirect gotos).
  263. typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
  264. LabelSetTy AddressTakenLabels;
  265. bool badCFG;
  266. const CFG::BuildOptions &BuildOpts;
  267. // State to track for building switch statements.
  268. bool switchExclusivelyCovered;
  269. Expr::EvalResult *switchCond;
  270. CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
  271. const Stmt *lastLookup;
  272. // Caches boolean evaluations of expressions to avoid multiple re-evaluations
  273. // during construction of branches for chained logical operators.
  274. typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
  275. CachedBoolEvalsTy CachedBoolEvals;
  276. public:
  277. explicit CFGBuilder(ASTContext *astContext,
  278. const CFG::BuildOptions &buildOpts)
  279. : Context(astContext), cfg(new CFG()), // crew a new CFG
  280. Block(nullptr), Succ(nullptr),
  281. SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
  282. TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
  283. switchExclusivelyCovered(false), switchCond(nullptr),
  284. cachedEntry(nullptr), lastLookup(nullptr) {}
  285. // buildCFG - Used by external clients to construct the CFG.
  286. std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
  287. bool alwaysAdd(const Stmt *stmt);
  288. private:
  289. // Visitors to walk an AST and construct the CFG.
  290. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
  291. CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
  292. CFGBlock *VisitBreakStmt(BreakStmt *B);
  293. CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
  294. CFGBlock *VisitCaseStmt(CaseStmt *C);
  295. CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
  296. CFGBlock *VisitCompoundStmt(CompoundStmt *C);
  297. CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
  298. AddStmtChoice asc);
  299. CFGBlock *VisitContinueStmt(ContinueStmt *C);
  300. CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  301. AddStmtChoice asc);
  302. CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
  303. CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
  304. CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
  305. CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
  306. CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
  307. CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  308. AddStmtChoice asc);
  309. CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  310. AddStmtChoice asc);
  311. CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
  312. CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
  313. CFGBlock *VisitDeclStmt(DeclStmt *DS);
  314. CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
  315. CFGBlock *VisitDefaultStmt(DefaultStmt *D);
  316. CFGBlock *VisitDoStmt(DoStmt *D);
  317. CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
  318. CFGBlock *VisitForStmt(ForStmt *F);
  319. CFGBlock *VisitGotoStmt(GotoStmt *G);
  320. CFGBlock *VisitIfStmt(IfStmt *I);
  321. CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
  322. CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
  323. CFGBlock *VisitLabelStmt(LabelStmt *L);
  324. CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
  325. CFGBlock *VisitLogicalOperator(BinaryOperator *B);
  326. std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
  327. Stmt *Term,
  328. CFGBlock *TrueBlock,
  329. CFGBlock *FalseBlock);
  330. CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
  331. CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
  332. CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  333. CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
  334. CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
  335. CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
  336. CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
  337. CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
  338. CFGBlock *VisitReturnStmt(ReturnStmt *R);
  339. CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
  340. CFGBlock *VisitSwitchStmt(SwitchStmt *S);
  341. CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  342. AddStmtChoice asc);
  343. CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
  344. CFGBlock *VisitWhileStmt(WhileStmt *W);
  345. CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
  346. CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
  347. CFGBlock *VisitChildren(Stmt *S);
  348. CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
  349. /// When creating the CFG for temporary destructors, we want to mirror the
  350. /// branch structure of the corresponding constructor calls.
  351. /// Thus, while visiting a statement for temporary destructors, we keep a
  352. /// context to keep track of the following information:
  353. /// - whether a subexpression is executed unconditionally
  354. /// - if a subexpression is executed conditionally, the first
  355. /// CXXBindTemporaryExpr we encounter in that subexpression (which
  356. /// corresponds to the last temporary destructor we have to call for this
  357. /// subexpression) and the CFG block at that point (which will become the
  358. /// successor block when inserting the decision point).
  359. ///
  360. /// That way, we can build the branch structure for temporary destructors as
  361. /// follows:
  362. /// 1. If a subexpression is executed unconditionally, we add the temporary
  363. /// destructor calls to the current block.
  364. /// 2. If a subexpression is executed conditionally, when we encounter a
  365. /// CXXBindTemporaryExpr:
  366. /// a) If it is the first temporary destructor call in the subexpression,
  367. /// we remember the CXXBindTemporaryExpr and the current block in the
  368. /// TempDtorContext; we start a new block, and insert the temporary
  369. /// destructor call.
  370. /// b) Otherwise, add the temporary destructor call to the current block.
  371. /// 3. When we finished visiting a conditionally executed subexpression,
  372. /// and we found at least one temporary constructor during the visitation
  373. /// (2.a has executed), we insert a decision block that uses the
  374. /// CXXBindTemporaryExpr as terminator, and branches to the current block
  375. /// if the CXXBindTemporaryExpr was marked executed, and otherwise
  376. /// branches to the stored successor.
  377. struct TempDtorContext {
  378. TempDtorContext()
  379. : IsConditional(false), KnownExecuted(true), Succ(nullptr),
  380. TerminatorExpr(nullptr) {}
  381. TempDtorContext(TryResult KnownExecuted)
  382. : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
  383. TerminatorExpr(nullptr) {}
  384. /// Returns whether we need to start a new branch for a temporary destructor
  385. /// call. This is the case when the temporary destructor is
  386. /// conditionally executed, and it is the first one we encounter while
  387. /// visiting a subexpression - other temporary destructors at the same level
  388. /// will be added to the same block and are executed under the same
  389. /// condition.
  390. bool needsTempDtorBranch() const {
  391. return IsConditional && !TerminatorExpr;
  392. }
  393. /// Remember the successor S of a temporary destructor decision branch for
  394. /// the corresponding CXXBindTemporaryExpr E.
  395. void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
  396. Succ = S;
  397. TerminatorExpr = E;
  398. }
  399. const bool IsConditional;
  400. const TryResult KnownExecuted;
  401. CFGBlock *Succ;
  402. CXXBindTemporaryExpr *TerminatorExpr;
  403. };
  404. // Visitors to walk an AST and generate destructors of temporaries in
  405. // full expression.
  406. CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
  407. TempDtorContext &Context);
  408. CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
  409. CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
  410. TempDtorContext &Context);
  411. CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
  412. CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
  413. CFGBlock *VisitConditionalOperatorForTemporaryDtors(
  414. AbstractConditionalOperator *E, bool BindToTemporary,
  415. TempDtorContext &Context);
  416. void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
  417. CFGBlock *FalseSucc = nullptr);
  418. // NYS == Not Yet Supported
  419. CFGBlock *NYS() {
  420. badCFG = true;
  421. return Block;
  422. }
  423. void autoCreateBlock() { if (!Block) Block = createBlock(); }
  424. CFGBlock *createBlock(bool add_successor = true);
  425. CFGBlock *createNoReturnBlock();
  426. CFGBlock *addStmt(Stmt *S) {
  427. return Visit(S, AddStmtChoice::AlwaysAdd);
  428. }
  429. CFGBlock *addInitializer(CXXCtorInitializer *I);
  430. void addAutomaticObjDtors(LocalScope::const_iterator B,
  431. LocalScope::const_iterator E, Stmt *S);
  432. void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
  433. // Local scopes creation.
  434. LocalScope* createOrReuseLocalScope(LocalScope* Scope);
  435. void addLocalScopeForStmt(Stmt *S);
  436. LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
  437. LocalScope* Scope = nullptr);
  438. LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
  439. void addLocalScopeAndDtors(Stmt *S);
  440. // Interface to CFGBlock - adding CFGElements.
  441. void appendStmt(CFGBlock *B, const Stmt *S) {
  442. if (alwaysAdd(S) && cachedEntry)
  443. cachedEntry->second = B;
  444. // All block-level expressions should have already been IgnoreParens()ed.
  445. assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
  446. B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
  447. }
  448. void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
  449. B->appendInitializer(I, cfg->getBumpVectorContext());
  450. }
  451. void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
  452. B->appendNewAllocator(NE, cfg->getBumpVectorContext());
  453. }
  454. void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
  455. B->appendBaseDtor(BS, cfg->getBumpVectorContext());
  456. }
  457. void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
  458. B->appendMemberDtor(FD, cfg->getBumpVectorContext());
  459. }
  460. void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
  461. B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
  462. }
  463. void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
  464. B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
  465. }
  466. void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
  467. B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
  468. }
  469. void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  470. LocalScope::const_iterator B, LocalScope::const_iterator E);
  471. void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
  472. B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
  473. cfg->getBumpVectorContext());
  474. }
  475. /// Add a reachable successor to a block, with the alternate variant that is
  476. /// unreachable.
  477. void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
  478. B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
  479. cfg->getBumpVectorContext());
  480. }
  481. /// \brief Find a relational comparison with an expression evaluating to a
  482. /// boolean and a constant other than 0 and 1.
  483. /// e.g. if ((x < y) == 10)
  484. TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
  485. const Expr *LHSExpr = B->getLHS()->IgnoreParens();
  486. const Expr *RHSExpr = B->getRHS()->IgnoreParens();
  487. const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
  488. const Expr *BoolExpr = RHSExpr;
  489. bool IntFirst = true;
  490. if (!IntLiteral) {
  491. IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
  492. BoolExpr = LHSExpr;
  493. IntFirst = false;
  494. }
  495. if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
  496. return TryResult();
  497. llvm::APInt IntValue = IntLiteral->getValue();
  498. if ((IntValue == 1) || (IntValue == 0))
  499. return TryResult();
  500. bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
  501. !IntValue.isNegative();
  502. BinaryOperatorKind Bok = B->getOpcode();
  503. if (Bok == BO_GT || Bok == BO_GE) {
  504. // Always true for 10 > bool and bool > -1
  505. // Always false for -1 > bool and bool > 10
  506. return TryResult(IntFirst == IntLarger);
  507. } else {
  508. // Always true for -1 < bool and bool < 10
  509. // Always false for 10 < bool and bool < -1
  510. return TryResult(IntFirst != IntLarger);
  511. }
  512. }
  513. /// Find an incorrect equality comparison. Either with an expression
  514. /// evaluating to a boolean and a constant other than 0 and 1.
  515. /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
  516. /// true/false e.q. (x & 8) == 4.
  517. TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
  518. const Expr *LHSExpr = B->getLHS()->IgnoreParens();
  519. const Expr *RHSExpr = B->getRHS()->IgnoreParens();
  520. const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
  521. const Expr *BoolExpr = RHSExpr;
  522. if (!IntLiteral) {
  523. IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
  524. BoolExpr = LHSExpr;
  525. }
  526. if (!IntLiteral)
  527. return TryResult();
  528. const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
  529. if (BitOp && (BitOp->getOpcode() == BO_And ||
  530. BitOp->getOpcode() == BO_Or)) {
  531. const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
  532. const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
  533. const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
  534. if (!IntLiteral2)
  535. IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
  536. if (!IntLiteral2)
  537. return TryResult();
  538. llvm::APInt L1 = IntLiteral->getValue();
  539. llvm::APInt L2 = IntLiteral2->getValue();
  540. if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
  541. (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
  542. if (BuildOpts.Observer)
  543. BuildOpts.Observer->compareBitwiseEquality(B,
  544. B->getOpcode() != BO_EQ);
  545. TryResult(B->getOpcode() != BO_EQ);
  546. }
  547. } else if (BoolExpr->isKnownToHaveBooleanValue()) {
  548. llvm::APInt IntValue = IntLiteral->getValue();
  549. if ((IntValue == 1) || (IntValue == 0)) {
  550. return TryResult();
  551. }
  552. return TryResult(B->getOpcode() != BO_EQ);
  553. }
  554. return TryResult();
  555. }
  556. TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
  557. const llvm::APSInt &Value1,
  558. const llvm::APSInt &Value2) {
  559. assert(Value1.isSigned() == Value2.isSigned());
  560. switch (Relation) {
  561. default:
  562. return TryResult();
  563. case BO_EQ:
  564. return TryResult(Value1 == Value2);
  565. case BO_NE:
  566. return TryResult(Value1 != Value2);
  567. case BO_LT:
  568. return TryResult(Value1 < Value2);
  569. case BO_LE:
  570. return TryResult(Value1 <= Value2);
  571. case BO_GT:
  572. return TryResult(Value1 > Value2);
  573. case BO_GE:
  574. return TryResult(Value1 >= Value2);
  575. }
  576. }
  577. /// \brief Find a pair of comparison expressions with or without parentheses
  578. /// with a shared variable and constants and a logical operator between them
  579. /// that always evaluates to either true or false.
  580. /// e.g. if (x != 3 || x != 4)
  581. TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
  582. assert(B->isLogicalOp());
  583. const BinaryOperator *LHS =
  584. dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
  585. const BinaryOperator *RHS =
  586. dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
  587. if (!LHS || !RHS)
  588. return TryResult();
  589. if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
  590. return TryResult();
  591. BinaryOperatorKind BO1 = LHS->getOpcode();
  592. const DeclRefExpr *Decl1 =
  593. dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts());
  594. const IntegerLiteral *Literal1 =
  595. dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens());
  596. if (!Decl1 && !Literal1) {
  597. if (BO1 == BO_GT)
  598. BO1 = BO_LT;
  599. else if (BO1 == BO_GE)
  600. BO1 = BO_LE;
  601. else if (BO1 == BO_LT)
  602. BO1 = BO_GT;
  603. else if (BO1 == BO_LE)
  604. BO1 = BO_GE;
  605. Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts());
  606. Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens());
  607. }
  608. if (!Decl1 || !Literal1)
  609. return TryResult();
  610. BinaryOperatorKind BO2 = RHS->getOpcode();
  611. const DeclRefExpr *Decl2 =
  612. dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts());
  613. const IntegerLiteral *Literal2 =
  614. dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens());
  615. if (!Decl2 && !Literal2) {
  616. if (BO2 == BO_GT)
  617. BO2 = BO_LT;
  618. else if (BO2 == BO_GE)
  619. BO2 = BO_LE;
  620. else if (BO2 == BO_LT)
  621. BO2 = BO_GT;
  622. else if (BO2 == BO_LE)
  623. BO2 = BO_GE;
  624. Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts());
  625. Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens());
  626. }
  627. if (!Decl2 || !Literal2)
  628. return TryResult();
  629. // Check that it is the same variable on both sides.
  630. if (Decl1->getDecl() != Decl2->getDecl())
  631. return TryResult();
  632. llvm::APSInt L1, L2;
  633. if (!Literal1->EvaluateAsInt(L1, *Context) ||
  634. !Literal2->EvaluateAsInt(L2, *Context))
  635. return TryResult();
  636. // Can't compare signed with unsigned or with different bit width.
  637. if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
  638. return TryResult();
  639. // Values that will be used to determine if result of logical
  640. // operator is always true/false
  641. const llvm::APSInt Values[] = {
  642. // Value less than both Value1 and Value2
  643. llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
  644. // L1
  645. L1,
  646. // Value between Value1 and Value2
  647. ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
  648. L1.isUnsigned()),
  649. // L2
  650. L2,
  651. // Value greater than both Value1 and Value2
  652. llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
  653. };
  654. // Check whether expression is always true/false by evaluating the following
  655. // * variable x is less than the smallest literal.
  656. // * variable x is equal to the smallest literal.
  657. // * Variable x is between smallest and largest literal.
  658. // * Variable x is equal to the largest literal.
  659. // * Variable x is greater than largest literal.
  660. bool AlwaysTrue = true, AlwaysFalse = true;
  661. for (unsigned int ValueIndex = 0;
  662. ValueIndex < sizeof(Values) / sizeof(Values[0]);
  663. ++ValueIndex) {
  664. llvm::APSInt Value = Values[ValueIndex];
  665. TryResult Res1, Res2;
  666. Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
  667. Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
  668. if (!Res1.isKnown() || !Res2.isKnown())
  669. return TryResult();
  670. if (B->getOpcode() == BO_LAnd) {
  671. AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
  672. AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
  673. } else {
  674. AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
  675. AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
  676. }
  677. }
  678. if (AlwaysTrue || AlwaysFalse) {
  679. if (BuildOpts.Observer)
  680. BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
  681. return TryResult(AlwaysTrue);
  682. }
  683. return TryResult();
  684. }
  685. /// Try and evaluate an expression to an integer constant.
  686. bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
  687. if (!BuildOpts.PruneTriviallyFalseEdges)
  688. return false;
  689. return !S->isTypeDependent() &&
  690. !S->isValueDependent() &&
  691. S->EvaluateAsRValue(outResult, *Context);
  692. }
  693. /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
  694. /// if we can evaluate to a known value, otherwise return -1.
  695. TryResult tryEvaluateBool(Expr *S) {
  696. if (!BuildOpts.PruneTriviallyFalseEdges ||
  697. S->isTypeDependent() || S->isValueDependent())
  698. return TryResult();
  699. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
  700. if (Bop->isLogicalOp()) {
  701. // Check the cache first.
  702. CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
  703. if (I != CachedBoolEvals.end())
  704. return I->second; // already in map;
  705. // Retrieve result at first, or the map might be updated.
  706. TryResult Result = evaluateAsBooleanConditionNoCache(S);
  707. CachedBoolEvals[S] = Result; // update or insert
  708. return Result;
  709. }
  710. else {
  711. switch (Bop->getOpcode()) {
  712. default: break;
  713. // For 'x & 0' and 'x * 0', we can determine that
  714. // the value is always false.
  715. case BO_Mul:
  716. case BO_And: {
  717. // If either operand is zero, we know the value
  718. // must be false.
  719. llvm::APSInt IntVal;
  720. if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
  721. if (!IntVal.getBoolValue()) {
  722. return TryResult(false);
  723. }
  724. }
  725. if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
  726. if (!IntVal.getBoolValue()) {
  727. return TryResult(false);
  728. }
  729. }
  730. }
  731. break;
  732. }
  733. }
  734. }
  735. return evaluateAsBooleanConditionNoCache(S);
  736. }
  737. /// \brief Evaluate as boolean \param E without using the cache.
  738. TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
  739. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
  740. if (Bop->isLogicalOp()) {
  741. TryResult LHS = tryEvaluateBool(Bop->getLHS());
  742. if (LHS.isKnown()) {
  743. // We were able to evaluate the LHS, see if we can get away with not
  744. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  745. if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
  746. return LHS.isTrue();
  747. TryResult RHS = tryEvaluateBool(Bop->getRHS());
  748. if (RHS.isKnown()) {
  749. if (Bop->getOpcode() == BO_LOr)
  750. return LHS.isTrue() || RHS.isTrue();
  751. else
  752. return LHS.isTrue() && RHS.isTrue();
  753. }
  754. } else {
  755. TryResult RHS = tryEvaluateBool(Bop->getRHS());
  756. if (RHS.isKnown()) {
  757. // We can't evaluate the LHS; however, sometimes the result
  758. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  759. if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
  760. return RHS.isTrue();
  761. } else {
  762. TryResult BopRes = checkIncorrectLogicOperator(Bop);
  763. if (BopRes.isKnown())
  764. return BopRes.isTrue();
  765. }
  766. }
  767. return TryResult();
  768. } else if (Bop->isEqualityOp()) {
  769. TryResult BopRes = checkIncorrectEqualityOperator(Bop);
  770. if (BopRes.isKnown())
  771. return BopRes.isTrue();
  772. } else if (Bop->isRelationalOp()) {
  773. TryResult BopRes = checkIncorrectRelationalOperator(Bop);
  774. if (BopRes.isKnown())
  775. return BopRes.isTrue();
  776. }
  777. }
  778. bool Result;
  779. if (E->EvaluateAsBooleanCondition(Result, *Context))
  780. return Result;
  781. return TryResult();
  782. }
  783. };
  784. inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
  785. const Stmt *stmt) const {
  786. return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
  787. }
  788. bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
  789. bool shouldAdd = BuildOpts.alwaysAdd(stmt);
  790. if (!BuildOpts.forcedBlkExprs)
  791. return shouldAdd;
  792. if (lastLookup == stmt) {
  793. if (cachedEntry) {
  794. assert(cachedEntry->first == stmt);
  795. return true;
  796. }
  797. return shouldAdd;
  798. }
  799. lastLookup = stmt;
  800. // Perform the lookup!
  801. CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
  802. if (!fb) {
  803. // No need to update 'cachedEntry', since it will always be null.
  804. assert(!cachedEntry);
  805. return shouldAdd;
  806. }
  807. CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
  808. if (itr == fb->end()) {
  809. cachedEntry = nullptr;
  810. return shouldAdd;
  811. }
  812. cachedEntry = &*itr;
  813. return true;
  814. }
  815. // FIXME: Add support for dependent-sized array types in C++?
  816. // Does it even make sense to build a CFG for an uninstantiated template?
  817. static const VariableArrayType *FindVA(const Type *t) {
  818. while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
  819. if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
  820. if (vat->getSizeExpr())
  821. return vat;
  822. t = vt->getElementType().getTypePtr();
  823. }
  824. return nullptr;
  825. }
  826. /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
  827. /// arbitrary statement. Examples include a single expression or a function
  828. /// body (compound statement). The ownership of the returned CFG is
  829. /// transferred to the caller. If CFG construction fails, this method returns
  830. /// NULL.
  831. std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
  832. assert(cfg.get());
  833. if (!Statement)
  834. return nullptr;
  835. // Create an empty block that will serve as the exit block for the CFG. Since
  836. // this is the first block added to the CFG, it will be implicitly registered
  837. // as the exit block.
  838. Succ = createBlock();
  839. assert(Succ == &cfg->getExit());
  840. Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
  841. if (BuildOpts.AddImplicitDtors)
  842. if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
  843. addImplicitDtorsForDestructor(DD);
  844. // Visit the statements and create the CFG.
  845. CFGBlock *B = addStmt(Statement);
  846. if (badCFG)
  847. return nullptr;
  848. // For C++ constructor add initializers to CFG.
  849. if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
  850. for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
  851. E = CD->init_rend(); I != E; ++I) {
  852. B = addInitializer(*I);
  853. if (badCFG)
  854. return nullptr;
  855. }
  856. }
  857. if (B)
  858. Succ = B;
  859. // Backpatch the gotos whose label -> block mappings we didn't know when we
  860. // encountered them.
  861. for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
  862. E = BackpatchBlocks.end(); I != E; ++I ) {
  863. CFGBlock *B = I->block;
  864. const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
  865. LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
  866. // If there is no target for the goto, then we are looking at an
  867. // incomplete AST. Handle this by not registering a successor.
  868. if (LI == LabelMap.end()) continue;
  869. JumpTarget JT = LI->second;
  870. prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
  871. JT.scopePosition);
  872. addSuccessor(B, JT.block);
  873. }
  874. // Add successors to the Indirect Goto Dispatch block (if we have one).
  875. if (CFGBlock *B = cfg->getIndirectGotoBlock())
  876. for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
  877. E = AddressTakenLabels.end(); I != E; ++I ) {
  878. // Lookup the target block.
  879. LabelMapTy::iterator LI = LabelMap.find(*I);
  880. // If there is no target block that contains label, then we are looking
  881. // at an incomplete AST. Handle this by not registering a successor.
  882. if (LI == LabelMap.end()) continue;
  883. addSuccessor(B, LI->second.block);
  884. }
  885. // Create an empty entry block that has no predecessors.
  886. cfg->setEntry(createBlock());
  887. return std::move(cfg);
  888. }
  889. /// createBlock - Used to lazily create blocks that are connected
  890. /// to the current (global) succcessor.
  891. CFGBlock *CFGBuilder::createBlock(bool add_successor) {
  892. CFGBlock *B = cfg->createBlock();
  893. if (add_successor && Succ)
  894. addSuccessor(B, Succ);
  895. return B;
  896. }
  897. /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
  898. /// CFG. It is *not* connected to the current (global) successor, and instead
  899. /// directly tied to the exit block in order to be reachable.
  900. CFGBlock *CFGBuilder::createNoReturnBlock() {
  901. CFGBlock *B = createBlock(false);
  902. B->setHasNoReturnElement();
  903. addSuccessor(B, &cfg->getExit(), Succ);
  904. return B;
  905. }
  906. /// addInitializer - Add C++ base or member initializer element to CFG.
  907. CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
  908. if (!BuildOpts.AddInitializers)
  909. return Block;
  910. bool HasTemporaries = false;
  911. // Destructors of temporaries in initialization expression should be called
  912. // after initialization finishes.
  913. Expr *Init = I->getInit();
  914. if (Init) {
  915. HasTemporaries = isa<ExprWithCleanups>(Init);
  916. if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
  917. // Generate destructors for temporaries in initialization expression.
  918. TempDtorContext Context;
  919. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  920. /*BindToTemporary=*/false, Context);
  921. }
  922. }
  923. autoCreateBlock();
  924. appendInitializer(Block, I);
  925. if (Init) {
  926. if (HasTemporaries) {
  927. // For expression with temporaries go directly to subexpression to omit
  928. // generating destructors for the second time.
  929. return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
  930. }
  931. if (BuildOpts.AddCXXDefaultInitExprInCtors) {
  932. if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
  933. // In general, appending the expression wrapped by a CXXDefaultInitExpr
  934. // may cause the same Expr to appear more than once in the CFG. Doing it
  935. // here is safe because there's only one initializer per field.
  936. autoCreateBlock();
  937. appendStmt(Block, Default);
  938. if (Stmt *Child = Default->getExpr())
  939. if (CFGBlock *R = Visit(Child))
  940. Block = R;
  941. return Block;
  942. }
  943. }
  944. return Visit(Init);
  945. }
  946. return Block;
  947. }
  948. /// \brief Retrieve the type of the temporary object whose lifetime was
  949. /// extended by a local reference with the given initializer.
  950. static QualType getReferenceInitTemporaryType(ASTContext &Context,
  951. const Expr *Init) {
  952. while (true) {
  953. // Skip parentheses.
  954. Init = Init->IgnoreParens();
  955. // Skip through cleanups.
  956. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
  957. Init = EWC->getSubExpr();
  958. continue;
  959. }
  960. // Skip through the temporary-materialization expression.
  961. if (const MaterializeTemporaryExpr *MTE
  962. = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  963. Init = MTE->GetTemporaryExpr();
  964. continue;
  965. }
  966. // Skip derived-to-base and no-op casts.
  967. if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
  968. if ((CE->getCastKind() == CK_DerivedToBase ||
  969. CE->getCastKind() == CK_UncheckedDerivedToBase ||
  970. CE->getCastKind() == CK_NoOp) &&
  971. Init->getType()->isRecordType()) {
  972. Init = CE->getSubExpr();
  973. continue;
  974. }
  975. }
  976. // Skip member accesses into rvalues.
  977. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
  978. if (!ME->isArrow() && ME->getBase()->isRValue()) {
  979. Init = ME->getBase();
  980. continue;
  981. }
  982. }
  983. break;
  984. }
  985. return Init->getType();
  986. }
  987. /// addAutomaticObjDtors - Add to current block automatic objects destructors
  988. /// for objects in range of local scope positions. Use S as trigger statement
  989. /// for destructors.
  990. void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
  991. LocalScope::const_iterator E, Stmt *S) {
  992. if (!BuildOpts.AddImplicitDtors)
  993. return;
  994. if (B == E)
  995. return;
  996. // We need to append the destructors in reverse order, but any one of them
  997. // may be a no-return destructor which changes the CFG. As a result, buffer
  998. // this sequence up and replay them in reverse order when appending onto the
  999. // CFGBlock(s).
  1000. SmallVector<VarDecl*, 10> Decls;
  1001. Decls.reserve(B.distance(E));
  1002. for (LocalScope::const_iterator I = B; I != E; ++I)
  1003. Decls.push_back(*I);
  1004. for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
  1005. E = Decls.rend();
  1006. I != E; ++I) {
  1007. // If this destructor is marked as a no-return destructor, we need to
  1008. // create a new block for the destructor which does not have as a successor
  1009. // anything built thus far: control won't flow out of this block.
  1010. QualType Ty = (*I)->getType();
  1011. if (Ty->isReferenceType()) {
  1012. Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
  1013. }
  1014. Ty = Context->getBaseElementType(Ty);
  1015. if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
  1016. Block = createNoReturnBlock();
  1017. else
  1018. autoCreateBlock();
  1019. appendAutomaticObjDtor(Block, *I, S);
  1020. }
  1021. }
  1022. /// addImplicitDtorsForDestructor - Add implicit destructors generated for
  1023. /// base and member objects in destructor.
  1024. void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
  1025. assert (BuildOpts.AddImplicitDtors
  1026. && "Can be called only when dtors should be added");
  1027. const CXXRecordDecl *RD = DD->getParent();
  1028. // At the end destroy virtual base objects.
  1029. for (const auto &VI : RD->vbases()) {
  1030. const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
  1031. if (!CD->hasTrivialDestructor()) {
  1032. autoCreateBlock();
  1033. appendBaseDtor(Block, &VI);
  1034. }
  1035. }
  1036. // Before virtual bases destroy direct base objects.
  1037. for (const auto &BI : RD->bases()) {
  1038. if (!BI.isVirtual()) {
  1039. const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
  1040. if (!CD->hasTrivialDestructor()) {
  1041. autoCreateBlock();
  1042. appendBaseDtor(Block, &BI);
  1043. }
  1044. }
  1045. }
  1046. // First destroy member objects.
  1047. for (auto *FI : RD->fields()) {
  1048. // Check for constant size array. Set type to array element type.
  1049. QualType QT = FI->getType();
  1050. if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  1051. if (AT->getSize() == 0)
  1052. continue;
  1053. QT = AT->getElementType();
  1054. }
  1055. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  1056. if (!CD->hasTrivialDestructor()) {
  1057. autoCreateBlock();
  1058. appendMemberDtor(Block, FI);
  1059. }
  1060. }
  1061. }
  1062. /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
  1063. /// way return valid LocalScope object.
  1064. LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
  1065. if (!Scope) {
  1066. llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
  1067. Scope = alloc.Allocate<LocalScope>();
  1068. BumpVectorContext ctx(alloc);
  1069. new (Scope) LocalScope(ctx, ScopePos);
  1070. }
  1071. return Scope;
  1072. }
  1073. /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
  1074. /// that should create implicit scope (e.g. if/else substatements).
  1075. void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
  1076. if (!BuildOpts.AddImplicitDtors)
  1077. return;
  1078. LocalScope *Scope = nullptr;
  1079. // For compound statement we will be creating explicit scope.
  1080. if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
  1081. for (auto *BI : CS->body()) {
  1082. Stmt *SI = BI->stripLabelLikeStatements();
  1083. if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
  1084. Scope = addLocalScopeForDeclStmt(DS, Scope);
  1085. }
  1086. return;
  1087. }
  1088. // For any other statement scope will be implicit and as such will be
  1089. // interesting only for DeclStmt.
  1090. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
  1091. addLocalScopeForDeclStmt(DS);
  1092. }
  1093. /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
  1094. /// reuse Scope if not NULL.
  1095. LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
  1096. LocalScope* Scope) {
  1097. if (!BuildOpts.AddImplicitDtors)
  1098. return Scope;
  1099. for (auto *DI : DS->decls())
  1100. if (VarDecl *VD = dyn_cast<VarDecl>(DI))
  1101. Scope = addLocalScopeForVarDecl(VD, Scope);
  1102. return Scope;
  1103. }
  1104. /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
  1105. /// create add scope for automatic objects and temporary objects bound to
  1106. /// const reference. Will reuse Scope if not NULL.
  1107. LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
  1108. LocalScope* Scope) {
  1109. if (!BuildOpts.AddImplicitDtors)
  1110. return Scope;
  1111. // Check if variable is local.
  1112. switch (VD->getStorageClass()) {
  1113. case SC_None:
  1114. case SC_Auto:
  1115. case SC_Register:
  1116. break;
  1117. default: return Scope;
  1118. }
  1119. // Check for const references bound to temporary. Set type to pointee.
  1120. QualType QT = VD->getType();
  1121. if (QT.getTypePtr()->isReferenceType()) {
  1122. // Attempt to determine whether this declaration lifetime-extends a
  1123. // temporary.
  1124. //
  1125. // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
  1126. // temporaries, and a single declaration can extend multiple temporaries.
  1127. // We should look at the storage duration on each nested
  1128. // MaterializeTemporaryExpr instead.
  1129. const Expr *Init = VD->getInit();
  1130. if (!Init)
  1131. return Scope;
  1132. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
  1133. Init = EWC->getSubExpr();
  1134. if (!isa<MaterializeTemporaryExpr>(Init))
  1135. return Scope;
  1136. // Lifetime-extending a temporary.
  1137. QT = getReferenceInitTemporaryType(*Context, Init);
  1138. }
  1139. // Check for constant size array. Set type to array element type.
  1140. while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  1141. if (AT->getSize() == 0)
  1142. return Scope;
  1143. QT = AT->getElementType();
  1144. }
  1145. // Check if type is a C++ class with non-trivial destructor.
  1146. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  1147. if (!CD->hasTrivialDestructor()) {
  1148. // Add the variable to scope
  1149. Scope = createOrReuseLocalScope(Scope);
  1150. Scope->addVar(VD);
  1151. ScopePos = Scope->begin();
  1152. }
  1153. return Scope;
  1154. }
  1155. /// addLocalScopeAndDtors - For given statement add local scope for it and
  1156. /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
  1157. void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
  1158. if (!BuildOpts.AddImplicitDtors)
  1159. return;
  1160. LocalScope::const_iterator scopeBeginPos = ScopePos;
  1161. addLocalScopeForStmt(S);
  1162. addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
  1163. }
  1164. /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
  1165. /// variables with automatic storage duration to CFGBlock's elements vector.
  1166. /// Elements will be prepended to physical beginning of the vector which
  1167. /// happens to be logical end. Use blocks terminator as statement that specifies
  1168. /// destructors call site.
  1169. /// FIXME: This mechanism for adding automatic destructors doesn't handle
  1170. /// no-return destructors properly.
  1171. void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  1172. LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1173. BumpVectorContext &C = cfg->getBumpVectorContext();
  1174. CFGBlock::iterator InsertPos
  1175. = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
  1176. for (LocalScope::const_iterator I = B; I != E; ++I)
  1177. InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
  1178. Blk->getTerminator());
  1179. }
  1180. /// Visit - Walk the subtree of a statement and add extra
  1181. /// blocks for ternary operators, &&, and ||. We also process "," and
  1182. /// DeclStmts (which may contain nested control-flow).
  1183. CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
  1184. if (!S) {
  1185. badCFG = true;
  1186. return nullptr;
  1187. }
  1188. if (Expr *E = dyn_cast<Expr>(S))
  1189. S = E->IgnoreParens();
  1190. switch (S->getStmtClass()) {
  1191. default:
  1192. return VisitStmt(S, asc);
  1193. case Stmt::AddrLabelExprClass:
  1194. return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
  1195. case Stmt::BinaryConditionalOperatorClass:
  1196. return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
  1197. case Stmt::BinaryOperatorClass:
  1198. return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
  1199. case Stmt::BlockExprClass:
  1200. return VisitNoRecurse(cast<Expr>(S), asc);
  1201. case Stmt::BreakStmtClass:
  1202. return VisitBreakStmt(cast<BreakStmt>(S));
  1203. case Stmt::CallExprClass:
  1204. case Stmt::CXXOperatorCallExprClass:
  1205. case Stmt::CXXMemberCallExprClass:
  1206. case Stmt::UserDefinedLiteralClass:
  1207. return VisitCallExpr(cast<CallExpr>(S), asc);
  1208. case Stmt::CaseStmtClass:
  1209. return VisitCaseStmt(cast<CaseStmt>(S));
  1210. case Stmt::ChooseExprClass:
  1211. return VisitChooseExpr(cast<ChooseExpr>(S), asc);
  1212. case Stmt::CompoundStmtClass:
  1213. return VisitCompoundStmt(cast<CompoundStmt>(S));
  1214. case Stmt::ConditionalOperatorClass:
  1215. return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
  1216. case Stmt::ContinueStmtClass:
  1217. return VisitContinueStmt(cast<ContinueStmt>(S));
  1218. case Stmt::CXXCatchStmtClass:
  1219. return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
  1220. case Stmt::ExprWithCleanupsClass:
  1221. return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
  1222. case Stmt::CXXDefaultArgExprClass:
  1223. case Stmt::CXXDefaultInitExprClass:
  1224. // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
  1225. // called function's declaration, not by the caller. If we simply add
  1226. // this expression to the CFG, we could end up with the same Expr
  1227. // appearing multiple times.
  1228. // PR13385 / <rdar://problem/12156507>
  1229. //
  1230. // It's likewise possible for multiple CXXDefaultInitExprs for the same
  1231. // expression to be used in the same function (through aggregate
  1232. // initialization).
  1233. return VisitStmt(S, asc);
  1234. case Stmt::CXXBindTemporaryExprClass:
  1235. return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
  1236. case Stmt::CXXConstructExprClass:
  1237. return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
  1238. case Stmt::CXXNewExprClass:
  1239. return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
  1240. case Stmt::CXXDeleteExprClass:
  1241. return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
  1242. case Stmt::CXXFunctionalCastExprClass:
  1243. return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
  1244. case Stmt::CXXTemporaryObjectExprClass:
  1245. return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
  1246. case Stmt::CXXThrowExprClass:
  1247. return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
  1248. case Stmt::CXXTryStmtClass:
  1249. return VisitCXXTryStmt(cast<CXXTryStmt>(S));
  1250. case Stmt::CXXForRangeStmtClass:
  1251. return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
  1252. case Stmt::DeclStmtClass:
  1253. return VisitDeclStmt(cast<DeclStmt>(S));
  1254. case Stmt::DefaultStmtClass:
  1255. return VisitDefaultStmt(cast<DefaultStmt>(S));
  1256. case Stmt::DoStmtClass:
  1257. return VisitDoStmt(cast<DoStmt>(S));
  1258. case Stmt::ForStmtClass:
  1259. return VisitForStmt(cast<ForStmt>(S));
  1260. case Stmt::GotoStmtClass:
  1261. return VisitGotoStmt(cast<GotoStmt>(S));
  1262. case Stmt::IfStmtClass:
  1263. return VisitIfStmt(cast<IfStmt>(S));
  1264. case Stmt::ImplicitCastExprClass:
  1265. return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
  1266. case Stmt::IndirectGotoStmtClass:
  1267. return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
  1268. case Stmt::LabelStmtClass:
  1269. return VisitLabelStmt(cast<LabelStmt>(S));
  1270. case Stmt::LambdaExprClass:
  1271. return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
  1272. case Stmt::MemberExprClass:
  1273. return VisitMemberExpr(cast<MemberExpr>(S), asc);
  1274. case Stmt::NullStmtClass:
  1275. return Block;
  1276. case Stmt::ObjCAtCatchStmtClass:
  1277. return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
  1278. case Stmt::ObjCAutoreleasePoolStmtClass:
  1279. return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
  1280. case Stmt::ObjCAtSynchronizedStmtClass:
  1281. return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
  1282. case Stmt::ObjCAtThrowStmtClass:
  1283. return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
  1284. case Stmt::ObjCAtTryStmtClass:
  1285. return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
  1286. case Stmt::ObjCForCollectionStmtClass:
  1287. return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
  1288. case Stmt::OpaqueValueExprClass:
  1289. return Block;
  1290. case Stmt::PseudoObjectExprClass:
  1291. return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
  1292. case Stmt::ReturnStmtClass:
  1293. return VisitReturnStmt(cast<ReturnStmt>(S));
  1294. case Stmt::UnaryExprOrTypeTraitExprClass:
  1295. return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1296. asc);
  1297. case Stmt::StmtExprClass:
  1298. return VisitStmtExpr(cast<StmtExpr>(S), asc);
  1299. case Stmt::SwitchStmtClass:
  1300. return VisitSwitchStmt(cast<SwitchStmt>(S));
  1301. case Stmt::UnaryOperatorClass:
  1302. return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
  1303. case Stmt::WhileStmtClass:
  1304. return VisitWhileStmt(cast<WhileStmt>(S));
  1305. }
  1306. }
  1307. CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
  1308. if (asc.alwaysAdd(*this, S)) {
  1309. autoCreateBlock();
  1310. appendStmt(Block, S);
  1311. }
  1312. return VisitChildren(S);
  1313. }
  1314. /// VisitChildren - Visit the children of a Stmt.
  1315. CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
  1316. CFGBlock *B = Block;
  1317. // Visit the children in their reverse order so that they appear in
  1318. // left-to-right (natural) order in the CFG.
  1319. reverse_children RChildren(S);
  1320. for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
  1321. I != E; ++I) {
  1322. if (Stmt *Child = *I)
  1323. if (CFGBlock *R = Visit(Child))
  1324. B = R;
  1325. }
  1326. return B;
  1327. }
  1328. CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
  1329. AddStmtChoice asc) {
  1330. AddressTakenLabels.insert(A->getLabel());
  1331. if (asc.alwaysAdd(*this, A)) {
  1332. autoCreateBlock();
  1333. appendStmt(Block, A);
  1334. }
  1335. return Block;
  1336. }
  1337. CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
  1338. AddStmtChoice asc) {
  1339. if (asc.alwaysAdd(*this, U)) {
  1340. autoCreateBlock();
  1341. appendStmt(Block, U);
  1342. }
  1343. return Visit(U->getSubExpr(), AddStmtChoice());
  1344. }
  1345. CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
  1346. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  1347. appendStmt(ConfluenceBlock, B);
  1348. if (badCFG)
  1349. return nullptr;
  1350. return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
  1351. ConfluenceBlock).first;
  1352. }
  1353. std::pair<CFGBlock*, CFGBlock*>
  1354. CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
  1355. Stmt *Term,
  1356. CFGBlock *TrueBlock,
  1357. CFGBlock *FalseBlock) {
  1358. // Introspect the RHS. If it is a nested logical operation, we recursively
  1359. // build the CFG using this function. Otherwise, resort to default
  1360. // CFG construction behavior.
  1361. Expr *RHS = B->getRHS()->IgnoreParens();
  1362. CFGBlock *RHSBlock, *ExitBlock;
  1363. do {
  1364. if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
  1365. if (B_RHS->isLogicalOp()) {
  1366. std::tie(RHSBlock, ExitBlock) =
  1367. VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
  1368. break;
  1369. }
  1370. // The RHS is not a nested logical operation. Don't push the terminator
  1371. // down further, but instead visit RHS and construct the respective
  1372. // pieces of the CFG, and link up the RHSBlock with the terminator
  1373. // we have been provided.
  1374. ExitBlock = RHSBlock = createBlock(false);
  1375. if (!Term) {
  1376. assert(TrueBlock == FalseBlock);
  1377. addSuccessor(RHSBlock, TrueBlock);
  1378. }
  1379. else {
  1380. RHSBlock->setTerminator(Term);
  1381. TryResult KnownVal = tryEvaluateBool(RHS);
  1382. if (!KnownVal.isKnown())
  1383. KnownVal = tryEvaluateBool(B);
  1384. addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
  1385. addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
  1386. }
  1387. Block = RHSBlock;
  1388. RHSBlock = addStmt(RHS);
  1389. }
  1390. while (false);
  1391. if (badCFG)
  1392. return std::make_pair(nullptr, nullptr);
  1393. // Generate the blocks for evaluating the LHS.
  1394. Expr *LHS = B->getLHS()->IgnoreParens();
  1395. if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
  1396. if (B_LHS->isLogicalOp()) {
  1397. if (B->getOpcode() == BO_LOr)
  1398. FalseBlock = RHSBlock;
  1399. else
  1400. TrueBlock = RHSBlock;
  1401. // For the LHS, treat 'B' as the terminator that we want to sink
  1402. // into the nested branch. The RHS always gets the top-most
  1403. // terminator.
  1404. return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
  1405. }
  1406. // Create the block evaluating the LHS.
  1407. // This contains the '&&' or '||' as the terminator.
  1408. CFGBlock *LHSBlock = createBlock(false);
  1409. LHSBlock->setTerminator(B);
  1410. Block = LHSBlock;
  1411. CFGBlock *EntryLHSBlock = addStmt(LHS);
  1412. if (badCFG)
  1413. return std::make_pair(nullptr, nullptr);
  1414. // See if this is a known constant.
  1415. TryResult KnownVal = tryEvaluateBool(LHS);
  1416. // Now link the LHSBlock with RHSBlock.
  1417. if (B->getOpcode() == BO_LOr) {
  1418. addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
  1419. addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
  1420. } else {
  1421. assert(B->getOpcode() == BO_LAnd);
  1422. addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
  1423. addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
  1424. }
  1425. return std::make_pair(EntryLHSBlock, ExitBlock);
  1426. }
  1427. CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
  1428. AddStmtChoice asc) {
  1429. // && or ||
  1430. if (B->isLogicalOp())
  1431. return VisitLogicalOperator(B);
  1432. if (B->getOpcode() == BO_Comma) { // ,
  1433. autoCreateBlock();
  1434. appendStmt(Block, B);
  1435. addStmt(B->getRHS());
  1436. return addStmt(B->getLHS());
  1437. }
  1438. if (B->isAssignmentOp()) {
  1439. if (asc.alwaysAdd(*this, B)) {
  1440. autoCreateBlock();
  1441. appendStmt(Block, B);
  1442. }
  1443. Visit(B->getLHS());
  1444. return Visit(B->getRHS());
  1445. }
  1446. if (asc.alwaysAdd(*this, B)) {
  1447. autoCreateBlock();
  1448. appendStmt(Block, B);
  1449. }
  1450. CFGBlock *RBlock = Visit(B->getRHS());
  1451. CFGBlock *LBlock = Visit(B->getLHS());
  1452. // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
  1453. // containing a DoStmt, and the LHS doesn't create a new block, then we should
  1454. // return RBlock. Otherwise we'll incorrectly return NULL.
  1455. return (LBlock ? LBlock : RBlock);
  1456. }
  1457. CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
  1458. if (asc.alwaysAdd(*this, E)) {
  1459. autoCreateBlock();
  1460. appendStmt(Block, E);
  1461. }
  1462. return Block;
  1463. }
  1464. CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
  1465. // "break" is a control-flow statement. Thus we stop processing the current
  1466. // block.
  1467. if (badCFG)
  1468. return nullptr;
  1469. // Now create a new block that ends with the break statement.
  1470. Block = createBlock(false);
  1471. Block->setTerminator(B);
  1472. // If there is no target for the break, then we are looking at an incomplete
  1473. // AST. This means that the CFG cannot be constructed.
  1474. if (BreakJumpTarget.block) {
  1475. addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
  1476. addSuccessor(Block, BreakJumpTarget.block);
  1477. } else
  1478. badCFG = true;
  1479. return Block;
  1480. }
  1481. static bool CanThrow(Expr *E, ASTContext &Ctx) {
  1482. QualType Ty = E->getType();
  1483. if (Ty->isFunctionPointerType())
  1484. Ty = Ty->getAs<PointerType>()->getPointeeType();
  1485. else if (Ty->isBlockPointerType())
  1486. Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
  1487. const FunctionType *FT = Ty->getAs<FunctionType>();
  1488. if (FT) {
  1489. if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
  1490. if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
  1491. Proto->isNothrow(Ctx))
  1492. return false;
  1493. }
  1494. return true;
  1495. }
  1496. CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
  1497. // Compute the callee type.
  1498. QualType calleeType = C->getCallee()->getType();
  1499. if (calleeType == Context->BoundMemberTy) {
  1500. QualType boundType = Expr::findBoundMemberType(C->getCallee());
  1501. // We should only get a null bound type if processing a dependent
  1502. // CFG. Recover by assuming nothing.
  1503. if (!boundType.isNull()) calleeType = boundType;
  1504. }
  1505. // If this is a call to a no-return function, this stops the block here.
  1506. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
  1507. bool AddEHEdge = false;
  1508. // Languages without exceptions are assumed to not throw.
  1509. if (Context->getLangOpts().Exceptions) {
  1510. if (BuildOpts.AddEHEdges)
  1511. AddEHEdge = true;
  1512. }
  1513. // If this is a call to a builtin function, it might not actually evaluate
  1514. // its arguments. Don't add them to the CFG if this is the case.
  1515. bool OmitArguments = false;
  1516. if (FunctionDecl *FD = C->getDirectCallee()) {
  1517. if (FD->isNoReturn())
  1518. NoReturn = true;
  1519. if (FD->hasAttr<NoThrowAttr>())
  1520. AddEHEdge = false;
  1521. if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
  1522. OmitArguments = true;
  1523. }
  1524. if (!CanThrow(C->getCallee(), *Context))
  1525. AddEHEdge = false;
  1526. if (OmitArguments) {
  1527. assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
  1528. assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
  1529. autoCreateBlock();
  1530. appendStmt(Block, C);
  1531. return Visit(C->getCallee());
  1532. }
  1533. if (!NoReturn && !AddEHEdge) {
  1534. return VisitStmt(C, asc.withAlwaysAdd(true));
  1535. }
  1536. if (Block) {
  1537. Succ = Block;
  1538. if (badCFG)
  1539. return nullptr;
  1540. }
  1541. if (NoReturn)
  1542. Block = createNoReturnBlock();
  1543. else
  1544. Block = createBlock();
  1545. appendStmt(Block, C);
  1546. if (AddEHEdge) {
  1547. // Add exceptional edges.
  1548. if (TryTerminatedBlock)
  1549. addSuccessor(Block, TryTerminatedBlock);
  1550. else
  1551. addSuccessor(Block, &cfg->getExit());
  1552. }
  1553. return VisitChildren(C);
  1554. }
  1555. CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
  1556. AddStmtChoice asc) {
  1557. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  1558. appendStmt(ConfluenceBlock, C);
  1559. if (badCFG)
  1560. return nullptr;
  1561. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  1562. Succ = ConfluenceBlock;
  1563. Block = nullptr;
  1564. CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
  1565. if (badCFG)
  1566. return nullptr;
  1567. Succ = ConfluenceBlock;
  1568. Block = nullptr;
  1569. CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
  1570. if (badCFG)
  1571. return nullptr;
  1572. Block = createBlock(false);
  1573. // See if this is a known constant.
  1574. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  1575. addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
  1576. addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
  1577. Block->setTerminator(C);
  1578. return addStmt(C->getCond());
  1579. }
  1580. CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
  1581. addLocalScopeAndDtors(C);
  1582. CFGBlock *LastBlock = Block;
  1583. for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
  1584. I != E; ++I ) {
  1585. // If we hit a segment of code just containing ';' (NullStmts), we can
  1586. // get a null block back. In such cases, just use the LastBlock
  1587. if (CFGBlock *newBlock = addStmt(*I))
  1588. LastBlock = newBlock;
  1589. if (badCFG)
  1590. return nullptr;
  1591. }
  1592. return LastBlock;
  1593. }
  1594. CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
  1595. AddStmtChoice asc) {
  1596. const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
  1597. const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
  1598. // Create the confluence block that will "merge" the results of the ternary
  1599. // expression.
  1600. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  1601. appendStmt(ConfluenceBlock, C);
  1602. if (badCFG)
  1603. return nullptr;
  1604. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  1605. // Create a block for the LHS expression if there is an LHS expression. A
  1606. // GCC extension allows LHS to be NULL, causing the condition to be the
  1607. // value that is returned instead.
  1608. // e.g: x ?: y is shorthand for: x ? x : y;
  1609. Succ = ConfluenceBlock;
  1610. Block = nullptr;
  1611. CFGBlock *LHSBlock = nullptr;
  1612. const Expr *trueExpr = C->getTrueExpr();
  1613. if (trueExpr != opaqueValue) {
  1614. LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
  1615. if (badCFG)
  1616. return nullptr;
  1617. Block = nullptr;
  1618. }
  1619. else
  1620. LHSBlock = ConfluenceBlock;
  1621. // Create the block for the RHS expression.
  1622. Succ = ConfluenceBlock;
  1623. CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
  1624. if (badCFG)
  1625. return nullptr;
  1626. // If the condition is a logical '&&' or '||', build a more accurate CFG.
  1627. if (BinaryOperator *Cond =
  1628. dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
  1629. if (Cond->isLogicalOp())
  1630. return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
  1631. // Create the block that will contain the condition.
  1632. Block = createBlock(false);
  1633. // See if this is a known constant.
  1634. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  1635. addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
  1636. addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
  1637. Block->setTerminator(C);
  1638. Expr *condExpr = C->getCond();
  1639. if (opaqueValue) {
  1640. // Run the condition expression if it's not trivially expressed in
  1641. // terms of the opaque value (or if there is no opaque value).
  1642. if (condExpr != opaqueValue)
  1643. addStmt(condExpr);
  1644. // Before that, run the common subexpression if there was one.
  1645. // At least one of this or the above will be run.
  1646. return addStmt(BCO->getCommon());
  1647. }
  1648. return addStmt(condExpr);
  1649. }
  1650. CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
  1651. // Check if the Decl is for an __label__. If so, elide it from the
  1652. // CFG entirely.
  1653. if (isa<LabelDecl>(*DS->decl_begin()))
  1654. return Block;
  1655. // This case also handles static_asserts.
  1656. if (DS->isSingleDecl())
  1657. return VisitDeclSubExpr(DS);
  1658. CFGBlock *B = nullptr;
  1659. // Build an individual DeclStmt for each decl.
  1660. for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
  1661. E = DS->decl_rend();
  1662. I != E; ++I) {
  1663. // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
  1664. unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
  1665. ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
  1666. // Allocate the DeclStmt using the BumpPtrAllocator. It will get
  1667. // automatically freed with the CFG.
  1668. DeclGroupRef DG(*I);
  1669. Decl *D = *I;
  1670. void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
  1671. DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
  1672. cfg->addSyntheticDeclStmt(DSNew, DS);
  1673. // Append the fake DeclStmt to block.
  1674. B = VisitDeclSubExpr(DSNew);
  1675. }
  1676. return B;
  1677. }
  1678. /// VisitDeclSubExpr - Utility method to add block-level expressions for
  1679. /// DeclStmts and initializers in them.
  1680. CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
  1681. assert(DS->isSingleDecl() && "Can handle single declarations only.");
  1682. VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  1683. if (!VD) {
  1684. // Of everything that can be declared in a DeclStmt, only VarDecls impact
  1685. // runtime semantics.
  1686. return Block;
  1687. }
  1688. bool HasTemporaries = false;
  1689. // Guard static initializers under a branch.
  1690. CFGBlock *blockAfterStaticInit = nullptr;
  1691. if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
  1692. // For static variables, we need to create a branch to track
  1693. // whether or not they are initialized.
  1694. if (Block) {
  1695. Succ = Block;
  1696. Block = nullptr;
  1697. if (badCFG)
  1698. return nullptr;
  1699. }
  1700. blockAfterStaticInit = Succ;
  1701. }
  1702. // Destructors of temporaries in initialization expression should be called
  1703. // after initialization finishes.
  1704. Expr *Init = VD->getInit();
  1705. if (Init) {
  1706. HasTemporaries = isa<ExprWithCleanups>(Init);
  1707. if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
  1708. // Generate destructors for temporaries in initialization expression.
  1709. TempDtorContext Context;
  1710. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  1711. /*BindToTemporary=*/false, Context);
  1712. }
  1713. }
  1714. autoCreateBlock();
  1715. appendStmt(Block, DS);
  1716. // Keep track of the last non-null block, as 'Block' can be nulled out
  1717. // if the initializer expression is something like a 'while' in a
  1718. // statement-expression.
  1719. CFGBlock *LastBlock = Block;
  1720. if (Init) {
  1721. if (HasTemporaries) {
  1722. // For expression with temporaries go directly to subexpression to omit
  1723. // generating destructors for the second time.
  1724. ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
  1725. if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
  1726. LastBlock = newBlock;
  1727. }
  1728. else {
  1729. if (CFGBlock *newBlock = Visit(Init))
  1730. LastBlock = newBlock;
  1731. }
  1732. }
  1733. // If the type of VD is a VLA, then we must process its size expressions.
  1734. for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
  1735. VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
  1736. if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
  1737. LastBlock = newBlock;
  1738. }
  1739. // Remove variable from local scope.
  1740. if (ScopePos && VD == *ScopePos)
  1741. ++ScopePos;
  1742. CFGBlock *B = LastBlock;
  1743. if (blockAfterStaticInit) {
  1744. Succ = B;
  1745. Block = createBlock(false);
  1746. Block->setTerminator(DS);
  1747. addSuccessor(Block, blockAfterStaticInit);
  1748. addSuccessor(Block, B);
  1749. B = Block;
  1750. }
  1751. return B;
  1752. }
  1753. CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
  1754. // We may see an if statement in the middle of a basic block, or it may be the
  1755. // first statement we are processing. In either case, we create a new basic
  1756. // block. First, we create the blocks for the then...else statements, and
  1757. // then we create the block containing the if statement. If we were in the
  1758. // middle of a block, we stop processing that block. That block is then the
  1759. // implicit successor for the "then" and "else" clauses.
  1760. // Save local scope position because in case of condition variable ScopePos
  1761. // won't be restored when traversing AST.
  1762. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  1763. // Create local scope for possible condition variable.
  1764. // Store scope position. Add implicit destructor.
  1765. if (VarDecl *VD = I->getConditionVariable()) {
  1766. LocalScope::const_iterator BeginScopePos = ScopePos;
  1767. addLocalScopeForVarDecl(VD);
  1768. addAutomaticObjDtors(ScopePos, BeginScopePos, I);
  1769. }
  1770. // The block we were processing is now finished. Make it the successor
  1771. // block.
  1772. if (Block) {
  1773. Succ = Block;
  1774. if (badCFG)
  1775. return nullptr;
  1776. }
  1777. // Process the false branch.
  1778. CFGBlock *ElseBlock = Succ;
  1779. if (Stmt *Else = I->getElse()) {
  1780. SaveAndRestore<CFGBlock*> sv(Succ);
  1781. // NULL out Block so that the recursive call to Visit will
  1782. // create a new basic block.
  1783. Block = nullptr;
  1784. // If branch is not a compound statement create implicit scope
  1785. // and add destructors.
  1786. if (!isa<CompoundStmt>(Else))
  1787. addLocalScopeAndDtors(Else);
  1788. ElseBlock = addStmt(Else);
  1789. if (!ElseBlock) // Can occur when the Else body has all NullStmts.
  1790. ElseBlock = sv.get();
  1791. else if (Block) {
  1792. if (badCFG)
  1793. return nullptr;
  1794. }
  1795. }
  1796. // Process the true branch.
  1797. CFGBlock *ThenBlock;
  1798. {
  1799. Stmt *Then = I->getThen();
  1800. assert(Then);
  1801. SaveAndRestore<CFGBlock*> sv(Succ);
  1802. Block = nullptr;
  1803. // If branch is not a compound statement create implicit scope
  1804. // and add destructors.
  1805. if (!isa<CompoundStmt>(Then))
  1806. addLocalScopeAndDtors(Then);
  1807. ThenBlock = addStmt(Then);
  1808. if (!ThenBlock) {
  1809. // We can reach here if the "then" body has all NullStmts.
  1810. // Create an empty block so we can distinguish between true and false
  1811. // branches in path-sensitive analyses.
  1812. ThenBlock = createBlock(false);
  1813. addSuccessor(ThenBlock, sv.get());
  1814. } else if (Block) {
  1815. if (badCFG)
  1816. return nullptr;
  1817. }
  1818. }
  1819. // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
  1820. // having these handle the actual control-flow jump. Note that
  1821. // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
  1822. // we resort to the old control-flow behavior. This special handling
  1823. // removes infeasible paths from the control-flow graph by having the
  1824. // control-flow transfer of '&&' or '||' go directly into the then/else
  1825. // blocks directly.
  1826. if (!I->getConditionVariable())
  1827. if (BinaryOperator *Cond =
  1828. dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
  1829. if (Cond->isLogicalOp())
  1830. return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
  1831. // Now create a new block containing the if statement.
  1832. Block = createBlock(false);
  1833. // Set the terminator of the new block to the If statement.
  1834. Block->setTerminator(I);
  1835. // See if this is a known constant.
  1836. const TryResult &KnownVal = tryEvaluateBool(I->getCond());
  1837. // Add the successors. If we know that specific branches are
  1838. // unreachable, inform addSuccessor() of that knowledge.
  1839. addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
  1840. addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
  1841. // Add the condition as the last statement in the new block. This may create
  1842. // new blocks as the condition may contain control-flow. Any newly created
  1843. // blocks will be pointed to be "Block".
  1844. CFGBlock *LastBlock = addStmt(I->getCond());
  1845. // Finally, if the IfStmt contains a condition variable, add it and its
  1846. // initializer to the CFG.
  1847. if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
  1848. autoCreateBlock();
  1849. LastBlock = addStmt(const_cast<DeclStmt *>(DS));
  1850. }
  1851. return LastBlock;
  1852. }
  1853. CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
  1854. // If we were in the middle of a block we stop processing that block.
  1855. //
  1856. // NOTE: If a "return" appears in the middle of a block, this means that the
  1857. // code afterwards is DEAD (unreachable). We still keep a basic block
  1858. // for that code; a simple "mark-and-sweep" from the entry block will be
  1859. // able to report such dead blocks.
  1860. // Create the new block.
  1861. Block = createBlock(false);
  1862. addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
  1863. // If the one of the destructors does not return, we already have the Exit
  1864. // block as a successor.
  1865. if (!Block->hasNoReturnElement())
  1866. addSuccessor(Block, &cfg->getExit());
  1867. // Add the return statement to the block. This may create new blocks if R
  1868. // contains control-flow (short-circuit operations).
  1869. return VisitStmt(R, AddStmtChoice::AlwaysAdd);
  1870. }
  1871. CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
  1872. // Get the block of the labeled statement. Add it to our map.
  1873. addStmt(L->getSubStmt());
  1874. CFGBlock *LabelBlock = Block;
  1875. if (!LabelBlock) // This can happen when the body is empty, i.e.
  1876. LabelBlock = createBlock(); // scopes that only contains NullStmts.
  1877. assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
  1878. "label already in map");
  1879. LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
  1880. // Labels partition blocks, so this is the end of the basic block we were
  1881. // processing (L is the block's label). Because this is label (and we have
  1882. // already processed the substatement) there is no extra control-flow to worry
  1883. // about.
  1884. LabelBlock->setLabel(L);
  1885. if (badCFG)
  1886. return nullptr;
  1887. // We set Block to NULL to allow lazy creation of a new block (if necessary);
  1888. Block = nullptr;
  1889. // This block is now the implicit successor of other blocks.
  1890. Succ = LabelBlock;
  1891. return LabelBlock;
  1892. }
  1893. CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
  1894. CFGBlock *LastBlock = VisitNoRecurse(E, asc);
  1895. for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
  1896. et = E->capture_init_end(); it != et; ++it) {
  1897. if (Expr *Init = *it) {
  1898. CFGBlock *Tmp = Visit(Init);
  1899. if (Tmp)
  1900. LastBlock = Tmp;
  1901. }
  1902. }
  1903. return LastBlock;
  1904. }
  1905. CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
  1906. // Goto is a control-flow statement. Thus we stop processing the current
  1907. // block and create a new one.
  1908. Block = createBlock(false);
  1909. Block->setTerminator(G);
  1910. // If we already know the mapping to the label block add the successor now.
  1911. LabelMapTy::iterator I = LabelMap.find(G->getLabel());
  1912. if (I == LabelMap.end())
  1913. // We will need to backpatch this block later.
  1914. BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
  1915. else {
  1916. JumpTarget JT = I->second;
  1917. addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
  1918. addSuccessor(Block, JT.block);
  1919. }
  1920. return Block;
  1921. }
  1922. CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
  1923. CFGBlock *LoopSuccessor = nullptr;
  1924. // Save local scope position because in case of condition variable ScopePos
  1925. // won't be restored when traversing AST.
  1926. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  1927. // Create local scope for init statement and possible condition variable.
  1928. // Add destructor for init statement and condition variable.
  1929. // Store scope position for continue statement.
  1930. if (Stmt *Init = F->getInit())
  1931. addLocalScopeForStmt(Init);
  1932. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  1933. if (VarDecl *VD = F->getConditionVariable())
  1934. addLocalScopeForVarDecl(VD);
  1935. LocalScope::const_iterator ContinueScopePos = ScopePos;
  1936. addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
  1937. // "for" is a control-flow statement. Thus we stop processing the current
  1938. // block.
  1939. if (Block) {
  1940. if (badCFG)
  1941. return nullptr;
  1942. LoopSuccessor = Block;
  1943. } else
  1944. LoopSuccessor = Succ;
  1945. // Save the current value for the break targets.
  1946. // All breaks should go to the code following the loop.
  1947. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  1948. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  1949. CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
  1950. // Now create the loop body.
  1951. {
  1952. assert(F->getBody());
  1953. // Save the current values for Block, Succ, continue and break targets.
  1954. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  1955. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
  1956. // Create an empty block to represent the transition block for looping back
  1957. // to the head of the loop. If we have increment code, it will
  1958. // go in this block as well.
  1959. Block = Succ = TransitionBlock = createBlock(false);
  1960. TransitionBlock->setLoopTarget(F);
  1961. if (Stmt *I = F->getInc()) {
  1962. // Generate increment code in its own basic block. This is the target of
  1963. // continue statements.
  1964. Succ = addStmt(I);
  1965. }
  1966. // Finish up the increment (or empty) block if it hasn't been already.
  1967. if (Block) {
  1968. assert(Block == Succ);
  1969. if (badCFG)
  1970. return nullptr;
  1971. Block = nullptr;
  1972. }
  1973. // The starting block for the loop increment is the block that should
  1974. // represent the 'loop target' for looping back to the start of the loop.
  1975. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  1976. ContinueJumpTarget.block->setLoopTarget(F);
  1977. // Loop body should end with destructor of Condition variable (if any).
  1978. addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
  1979. // If body is not a compound statement create implicit scope
  1980. // and add destructors.
  1981. if (!isa<CompoundStmt>(F->getBody()))
  1982. addLocalScopeAndDtors(F->getBody());
  1983. // Now populate the body block, and in the process create new blocks as we
  1984. // walk the body of the loop.
  1985. BodyBlock = addStmt(F->getBody());
  1986. if (!BodyBlock) {
  1987. // In the case of "for (...;...;...);" we can have a null BodyBlock.
  1988. // Use the continue jump target as the proxy for the body.
  1989. BodyBlock = ContinueJumpTarget.block;
  1990. }
  1991. else if (badCFG)
  1992. return nullptr;
  1993. }
  1994. // Because of short-circuit evaluation, the condition of the loop can span
  1995. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  1996. // evaluate the condition.
  1997. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
  1998. do {
  1999. Expr *C = F->getCond();
  2000. // Specially handle logical operators, which have a slightly
  2001. // more optimal CFG representation.
  2002. if (BinaryOperator *Cond =
  2003. dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
  2004. if (Cond->isLogicalOp()) {
  2005. std::tie(EntryConditionBlock, ExitConditionBlock) =
  2006. VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
  2007. break;
  2008. }
  2009. // The default case when not handling logical operators.
  2010. EntryConditionBlock = ExitConditionBlock = createBlock(false);
  2011. ExitConditionBlock->setTerminator(F);
  2012. // See if this is a known constant.
  2013. TryResult KnownVal(true);
  2014. if (C) {
  2015. // Now add the actual condition to the condition block.
  2016. // Because the condition itself may contain control-flow, new blocks may
  2017. // be created. Thus we update "Succ" after adding the condition.
  2018. Block = ExitConditionBlock;
  2019. EntryConditionBlock = addStmt(C);
  2020. // If this block contains a condition variable, add both the condition
  2021. // variable and initializer to the CFG.
  2022. if (VarDecl *VD = F->getConditionVariable()) {
  2023. if (Expr *Init = VD->getInit()) {
  2024. autoCreateBlock();
  2025. appendStmt(Block, F->getConditionVariableDeclStmt());
  2026. EntryConditionBlock = addStmt(Init);
  2027. assert(Block == EntryConditionBlock);
  2028. }
  2029. }
  2030. if (Block && badCFG)
  2031. return nullptr;
  2032. KnownVal = tryEvaluateBool(C);
  2033. }
  2034. // Add the loop body entry as a successor to the condition.
  2035. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
  2036. // Link up the condition block with the code that follows the loop. (the
  2037. // false branch).
  2038. addSuccessor(ExitConditionBlock,
  2039. KnownVal.isTrue() ? nullptr : LoopSuccessor);
  2040. } while (false);
  2041. // Link up the loop-back block to the entry condition block.
  2042. addSuccessor(TransitionBlock, EntryConditionBlock);
  2043. // The condition block is the implicit successor for any code above the loop.
  2044. Succ = EntryConditionBlock;
  2045. // If the loop contains initialization, create a new block for those
  2046. // statements. This block can also contain statements that precede the loop.
  2047. if (Stmt *I = F->getInit()) {
  2048. Block = createBlock();
  2049. return addStmt(I);
  2050. }
  2051. // There is no loop initialization. We are thus basically a while loop.
  2052. // NULL out Block to force lazy block construction.
  2053. Block = nullptr;
  2054. Succ = EntryConditionBlock;
  2055. return EntryConditionBlock;
  2056. }
  2057. CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
  2058. if (asc.alwaysAdd(*this, M)) {
  2059. autoCreateBlock();
  2060. appendStmt(Block, M);
  2061. }
  2062. return Visit(M->getBase());
  2063. }
  2064. CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
  2065. // Objective-C fast enumeration 'for' statements:
  2066. // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
  2067. //
  2068. // for ( Type newVariable in collection_expression ) { statements }
  2069. //
  2070. // becomes:
  2071. //
  2072. // prologue:
  2073. // 1. collection_expression
  2074. // T. jump to loop_entry
  2075. // loop_entry:
  2076. // 1. side-effects of element expression
  2077. // 1. ObjCForCollectionStmt [performs binding to newVariable]
  2078. // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
  2079. // TB:
  2080. // statements
  2081. // T. jump to loop_entry
  2082. // FB:
  2083. // what comes after
  2084. //
  2085. // and
  2086. //
  2087. // Type existingItem;
  2088. // for ( existingItem in expression ) { statements }
  2089. //
  2090. // becomes:
  2091. //
  2092. // the same with newVariable replaced with existingItem; the binding works
  2093. // the same except that for one ObjCForCollectionStmt::getElement() returns
  2094. // a DeclStmt and the other returns a DeclRefExpr.
  2095. //
  2096. CFGBlock *LoopSuccessor = nullptr;
  2097. if (Block) {
  2098. if (badCFG)
  2099. return nullptr;
  2100. LoopSuccessor = Block;
  2101. Block = nullptr;
  2102. } else
  2103. LoopSuccessor = Succ;
  2104. // Build the condition blocks.
  2105. CFGBlock *ExitConditionBlock = createBlock(false);
  2106. // Set the terminator for the "exit" condition block.
  2107. ExitConditionBlock->setTerminator(S);
  2108. // The last statement in the block should be the ObjCForCollectionStmt, which
  2109. // performs the actual binding to 'element' and determines if there are any
  2110. // more items in the collection.
  2111. appendStmt(ExitConditionBlock, S);
  2112. Block = ExitConditionBlock;
  2113. // Walk the 'element' expression to see if there are any side-effects. We
  2114. // generate new blocks as necessary. We DON'T add the statement by default to
  2115. // the CFG unless it contains control-flow.
  2116. CFGBlock *EntryConditionBlock = Visit(S->getElement(),
  2117. AddStmtChoice::NotAlwaysAdd);
  2118. if (Block) {
  2119. if (badCFG)
  2120. return nullptr;
  2121. Block = nullptr;
  2122. }
  2123. // The condition block is the implicit successor for the loop body as well as
  2124. // any code above the loop.
  2125. Succ = EntryConditionBlock;
  2126. // Now create the true branch.
  2127. {
  2128. // Save the current values for Succ, continue and break targets.
  2129. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2130. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  2131. save_break(BreakJumpTarget);
  2132. // Add an intermediate block between the BodyBlock and the
  2133. // EntryConditionBlock to represent the "loop back" transition, for looping
  2134. // back to the head of the loop.
  2135. CFGBlock *LoopBackBlock = nullptr;
  2136. Succ = LoopBackBlock = createBlock();
  2137. LoopBackBlock->setLoopTarget(S);
  2138. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2139. ContinueJumpTarget = JumpTarget(Succ, ScopePos);
  2140. CFGBlock *BodyBlock = addStmt(S->getBody());
  2141. if (!BodyBlock)
  2142. BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
  2143. else if (Block) {
  2144. if (badCFG)
  2145. return nullptr;
  2146. }
  2147. // This new body block is a successor to our "exit" condition block.
  2148. addSuccessor(ExitConditionBlock, BodyBlock);
  2149. }
  2150. // Link up the condition block with the code that follows the loop.
  2151. // (the false branch).
  2152. addSuccessor(ExitConditionBlock, LoopSuccessor);
  2153. // Now create a prologue block to contain the collection expression.
  2154. Block = createBlock();
  2155. return addStmt(S->getCollection());
  2156. }
  2157. CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
  2158. // Inline the body.
  2159. return addStmt(S->getSubStmt());
  2160. // TODO: consider adding cleanups for the end of @autoreleasepool scope.
  2161. }
  2162. CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  2163. // FIXME: Add locking 'primitives' to CFG for @synchronized.
  2164. // Inline the body.
  2165. CFGBlock *SyncBlock = addStmt(S->getSynchBody());
  2166. // The sync body starts its own basic block. This makes it a little easier
  2167. // for diagnostic clients.
  2168. if (SyncBlock) {
  2169. if (badCFG)
  2170. return nullptr;
  2171. Block = nullptr;
  2172. Succ = SyncBlock;
  2173. }
  2174. // Add the @synchronized to the CFG.
  2175. autoCreateBlock();
  2176. appendStmt(Block, S);
  2177. // Inline the sync expression.
  2178. return addStmt(S->getSynchExpr());
  2179. }
  2180. CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
  2181. // FIXME
  2182. return NYS();
  2183. }
  2184. CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  2185. autoCreateBlock();
  2186. // Add the PseudoObject as the last thing.
  2187. appendStmt(Block, E);
  2188. CFGBlock *lastBlock = Block;
  2189. // Before that, evaluate all of the semantics in order. In
  2190. // CFG-land, that means appending them in reverse order.
  2191. for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
  2192. Expr *Semantic = E->getSemanticExpr(--i);
  2193. // If the semantic is an opaque value, we're being asked to bind
  2194. // it to its source expression.
  2195. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  2196. Semantic = OVE->getSourceExpr();
  2197. if (CFGBlock *B = Visit(Semantic))
  2198. lastBlock = B;
  2199. }
  2200. return lastBlock;
  2201. }
  2202. CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
  2203. CFGBlock *LoopSuccessor = nullptr;
  2204. // Save local scope position because in case of condition variable ScopePos
  2205. // won't be restored when traversing AST.
  2206. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2207. // Create local scope for possible condition variable.
  2208. // Store scope position for continue statement.
  2209. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  2210. if (VarDecl *VD = W->getConditionVariable()) {
  2211. addLocalScopeForVarDecl(VD);
  2212. addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
  2213. }
  2214. // "while" is a control-flow statement. Thus we stop processing the current
  2215. // block.
  2216. if (Block) {
  2217. if (badCFG)
  2218. return nullptr;
  2219. LoopSuccessor = Block;
  2220. Block = nullptr;
  2221. } else {
  2222. LoopSuccessor = Succ;
  2223. }
  2224. CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
  2225. // Process the loop body.
  2226. {
  2227. assert(W->getBody());
  2228. // Save the current values for Block, Succ, continue and break targets.
  2229. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2230. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  2231. save_break(BreakJumpTarget);
  2232. // Create an empty block to represent the transition block for looping back
  2233. // to the head of the loop.
  2234. Succ = TransitionBlock = createBlock(false);
  2235. TransitionBlock->setLoopTarget(W);
  2236. ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
  2237. // All breaks should go to the code following the loop.
  2238. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2239. // Loop body should end with destructor of Condition variable (if any).
  2240. addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
  2241. // If body is not a compound statement create implicit scope
  2242. // and add destructors.
  2243. if (!isa<CompoundStmt>(W->getBody()))
  2244. addLocalScopeAndDtors(W->getBody());
  2245. // Create the body. The returned block is the entry to the loop body.
  2246. BodyBlock = addStmt(W->getBody());
  2247. if (!BodyBlock)
  2248. BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
  2249. else if (Block && badCFG)
  2250. return nullptr;
  2251. }
  2252. // Because of short-circuit evaluation, the condition of the loop can span
  2253. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  2254. // evaluate the condition.
  2255. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
  2256. do {
  2257. Expr *C = W->getCond();
  2258. // Specially handle logical operators, which have a slightly
  2259. // more optimal CFG representation.
  2260. if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
  2261. if (Cond->isLogicalOp()) {
  2262. std::tie(EntryConditionBlock, ExitConditionBlock) =
  2263. VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
  2264. break;
  2265. }
  2266. // The default case when not handling logical operators.
  2267. ExitConditionBlock = createBlock(false);
  2268. ExitConditionBlock->setTerminator(W);
  2269. // Now add the actual condition to the condition block.
  2270. // Because the condition itself may contain control-flow, new blocks may
  2271. // be created. Thus we update "Succ" after adding the condition.
  2272. Block = ExitConditionBlock;
  2273. Block = EntryConditionBlock = addStmt(C);
  2274. // If this block contains a condition variable, add both the condition
  2275. // variable and initializer to the CFG.
  2276. if (VarDecl *VD = W->getConditionVariable()) {
  2277. if (Expr *Init = VD->getInit()) {
  2278. autoCreateBlock();
  2279. appendStmt(Block, W->getConditionVariableDeclStmt());
  2280. EntryConditionBlock = addStmt(Init);
  2281. assert(Block == EntryConditionBlock);
  2282. }
  2283. }
  2284. if (Block && badCFG)
  2285. return nullptr;
  2286. // See if this is a known constant.
  2287. const TryResult& KnownVal = tryEvaluateBool(C);
  2288. // Add the loop body entry as a successor to the condition.
  2289. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
  2290. // Link up the condition block with the code that follows the loop. (the
  2291. // false branch).
  2292. addSuccessor(ExitConditionBlock,
  2293. KnownVal.isTrue() ? nullptr : LoopSuccessor);
  2294. } while(false);
  2295. // Link up the loop-back block to the entry condition block.
  2296. addSuccessor(TransitionBlock, EntryConditionBlock);
  2297. // There can be no more statements in the condition block since we loop back
  2298. // to this block. NULL out Block to force lazy creation of another block.
  2299. Block = nullptr;
  2300. // Return the condition block, which is the dominating block for the loop.
  2301. Succ = EntryConditionBlock;
  2302. return EntryConditionBlock;
  2303. }
  2304. CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
  2305. // FIXME: For now we pretend that @catch and the code it contains does not
  2306. // exit.
  2307. return Block;
  2308. }
  2309. CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
  2310. // FIXME: This isn't complete. We basically treat @throw like a return
  2311. // statement.
  2312. // If we were in the middle of a block we stop processing that block.
  2313. if (badCFG)
  2314. return nullptr;
  2315. // Create the new block.
  2316. Block = createBlock(false);
  2317. // The Exit block is the only successor.
  2318. addSuccessor(Block, &cfg->getExit());
  2319. // Add the statement to the block. This may create new blocks if S contains
  2320. // control-flow (short-circuit operations).
  2321. return VisitStmt(S, AddStmtChoice::AlwaysAdd);
  2322. }
  2323. CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
  2324. // If we were in the middle of a block we stop processing that block.
  2325. if (badCFG)
  2326. return nullptr;
  2327. // Create the new block.
  2328. Block = createBlock(false);
  2329. if (TryTerminatedBlock)
  2330. // The current try statement is the only successor.
  2331. addSuccessor(Block, TryTerminatedBlock);
  2332. else
  2333. // otherwise the Exit block is the only successor.
  2334. addSuccessor(Block, &cfg->getExit());
  2335. // Add the statement to the block. This may create new blocks if S contains
  2336. // control-flow (short-circuit operations).
  2337. return VisitStmt(T, AddStmtChoice::AlwaysAdd);
  2338. }
  2339. CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
  2340. CFGBlock *LoopSuccessor = nullptr;
  2341. // "do...while" is a control-flow statement. Thus we stop processing the
  2342. // current block.
  2343. if (Block) {
  2344. if (badCFG)
  2345. return nullptr;
  2346. LoopSuccessor = Block;
  2347. } else
  2348. LoopSuccessor = Succ;
  2349. // Because of short-circuit evaluation, the condition of the loop can span
  2350. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  2351. // evaluate the condition.
  2352. CFGBlock *ExitConditionBlock = createBlock(false);
  2353. CFGBlock *EntryConditionBlock = ExitConditionBlock;
  2354. // Set the terminator for the "exit" condition block.
  2355. ExitConditionBlock->setTerminator(D);
  2356. // Now add the actual condition to the condition block. Because the condition
  2357. // itself may contain control-flow, new blocks may be created.
  2358. if (Stmt *C = D->getCond()) {
  2359. Block = ExitConditionBlock;
  2360. EntryConditionBlock = addStmt(C);
  2361. if (Block) {
  2362. if (badCFG)
  2363. return nullptr;
  2364. }
  2365. }
  2366. // The condition block is the implicit successor for the loop body.
  2367. Succ = EntryConditionBlock;
  2368. // See if this is a known constant.
  2369. const TryResult &KnownVal = tryEvaluateBool(D->getCond());
  2370. // Process the loop body.
  2371. CFGBlock *BodyBlock = nullptr;
  2372. {
  2373. assert(D->getBody());
  2374. // Save the current values for Block, Succ, and continue and break targets
  2375. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2376. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  2377. save_break(BreakJumpTarget);
  2378. // All continues within this loop should go to the condition block
  2379. ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
  2380. // All breaks should go to the code following the loop.
  2381. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2382. // NULL out Block to force lazy instantiation of blocks for the body.
  2383. Block = nullptr;
  2384. // If body is not a compound statement create implicit scope
  2385. // and add destructors.
  2386. if (!isa<CompoundStmt>(D->getBody()))
  2387. addLocalScopeAndDtors(D->getBody());
  2388. // Create the body. The returned block is the entry to the loop body.
  2389. BodyBlock = addStmt(D->getBody());
  2390. if (!BodyBlock)
  2391. BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
  2392. else if (Block) {
  2393. if (badCFG)
  2394. return nullptr;
  2395. }
  2396. if (!KnownVal.isFalse()) {
  2397. // Add an intermediate block between the BodyBlock and the
  2398. // ExitConditionBlock to represent the "loop back" transition. Create an
  2399. // empty block to represent the transition block for looping back to the
  2400. // head of the loop.
  2401. // FIXME: Can we do this more efficiently without adding another block?
  2402. Block = nullptr;
  2403. Succ = BodyBlock;
  2404. CFGBlock *LoopBackBlock = createBlock();
  2405. LoopBackBlock->setLoopTarget(D);
  2406. // Add the loop body entry as a successor to the condition.
  2407. addSuccessor(ExitConditionBlock, LoopBackBlock);
  2408. }
  2409. else
  2410. addSuccessor(ExitConditionBlock, nullptr);
  2411. }
  2412. // Link up the condition block with the code that follows the loop.
  2413. // (the false branch).
  2414. addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
  2415. // There can be no more statements in the body block(s) since we loop back to
  2416. // the body. NULL out Block to force lazy creation of another block.
  2417. Block = nullptr;
  2418. // Return the loop body, which is the dominating block for the loop.
  2419. Succ = BodyBlock;
  2420. return BodyBlock;
  2421. }
  2422. CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
  2423. // "continue" is a control-flow statement. Thus we stop processing the
  2424. // current block.
  2425. if (badCFG)
  2426. return nullptr;
  2427. // Now create a new block that ends with the continue statement.
  2428. Block = createBlock(false);
  2429. Block->setTerminator(C);
  2430. // If there is no target for the continue, then we are looking at an
  2431. // incomplete AST. This means the CFG cannot be constructed.
  2432. if (ContinueJumpTarget.block) {
  2433. addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
  2434. addSuccessor(Block, ContinueJumpTarget.block);
  2435. } else
  2436. badCFG = true;
  2437. return Block;
  2438. }
  2439. CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  2440. AddStmtChoice asc) {
  2441. if (asc.alwaysAdd(*this, E)) {
  2442. autoCreateBlock();
  2443. appendStmt(Block, E);
  2444. }
  2445. // VLA types have expressions that must be evaluated.
  2446. CFGBlock *lastBlock = Block;
  2447. if (E->isArgumentType()) {
  2448. for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
  2449. VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
  2450. lastBlock = addStmt(VA->getSizeExpr());
  2451. }
  2452. return lastBlock;
  2453. }
  2454. /// VisitStmtExpr - Utility method to handle (nested) statement
  2455. /// expressions (a GCC extension).
  2456. CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
  2457. if (asc.alwaysAdd(*this, SE)) {
  2458. autoCreateBlock();
  2459. appendStmt(Block, SE);
  2460. }
  2461. return VisitCompoundStmt(SE->getSubStmt());
  2462. }
  2463. CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
  2464. // "switch" is a control-flow statement. Thus we stop processing the current
  2465. // block.
  2466. CFGBlock *SwitchSuccessor = nullptr;
  2467. // Save local scope position because in case of condition variable ScopePos
  2468. // won't be restored when traversing AST.
  2469. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2470. // Create local scope for possible condition variable.
  2471. // Store scope position. Add implicit destructor.
  2472. if (VarDecl *VD = Terminator->getConditionVariable()) {
  2473. LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
  2474. addLocalScopeForVarDecl(VD);
  2475. addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
  2476. }
  2477. if (Block) {
  2478. if (badCFG)
  2479. return nullptr;
  2480. SwitchSuccessor = Block;
  2481. } else SwitchSuccessor = Succ;
  2482. // Save the current "switch" context.
  2483. SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
  2484. save_default(DefaultCaseBlock);
  2485. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  2486. // Set the "default" case to be the block after the switch statement. If the
  2487. // switch statement contains a "default:", this value will be overwritten with
  2488. // the block for that code.
  2489. DefaultCaseBlock = SwitchSuccessor;
  2490. // Create a new block that will contain the switch statement.
  2491. SwitchTerminatedBlock = createBlock(false);
  2492. // Now process the switch body. The code after the switch is the implicit
  2493. // successor.
  2494. Succ = SwitchSuccessor;
  2495. BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
  2496. // When visiting the body, the case statements should automatically get linked
  2497. // up to the switch. We also don't keep a pointer to the body, since all
  2498. // control-flow from the switch goes to case/default statements.
  2499. assert(Terminator->getBody() && "switch must contain a non-NULL body");
  2500. Block = nullptr;
  2501. // For pruning unreachable case statements, save the current state
  2502. // for tracking the condition value.
  2503. SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
  2504. false);
  2505. // Determine if the switch condition can be explicitly evaluated.
  2506. assert(Terminator->getCond() && "switch condition must be non-NULL");
  2507. Expr::EvalResult result;
  2508. bool b = tryEvaluate(Terminator->getCond(), result);
  2509. SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
  2510. b ? &result : nullptr);
  2511. // If body is not a compound statement create implicit scope
  2512. // and add destructors.
  2513. if (!isa<CompoundStmt>(Terminator->getBody()))
  2514. addLocalScopeAndDtors(Terminator->getBody());
  2515. addStmt(Terminator->getBody());
  2516. if (Block) {
  2517. if (badCFG)
  2518. return nullptr;
  2519. }
  2520. // If we have no "default:" case, the default transition is to the code
  2521. // following the switch body. Moreover, take into account if all the
  2522. // cases of a switch are covered (e.g., switching on an enum value).
  2523. //
  2524. // Note: We add a successor to a switch that is considered covered yet has no
  2525. // case statements if the enumeration has no enumerators.
  2526. bool SwitchAlwaysHasSuccessor = false;
  2527. SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
  2528. SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
  2529. Terminator->getSwitchCaseList();
  2530. addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
  2531. !SwitchAlwaysHasSuccessor);
  2532. // Add the terminator and condition in the switch block.
  2533. SwitchTerminatedBlock->setTerminator(Terminator);
  2534. Block = SwitchTerminatedBlock;
  2535. CFGBlock *LastBlock = addStmt(Terminator->getCond());
  2536. // Finally, if the SwitchStmt contains a condition variable, add both the
  2537. // SwitchStmt and the condition variable initialization to the CFG.
  2538. if (VarDecl *VD = Terminator->getConditionVariable()) {
  2539. if (Expr *Init = VD->getInit()) {
  2540. autoCreateBlock();
  2541. appendStmt(Block, Terminator->getConditionVariableDeclStmt());
  2542. LastBlock = addStmt(Init);
  2543. }
  2544. }
  2545. return LastBlock;
  2546. }
  2547. static bool shouldAddCase(bool &switchExclusivelyCovered,
  2548. const Expr::EvalResult *switchCond,
  2549. const CaseStmt *CS,
  2550. ASTContext &Ctx) {
  2551. if (!switchCond)
  2552. return true;
  2553. bool addCase = false;
  2554. if (!switchExclusivelyCovered) {
  2555. if (switchCond->Val.isInt()) {
  2556. // Evaluate the LHS of the case value.
  2557. const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
  2558. const llvm::APSInt &condInt = switchCond->Val.getInt();
  2559. if (condInt == lhsInt) {
  2560. addCase = true;
  2561. switchExclusivelyCovered = true;
  2562. }
  2563. else if (condInt < lhsInt) {
  2564. if (const Expr *RHS = CS->getRHS()) {
  2565. // Evaluate the RHS of the case value.
  2566. const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
  2567. if (V2 <= condInt) {
  2568. addCase = true;
  2569. switchExclusivelyCovered = true;
  2570. }
  2571. }
  2572. }
  2573. }
  2574. else
  2575. addCase = true;
  2576. }
  2577. return addCase;
  2578. }
  2579. CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
  2580. // CaseStmts are essentially labels, so they are the first statement in a
  2581. // block.
  2582. CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
  2583. if (Stmt *Sub = CS->getSubStmt()) {
  2584. // For deeply nested chains of CaseStmts, instead of doing a recursion
  2585. // (which can blow out the stack), manually unroll and create blocks
  2586. // along the way.
  2587. while (isa<CaseStmt>(Sub)) {
  2588. CFGBlock *currentBlock = createBlock(false);
  2589. currentBlock->setLabel(CS);
  2590. if (TopBlock)
  2591. addSuccessor(LastBlock, currentBlock);
  2592. else
  2593. TopBlock = currentBlock;
  2594. addSuccessor(SwitchTerminatedBlock,
  2595. shouldAddCase(switchExclusivelyCovered, switchCond,
  2596. CS, *Context)
  2597. ? currentBlock : nullptr);
  2598. LastBlock = currentBlock;
  2599. CS = cast<CaseStmt>(Sub);
  2600. Sub = CS->getSubStmt();
  2601. }
  2602. addStmt(Sub);
  2603. }
  2604. CFGBlock *CaseBlock = Block;
  2605. if (!CaseBlock)
  2606. CaseBlock = createBlock();
  2607. // Cases statements partition blocks, so this is the top of the basic block we
  2608. // were processing (the "case XXX:" is the label).
  2609. CaseBlock->setLabel(CS);
  2610. if (badCFG)
  2611. return nullptr;
  2612. // Add this block to the list of successors for the block with the switch
  2613. // statement.
  2614. assert(SwitchTerminatedBlock);
  2615. addSuccessor(SwitchTerminatedBlock, CaseBlock,
  2616. shouldAddCase(switchExclusivelyCovered, switchCond,
  2617. CS, *Context));
  2618. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  2619. Block = nullptr;
  2620. if (TopBlock) {
  2621. addSuccessor(LastBlock, CaseBlock);
  2622. Succ = TopBlock;
  2623. } else {
  2624. // This block is now the implicit successor of other blocks.
  2625. Succ = CaseBlock;
  2626. }
  2627. return Succ;
  2628. }
  2629. CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
  2630. if (Terminator->getSubStmt())
  2631. addStmt(Terminator->getSubStmt());
  2632. DefaultCaseBlock = Block;
  2633. if (!DefaultCaseBlock)
  2634. DefaultCaseBlock = createBlock();
  2635. // Default statements partition blocks, so this is the top of the basic block
  2636. // we were processing (the "default:" is the label).
  2637. DefaultCaseBlock->setLabel(Terminator);
  2638. if (badCFG)
  2639. return nullptr;
  2640. // Unlike case statements, we don't add the default block to the successors
  2641. // for the switch statement immediately. This is done when we finish
  2642. // processing the switch statement. This allows for the default case
  2643. // (including a fall-through to the code after the switch statement) to always
  2644. // be the last successor of a switch-terminated block.
  2645. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  2646. Block = nullptr;
  2647. // This block is now the implicit successor of other blocks.
  2648. Succ = DefaultCaseBlock;
  2649. return DefaultCaseBlock;
  2650. }
  2651. CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
  2652. // "try"/"catch" is a control-flow statement. Thus we stop processing the
  2653. // current block.
  2654. CFGBlock *TrySuccessor = nullptr;
  2655. if (Block) {
  2656. if (badCFG)
  2657. return nullptr;
  2658. TrySuccessor = Block;
  2659. } else TrySuccessor = Succ;
  2660. CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
  2661. // Create a new block that will contain the try statement.
  2662. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  2663. // Add the terminator in the try block.
  2664. NewTryTerminatedBlock->setTerminator(Terminator);
  2665. bool HasCatchAll = false;
  2666. for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
  2667. // The code after the try is the implicit successor.
  2668. Succ = TrySuccessor;
  2669. CXXCatchStmt *CS = Terminator->getHandler(h);
  2670. if (CS->getExceptionDecl() == nullptr) {
  2671. HasCatchAll = true;
  2672. }
  2673. Block = nullptr;
  2674. CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
  2675. if (!CatchBlock)
  2676. return nullptr;
  2677. // Add this block to the list of successors for the block with the try
  2678. // statement.
  2679. addSuccessor(NewTryTerminatedBlock, CatchBlock);
  2680. }
  2681. if (!HasCatchAll) {
  2682. if (PrevTryTerminatedBlock)
  2683. addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
  2684. else
  2685. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  2686. }
  2687. // The code after the try is the implicit successor.
  2688. Succ = TrySuccessor;
  2689. // Save the current "try" context.
  2690. SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
  2691. cfg->addTryDispatchBlock(TryTerminatedBlock);
  2692. assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
  2693. Block = nullptr;
  2694. return addStmt(Terminator->getTryBlock());
  2695. }
  2696. CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
  2697. // CXXCatchStmt are treated like labels, so they are the first statement in a
  2698. // block.
  2699. // Save local scope position because in case of exception variable ScopePos
  2700. // won't be restored when traversing AST.
  2701. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2702. // Create local scope for possible exception variable.
  2703. // Store scope position. Add implicit destructor.
  2704. if (VarDecl *VD = CS->getExceptionDecl()) {
  2705. LocalScope::const_iterator BeginScopePos = ScopePos;
  2706. addLocalScopeForVarDecl(VD);
  2707. addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
  2708. }
  2709. if (CS->getHandlerBlock())
  2710. addStmt(CS->getHandlerBlock());
  2711. CFGBlock *CatchBlock = Block;
  2712. if (!CatchBlock)
  2713. CatchBlock = createBlock();
  2714. // CXXCatchStmt is more than just a label. They have semantic meaning
  2715. // as well, as they implicitly "initialize" the catch variable. Add
  2716. // it to the CFG as a CFGElement so that the control-flow of these
  2717. // semantics gets captured.
  2718. appendStmt(CatchBlock, CS);
  2719. // Also add the CXXCatchStmt as a label, to mirror handling of regular
  2720. // labels.
  2721. CatchBlock->setLabel(CS);
  2722. // Bail out if the CFG is bad.
  2723. if (badCFG)
  2724. return nullptr;
  2725. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  2726. Block = nullptr;
  2727. return CatchBlock;
  2728. }
  2729. CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
  2730. // C++0x for-range statements are specified as [stmt.ranged]:
  2731. //
  2732. // {
  2733. // auto && __range = range-init;
  2734. // for ( auto __begin = begin-expr,
  2735. // __end = end-expr;
  2736. // __begin != __end;
  2737. // ++__begin ) {
  2738. // for-range-declaration = *__begin;
  2739. // statement
  2740. // }
  2741. // }
  2742. // Save local scope position before the addition of the implicit variables.
  2743. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2744. // Create local scopes and destructors for range, begin and end variables.
  2745. if (Stmt *Range = S->getRangeStmt())
  2746. addLocalScopeForStmt(Range);
  2747. if (Stmt *BeginEnd = S->getBeginEndStmt())
  2748. addLocalScopeForStmt(BeginEnd);
  2749. addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
  2750. LocalScope::const_iterator ContinueScopePos = ScopePos;
  2751. // "for" is a control-flow statement. Thus we stop processing the current
  2752. // block.
  2753. CFGBlock *LoopSuccessor = nullptr;
  2754. if (Block) {
  2755. if (badCFG)
  2756. return nullptr;
  2757. LoopSuccessor = Block;
  2758. } else
  2759. LoopSuccessor = Succ;
  2760. // Save the current value for the break targets.
  2761. // All breaks should go to the code following the loop.
  2762. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  2763. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2764. // The block for the __begin != __end expression.
  2765. CFGBlock *ConditionBlock = createBlock(false);
  2766. ConditionBlock->setTerminator(S);
  2767. // Now add the actual condition to the condition block.
  2768. if (Expr *C = S->getCond()) {
  2769. Block = ConditionBlock;
  2770. CFGBlock *BeginConditionBlock = addStmt(C);
  2771. if (badCFG)
  2772. return nullptr;
  2773. assert(BeginConditionBlock == ConditionBlock &&
  2774. "condition block in for-range was unexpectedly complex");
  2775. (void)BeginConditionBlock;
  2776. }
  2777. // The condition block is the implicit successor for the loop body as well as
  2778. // any code above the loop.
  2779. Succ = ConditionBlock;
  2780. // See if this is a known constant.
  2781. TryResult KnownVal(true);
  2782. if (S->getCond())
  2783. KnownVal = tryEvaluateBool(S->getCond());
  2784. // Now create the loop body.
  2785. {
  2786. assert(S->getBody());
  2787. // Save the current values for Block, Succ, and continue targets.
  2788. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2789. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
  2790. // Generate increment code in its own basic block. This is the target of
  2791. // continue statements.
  2792. Block = nullptr;
  2793. Succ = addStmt(S->getInc());
  2794. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  2795. // The starting block for the loop increment is the block that should
  2796. // represent the 'loop target' for looping back to the start of the loop.
  2797. ContinueJumpTarget.block->setLoopTarget(S);
  2798. // Finish up the increment block and prepare to start the loop body.
  2799. assert(Block);
  2800. if (badCFG)
  2801. return nullptr;
  2802. Block = nullptr;
  2803. // Add implicit scope and dtors for loop variable.
  2804. addLocalScopeAndDtors(S->getLoopVarStmt());
  2805. // Populate a new block to contain the loop body and loop variable.
  2806. addStmt(S->getBody());
  2807. if (badCFG)
  2808. return nullptr;
  2809. CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
  2810. if (badCFG)
  2811. return nullptr;
  2812. // This new body block is a successor to our condition block.
  2813. addSuccessor(ConditionBlock,
  2814. KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
  2815. }
  2816. // Link up the condition block with the code that follows the loop (the
  2817. // false branch).
  2818. addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
  2819. // Add the initialization statements.
  2820. Block = createBlock();
  2821. addStmt(S->getBeginEndStmt());
  2822. return addStmt(S->getRangeStmt());
  2823. }
  2824. CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
  2825. AddStmtChoice asc) {
  2826. if (BuildOpts.AddTemporaryDtors) {
  2827. // If adding implicit destructors visit the full expression for adding
  2828. // destructors of temporaries.
  2829. TempDtorContext Context;
  2830. VisitForTemporaryDtors(E->getSubExpr(), false, Context);
  2831. // Full expression has to be added as CFGStmt so it will be sequenced
  2832. // before destructors of it's temporaries.
  2833. asc = asc.withAlwaysAdd(true);
  2834. }
  2835. return Visit(E->getSubExpr(), asc);
  2836. }
  2837. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  2838. AddStmtChoice asc) {
  2839. if (asc.alwaysAdd(*this, E)) {
  2840. autoCreateBlock();
  2841. appendStmt(Block, E);
  2842. // We do not want to propagate the AlwaysAdd property.
  2843. asc = asc.withAlwaysAdd(false);
  2844. }
  2845. return Visit(E->getSubExpr(), asc);
  2846. }
  2847. CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
  2848. AddStmtChoice asc) {
  2849. autoCreateBlock();
  2850. appendStmt(Block, C);
  2851. return VisitChildren(C);
  2852. }
  2853. CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
  2854. AddStmtChoice asc) {
  2855. autoCreateBlock();
  2856. appendStmt(Block, NE);
  2857. if (NE->getInitializer())
  2858. Block = Visit(NE->getInitializer());
  2859. if (BuildOpts.AddCXXNewAllocator)
  2860. appendNewAllocator(Block, NE);
  2861. if (NE->isArray())
  2862. Block = Visit(NE->getArraySize());
  2863. for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
  2864. E = NE->placement_arg_end(); I != E; ++I)
  2865. Block = Visit(*I);
  2866. return Block;
  2867. }
  2868. CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
  2869. AddStmtChoice asc) {
  2870. autoCreateBlock();
  2871. appendStmt(Block, DE);
  2872. QualType DTy = DE->getDestroyedType();
  2873. DTy = DTy.getNonReferenceType();
  2874. CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
  2875. if (RD) {
  2876. if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
  2877. appendDeleteDtor(Block, RD, DE);
  2878. }
  2879. return VisitChildren(DE);
  2880. }
  2881. CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  2882. AddStmtChoice asc) {
  2883. if (asc.alwaysAdd(*this, E)) {
  2884. autoCreateBlock();
  2885. appendStmt(Block, E);
  2886. // We do not want to propagate the AlwaysAdd property.
  2887. asc = asc.withAlwaysAdd(false);
  2888. }
  2889. return Visit(E->getSubExpr(), asc);
  2890. }
  2891. CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  2892. AddStmtChoice asc) {
  2893. autoCreateBlock();
  2894. appendStmt(Block, C);
  2895. return VisitChildren(C);
  2896. }
  2897. CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
  2898. AddStmtChoice asc) {
  2899. if (asc.alwaysAdd(*this, E)) {
  2900. autoCreateBlock();
  2901. appendStmt(Block, E);
  2902. }
  2903. return Visit(E->getSubExpr(), AddStmtChoice());
  2904. }
  2905. CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  2906. // Lazily create the indirect-goto dispatch block if there isn't one already.
  2907. CFGBlock *IBlock = cfg->getIndirectGotoBlock();
  2908. if (!IBlock) {
  2909. IBlock = createBlock(false);
  2910. cfg->setIndirectGotoBlock(IBlock);
  2911. }
  2912. // IndirectGoto is a control-flow statement. Thus we stop processing the
  2913. // current block and create a new one.
  2914. if (badCFG)
  2915. return nullptr;
  2916. Block = createBlock(false);
  2917. Block->setTerminator(I);
  2918. addSuccessor(Block, IBlock);
  2919. return addStmt(I->getTarget());
  2920. }
  2921. CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
  2922. TempDtorContext &Context) {
  2923. assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
  2924. tryAgain:
  2925. if (!E) {
  2926. badCFG = true;
  2927. return nullptr;
  2928. }
  2929. switch (E->getStmtClass()) {
  2930. default:
  2931. return VisitChildrenForTemporaryDtors(E, Context);
  2932. case Stmt::BinaryOperatorClass:
  2933. return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
  2934. Context);
  2935. case Stmt::CXXBindTemporaryExprClass:
  2936. return VisitCXXBindTemporaryExprForTemporaryDtors(
  2937. cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
  2938. case Stmt::BinaryConditionalOperatorClass:
  2939. case Stmt::ConditionalOperatorClass:
  2940. return VisitConditionalOperatorForTemporaryDtors(
  2941. cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
  2942. case Stmt::ImplicitCastExprClass:
  2943. // For implicit cast we want BindToTemporary to be passed further.
  2944. E = cast<CastExpr>(E)->getSubExpr();
  2945. goto tryAgain;
  2946. case Stmt::CXXFunctionalCastExprClass:
  2947. // For functional cast we want BindToTemporary to be passed further.
  2948. E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
  2949. goto tryAgain;
  2950. case Stmt::ParenExprClass:
  2951. E = cast<ParenExpr>(E)->getSubExpr();
  2952. goto tryAgain;
  2953. case Stmt::MaterializeTemporaryExprClass: {
  2954. const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
  2955. BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
  2956. SmallVector<const Expr *, 2> CommaLHSs;
  2957. SmallVector<SubobjectAdjustment, 2> Adjustments;
  2958. // Find the expression whose lifetime needs to be extended.
  2959. E = const_cast<Expr *>(
  2960. cast<MaterializeTemporaryExpr>(E)
  2961. ->GetTemporaryExpr()
  2962. ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
  2963. // Visit the skipped comma operator left-hand sides for other temporaries.
  2964. for (const Expr *CommaLHS : CommaLHSs) {
  2965. VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
  2966. /*BindToTemporary=*/false, Context);
  2967. }
  2968. goto tryAgain;
  2969. }
  2970. case Stmt::BlockExprClass:
  2971. // Don't recurse into blocks; their subexpressions don't get evaluated
  2972. // here.
  2973. return Block;
  2974. case Stmt::LambdaExprClass: {
  2975. // For lambda expressions, only recurse into the capture initializers,
  2976. // and not the body.
  2977. auto *LE = cast<LambdaExpr>(E);
  2978. CFGBlock *B = Block;
  2979. for (Expr *Init : LE->capture_inits()) {
  2980. if (CFGBlock *R = VisitForTemporaryDtors(
  2981. Init, /*BindToTemporary=*/false, Context))
  2982. B = R;
  2983. }
  2984. return B;
  2985. }
  2986. case Stmt::CXXDefaultArgExprClass:
  2987. E = cast<CXXDefaultArgExpr>(E)->getExpr();
  2988. goto tryAgain;
  2989. case Stmt::CXXDefaultInitExprClass:
  2990. E = cast<CXXDefaultInitExpr>(E)->getExpr();
  2991. goto tryAgain;
  2992. }
  2993. }
  2994. CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
  2995. TempDtorContext &Context) {
  2996. if (isa<LambdaExpr>(E)) {
  2997. // Do not visit the children of lambdas; they have their own CFGs.
  2998. return Block;
  2999. }
  3000. // When visiting children for destructors we want to visit them in reverse
  3001. // order that they will appear in the CFG. Because the CFG is built
  3002. // bottom-up, this means we visit them in their natural order, which
  3003. // reverses them in the CFG.
  3004. CFGBlock *B = Block;
  3005. for (Stmt *Child : E->children())
  3006. if (Child)
  3007. if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
  3008. B = R;
  3009. return B;
  3010. }
  3011. CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
  3012. BinaryOperator *E, TempDtorContext &Context) {
  3013. if (E->isLogicalOp()) {
  3014. VisitForTemporaryDtors(E->getLHS(), false, Context);
  3015. TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
  3016. if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
  3017. RHSExecuted.negate();
  3018. // We do not know at CFG-construction time whether the right-hand-side was
  3019. // executed, thus we add a branch node that depends on the temporary
  3020. // constructor call.
  3021. TempDtorContext RHSContext(
  3022. bothKnownTrue(Context.KnownExecuted, RHSExecuted));
  3023. VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
  3024. InsertTempDtorDecisionBlock(RHSContext);
  3025. return Block;
  3026. }
  3027. if (E->isAssignmentOp()) {
  3028. // For assignment operator (=) LHS expression is visited
  3029. // before RHS expression. For destructors visit them in reverse order.
  3030. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
  3031. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  3032. return LHSBlock ? LHSBlock : RHSBlock;
  3033. }
  3034. // For any other binary operator RHS expression is visited before
  3035. // LHS expression (order of children). For destructors visit them in reverse
  3036. // order.
  3037. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  3038. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
  3039. return RHSBlock ? RHSBlock : LHSBlock;
  3040. }
  3041. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
  3042. CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
  3043. // First add destructors for temporaries in subexpression.
  3044. CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
  3045. if (!BindToTemporary) {
  3046. // If lifetime of temporary is not prolonged (by assigning to constant
  3047. // reference) add destructor for it.
  3048. const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
  3049. if (Dtor->getParent()->isAnyDestructorNoReturn()) {
  3050. // If the destructor is marked as a no-return destructor, we need to
  3051. // create a new block for the destructor which does not have as a
  3052. // successor anything built thus far. Control won't flow out of this
  3053. // block.
  3054. if (B) Succ = B;
  3055. Block = createNoReturnBlock();
  3056. } else if (Context.needsTempDtorBranch()) {
  3057. // If we need to introduce a branch, we add a new block that we will hook
  3058. // up to a decision block later.
  3059. if (B) Succ = B;
  3060. Block = createBlock();
  3061. } else {
  3062. autoCreateBlock();
  3063. }
  3064. if (Context.needsTempDtorBranch()) {
  3065. Context.setDecisionPoint(Succ, E);
  3066. }
  3067. appendTemporaryDtor(Block, E);
  3068. B = Block;
  3069. }
  3070. return B;
  3071. }
  3072. void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
  3073. CFGBlock *FalseSucc) {
  3074. if (!Context.TerminatorExpr) {
  3075. // If no temporary was found, we do not need to insert a decision point.
  3076. return;
  3077. }
  3078. assert(Context.TerminatorExpr);
  3079. CFGBlock *Decision = createBlock(false);
  3080. Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
  3081. addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
  3082. addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
  3083. !Context.KnownExecuted.isTrue());
  3084. Block = Decision;
  3085. }
  3086. CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
  3087. AbstractConditionalOperator *E, bool BindToTemporary,
  3088. TempDtorContext &Context) {
  3089. VisitForTemporaryDtors(E->getCond(), false, Context);
  3090. CFGBlock *ConditionBlock = Block;
  3091. CFGBlock *ConditionSucc = Succ;
  3092. TryResult ConditionVal = tryEvaluateBool(E->getCond());
  3093. TryResult NegatedVal = ConditionVal;
  3094. if (NegatedVal.isKnown()) NegatedVal.negate();
  3095. TempDtorContext TrueContext(
  3096. bothKnownTrue(Context.KnownExecuted, ConditionVal));
  3097. VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
  3098. CFGBlock *TrueBlock = Block;
  3099. Block = ConditionBlock;
  3100. Succ = ConditionSucc;
  3101. TempDtorContext FalseContext(
  3102. bothKnownTrue(Context.KnownExecuted, NegatedVal));
  3103. VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
  3104. if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
  3105. InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
  3106. } else if (TrueContext.TerminatorExpr) {
  3107. Block = TrueBlock;
  3108. InsertTempDtorDecisionBlock(TrueContext);
  3109. } else {
  3110. InsertTempDtorDecisionBlock(FalseContext);
  3111. }
  3112. return Block;
  3113. }
  3114. } // end anonymous namespace
  3115. /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
  3116. /// no successors or predecessors. If this is the first block created in the
  3117. /// CFG, it is automatically set to be the Entry and Exit of the CFG.
  3118. CFGBlock *CFG::createBlock() {
  3119. bool first_block = begin() == end();
  3120. // Create the block.
  3121. CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
  3122. new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
  3123. Blocks.push_back(Mem, BlkBVC);
  3124. // If this is the first block, set it as the Entry and Exit.
  3125. if (first_block)
  3126. Entry = Exit = &back();
  3127. // Return the block.
  3128. return &back();
  3129. }
  3130. /// buildCFG - Constructs a CFG from an AST.
  3131. std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
  3132. ASTContext *C, const BuildOptions &BO) {
  3133. CFGBuilder Builder(C, BO);
  3134. return Builder.buildCFG(D, Statement);
  3135. }
  3136. const CXXDestructorDecl *
  3137. CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
  3138. switch (getKind()) {
  3139. case CFGElement::Statement:
  3140. case CFGElement::Initializer:
  3141. case CFGElement::NewAllocator:
  3142. llvm_unreachable("getDestructorDecl should only be used with "
  3143. "ImplicitDtors");
  3144. case CFGElement::AutomaticObjectDtor: {
  3145. const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
  3146. QualType ty = var->getType();
  3147. ty = ty.getNonReferenceType();
  3148. while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
  3149. ty = arrayType->getElementType();
  3150. }
  3151. const RecordType *recordType = ty->getAs<RecordType>();
  3152. const CXXRecordDecl *classDecl =
  3153. cast<CXXRecordDecl>(recordType->getDecl());
  3154. return classDecl->getDestructor();
  3155. }
  3156. case CFGElement::DeleteDtor: {
  3157. const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
  3158. QualType DTy = DE->getDestroyedType();
  3159. DTy = DTy.getNonReferenceType();
  3160. const CXXRecordDecl *classDecl =
  3161. astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
  3162. return classDecl->getDestructor();
  3163. }
  3164. case CFGElement::TemporaryDtor: {
  3165. const CXXBindTemporaryExpr *bindExpr =
  3166. castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
  3167. const CXXTemporary *temp = bindExpr->getTemporary();
  3168. return temp->getDestructor();
  3169. }
  3170. case CFGElement::BaseDtor:
  3171. case CFGElement::MemberDtor:
  3172. // Not yet supported.
  3173. return nullptr;
  3174. }
  3175. llvm_unreachable("getKind() returned bogus value");
  3176. }
  3177. bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
  3178. if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
  3179. return DD->isNoReturn();
  3180. return false;
  3181. }
  3182. //===----------------------------------------------------------------------===//
  3183. // CFGBlock operations.
  3184. //===----------------------------------------------------------------------===//
  3185. CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
  3186. : ReachableBlock(IsReachable ? B : nullptr),
  3187. UnreachableBlock(!IsReachable ? B : nullptr,
  3188. B && IsReachable ? AB_Normal : AB_Unreachable) {}
  3189. CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
  3190. : ReachableBlock(B),
  3191. UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
  3192. B == AlternateBlock ? AB_Alternate : AB_Normal) {}
  3193. void CFGBlock::addSuccessor(AdjacentBlock Succ,
  3194. BumpVectorContext &C) {
  3195. if (CFGBlock *B = Succ.getReachableBlock())
  3196. B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
  3197. if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
  3198. UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
  3199. Succs.push_back(Succ, C);
  3200. }
  3201. bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
  3202. const CFGBlock *From, const CFGBlock *To) {
  3203. if (F.IgnoreNullPredecessors && !From)
  3204. return true;
  3205. if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
  3206. // If the 'To' has no label or is labeled but the label isn't a
  3207. // CaseStmt then filter this edge.
  3208. if (const SwitchStmt *S =
  3209. dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
  3210. if (S->isAllEnumCasesCovered()) {
  3211. const Stmt *L = To->getLabel();
  3212. if (!L || !isa<CaseStmt>(L))
  3213. return true;
  3214. }
  3215. }
  3216. }
  3217. return false;
  3218. }
  3219. //===----------------------------------------------------------------------===//
  3220. // CFG pretty printing
  3221. //===----------------------------------------------------------------------===//
  3222. namespace {
  3223. class StmtPrinterHelper : public PrinterHelper {
  3224. typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
  3225. typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
  3226. StmtMapTy StmtMap;
  3227. DeclMapTy DeclMap;
  3228. signed currentBlock;
  3229. unsigned currStmt;
  3230. const LangOptions &LangOpts;
  3231. public:
  3232. StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
  3233. : currentBlock(0), currStmt(0), LangOpts(LO)
  3234. {
  3235. for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
  3236. unsigned j = 1;
  3237. for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
  3238. BI != BEnd; ++BI, ++j ) {
  3239. if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
  3240. const Stmt *stmt= SE->getStmt();
  3241. std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
  3242. StmtMap[stmt] = P;
  3243. switch (stmt->getStmtClass()) {
  3244. case Stmt::DeclStmtClass:
  3245. DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
  3246. break;
  3247. case Stmt::IfStmtClass: {
  3248. const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
  3249. if (var)
  3250. DeclMap[var] = P;
  3251. break;
  3252. }
  3253. case Stmt::ForStmtClass: {
  3254. const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
  3255. if (var)
  3256. DeclMap[var] = P;
  3257. break;
  3258. }
  3259. case Stmt::WhileStmtClass: {
  3260. const VarDecl *var =
  3261. cast<WhileStmt>(stmt)->getConditionVariable();
  3262. if (var)
  3263. DeclMap[var] = P;
  3264. break;
  3265. }
  3266. case Stmt::SwitchStmtClass: {
  3267. const VarDecl *var =
  3268. cast<SwitchStmt>(stmt)->getConditionVariable();
  3269. if (var)
  3270. DeclMap[var] = P;
  3271. break;
  3272. }
  3273. case Stmt::CXXCatchStmtClass: {
  3274. const VarDecl *var =
  3275. cast<CXXCatchStmt>(stmt)->getExceptionDecl();
  3276. if (var)
  3277. DeclMap[var] = P;
  3278. break;
  3279. }
  3280. default:
  3281. break;
  3282. }
  3283. }
  3284. }
  3285. }
  3286. }
  3287. ~StmtPrinterHelper() override {}
  3288. const LangOptions &getLangOpts() const { return LangOpts; }
  3289. void setBlockID(signed i) { currentBlock = i; }
  3290. void setStmtID(unsigned i) { currStmt = i; }
  3291. bool handledStmt(Stmt *S, raw_ostream &OS) override {
  3292. StmtMapTy::iterator I = StmtMap.find(S);
  3293. if (I == StmtMap.end())
  3294. return false;
  3295. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  3296. && I->second.second == currStmt) {
  3297. return false;
  3298. }
  3299. OS << "[B" << I->second.first << "." << I->second.second << "]";
  3300. return true;
  3301. }
  3302. bool handleDecl(const Decl *D, raw_ostream &OS) {
  3303. DeclMapTy::iterator I = DeclMap.find(D);
  3304. if (I == DeclMap.end())
  3305. return false;
  3306. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  3307. && I->second.second == currStmt) {
  3308. return false;
  3309. }
  3310. OS << "[B" << I->second.first << "." << I->second.second << "]";
  3311. return true;
  3312. }
  3313. };
  3314. } // end anonymous namespace
  3315. namespace {
  3316. class CFGBlockTerminatorPrint
  3317. : public StmtVisitor<CFGBlockTerminatorPrint,void> {
  3318. raw_ostream &OS;
  3319. StmtPrinterHelper* Helper;
  3320. PrintingPolicy Policy;
  3321. public:
  3322. CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
  3323. const PrintingPolicy &Policy)
  3324. : OS(os), Helper(helper), Policy(Policy) {
  3325. this->Policy.IncludeNewlines = false;
  3326. }
  3327. void VisitIfStmt(IfStmt *I) {
  3328. OS << "if ";
  3329. if (Stmt *C = I->getCond())
  3330. C->printPretty(OS, Helper, Policy);
  3331. }
  3332. // Default case.
  3333. void VisitStmt(Stmt *Terminator) {
  3334. Terminator->printPretty(OS, Helper, Policy);
  3335. }
  3336. void VisitDeclStmt(DeclStmt *DS) {
  3337. VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  3338. OS << "static init " << VD->getName();
  3339. }
  3340. void VisitForStmt(ForStmt *F) {
  3341. OS << "for (" ;
  3342. if (F->getInit())
  3343. OS << "...";
  3344. OS << "; ";
  3345. if (Stmt *C = F->getCond())
  3346. C->printPretty(OS, Helper, Policy);
  3347. OS << "; ";
  3348. if (F->getInc())
  3349. OS << "...";
  3350. OS << ")";
  3351. }
  3352. void VisitWhileStmt(WhileStmt *W) {
  3353. OS << "while " ;
  3354. if (Stmt *C = W->getCond())
  3355. C->printPretty(OS, Helper, Policy);
  3356. }
  3357. void VisitDoStmt(DoStmt *D) {
  3358. OS << "do ... while ";
  3359. if (Stmt *C = D->getCond())
  3360. C->printPretty(OS, Helper, Policy);
  3361. }
  3362. void VisitSwitchStmt(SwitchStmt *Terminator) {
  3363. OS << "switch ";
  3364. Terminator->getCond()->printPretty(OS, Helper, Policy);
  3365. }
  3366. void VisitCXXTryStmt(CXXTryStmt *CS) {
  3367. OS << "try ...";
  3368. }
  3369. void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
  3370. if (Stmt *Cond = C->getCond())
  3371. Cond->printPretty(OS, Helper, Policy);
  3372. OS << " ? ... : ...";
  3373. }
  3374. void VisitChooseExpr(ChooseExpr *C) {
  3375. OS << "__builtin_choose_expr( ";
  3376. if (Stmt *Cond = C->getCond())
  3377. Cond->printPretty(OS, Helper, Policy);
  3378. OS << " )";
  3379. }
  3380. void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  3381. OS << "goto *";
  3382. if (Stmt *T = I->getTarget())
  3383. T->printPretty(OS, Helper, Policy);
  3384. }
  3385. void VisitBinaryOperator(BinaryOperator* B) {
  3386. if (!B->isLogicalOp()) {
  3387. VisitExpr(B);
  3388. return;
  3389. }
  3390. if (B->getLHS())
  3391. B->getLHS()->printPretty(OS, Helper, Policy);
  3392. switch (B->getOpcode()) {
  3393. case BO_LOr:
  3394. OS << " || ...";
  3395. return;
  3396. case BO_LAnd:
  3397. OS << " && ...";
  3398. return;
  3399. default:
  3400. llvm_unreachable("Invalid logical operator.");
  3401. }
  3402. }
  3403. void VisitExpr(Expr *E) {
  3404. E->printPretty(OS, Helper, Policy);
  3405. }
  3406. public:
  3407. void print(CFGTerminator T) {
  3408. if (T.isTemporaryDtorsBranch())
  3409. OS << "(Temp Dtor) ";
  3410. Visit(T.getStmt());
  3411. }
  3412. };
  3413. } // end anonymous namespace
  3414. static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
  3415. const CFGElement &E) {
  3416. if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
  3417. const Stmt *S = CS->getStmt();
  3418. assert(S != nullptr && "Expecting non-null Stmt");
  3419. // special printing for statement-expressions.
  3420. if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
  3421. const CompoundStmt *Sub = SE->getSubStmt();
  3422. if (Sub->children()) {
  3423. OS << "({ ... ; ";
  3424. Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
  3425. OS << " })\n";
  3426. return;
  3427. }
  3428. }
  3429. // special printing for comma expressions.
  3430. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
  3431. if (B->getOpcode() == BO_Comma) {
  3432. OS << "... , ";
  3433. Helper.handledStmt(B->getRHS(),OS);
  3434. OS << '\n';
  3435. return;
  3436. }
  3437. }
  3438. S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  3439. if (isa<CXXOperatorCallExpr>(S)) {
  3440. OS << " (OperatorCall)";
  3441. }
  3442. else if (isa<CXXBindTemporaryExpr>(S)) {
  3443. OS << " (BindTemporary)";
  3444. }
  3445. else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
  3446. OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
  3447. }
  3448. else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
  3449. OS << " (" << CE->getStmtClassName() << ", "
  3450. << CE->getCastKindName()
  3451. << ", " << CE->getType().getAsString()
  3452. << ")";
  3453. }
  3454. // Expressions need a newline.
  3455. if (isa<Expr>(S))
  3456. OS << '\n';
  3457. } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
  3458. const CXXCtorInitializer *I = IE->getInitializer();
  3459. if (I->isBaseInitializer())
  3460. OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
  3461. else if (I->isDelegatingInitializer())
  3462. OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
  3463. else OS << I->getAnyMember()->getName();
  3464. OS << "(";
  3465. if (Expr *IE = I->getInit())
  3466. IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  3467. OS << ")";
  3468. if (I->isBaseInitializer())
  3469. OS << " (Base initializer)\n";
  3470. else if (I->isDelegatingInitializer())
  3471. OS << " (Delegating initializer)\n";
  3472. else OS << " (Member initializer)\n";
  3473. } else if (Optional<CFGAutomaticObjDtor> DE =
  3474. E.getAs<CFGAutomaticObjDtor>()) {
  3475. const VarDecl *VD = DE->getVarDecl();
  3476. Helper.handleDecl(VD, OS);
  3477. const Type* T = VD->getType().getTypePtr();
  3478. if (const ReferenceType* RT = T->getAs<ReferenceType>())
  3479. T = RT->getPointeeType().getTypePtr();
  3480. T = T->getBaseElementTypeUnsafe();
  3481. OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
  3482. OS << " (Implicit destructor)\n";
  3483. } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
  3484. OS << "CFGNewAllocator(";
  3485. if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
  3486. AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  3487. OS << ")\n";
  3488. } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
  3489. const CXXRecordDecl *RD = DE->getCXXRecordDecl();
  3490. if (!RD)
  3491. return;
  3492. CXXDeleteExpr *DelExpr =
  3493. const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
  3494. Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
  3495. OS << "->~" << RD->getName().str() << "()";
  3496. OS << " (Implicit destructor)\n";
  3497. } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
  3498. const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
  3499. OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
  3500. OS << " (Base object destructor)\n";
  3501. } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
  3502. const FieldDecl *FD = ME->getFieldDecl();
  3503. const Type *T = FD->getType()->getBaseElementTypeUnsafe();
  3504. OS << "this->" << FD->getName();
  3505. OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
  3506. OS << " (Member object destructor)\n";
  3507. } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
  3508. const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
  3509. OS << "~";
  3510. BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  3511. OS << "() (Temporary object destructor)\n";
  3512. }
  3513. }
  3514. static void print_block(raw_ostream &OS, const CFG* cfg,
  3515. const CFGBlock &B,
  3516. StmtPrinterHelper &Helper, bool print_edges,
  3517. bool ShowColors) {
  3518. Helper.setBlockID(B.getBlockID());
  3519. // Print the header.
  3520. if (ShowColors)
  3521. OS.changeColor(raw_ostream::YELLOW, true);
  3522. OS << "\n [B" << B.getBlockID();
  3523. if (&B == &cfg->getEntry())
  3524. OS << " (ENTRY)]\n";
  3525. else if (&B == &cfg->getExit())
  3526. OS << " (EXIT)]\n";
  3527. else if (&B == cfg->getIndirectGotoBlock())
  3528. OS << " (INDIRECT GOTO DISPATCH)]\n";
  3529. else if (B.hasNoReturnElement())
  3530. OS << " (NORETURN)]\n";
  3531. else
  3532. OS << "]\n";
  3533. if (ShowColors)
  3534. OS.resetColor();
  3535. // Print the label of this block.
  3536. if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
  3537. if (print_edges)
  3538. OS << " ";
  3539. if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
  3540. OS << L->getName();
  3541. else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  3542. OS << "case ";
  3543. if (C->getLHS())
  3544. C->getLHS()->printPretty(OS, &Helper,
  3545. PrintingPolicy(Helper.getLangOpts()));
  3546. if (C->getRHS()) {
  3547. OS << " ... ";
  3548. C->getRHS()->printPretty(OS, &Helper,
  3549. PrintingPolicy(Helper.getLangOpts()));
  3550. }
  3551. } else if (isa<DefaultStmt>(Label))
  3552. OS << "default";
  3553. else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
  3554. OS << "catch (";
  3555. if (CS->getExceptionDecl())
  3556. CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
  3557. 0);
  3558. else
  3559. OS << "...";
  3560. OS << ")";
  3561. } else
  3562. llvm_unreachable("Invalid label statement in CFGBlock.");
  3563. OS << ":\n";
  3564. }
  3565. // Iterate through the statements in the block and print them.
  3566. unsigned j = 1;
  3567. for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
  3568. I != E ; ++I, ++j ) {
  3569. // Print the statement # in the basic block and the statement itself.
  3570. if (print_edges)
  3571. OS << " ";
  3572. OS << llvm::format("%3d", j) << ": ";
  3573. Helper.setStmtID(j);
  3574. print_elem(OS, Helper, *I);
  3575. }
  3576. // Print the terminator of this block.
  3577. if (B.getTerminator()) {
  3578. if (ShowColors)
  3579. OS.changeColor(raw_ostream::GREEN);
  3580. OS << " T: ";
  3581. Helper.setBlockID(-1);
  3582. PrintingPolicy PP(Helper.getLangOpts());
  3583. CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
  3584. TPrinter.print(B.getTerminator());
  3585. OS << '\n';
  3586. if (ShowColors)
  3587. OS.resetColor();
  3588. }
  3589. if (print_edges) {
  3590. // Print the predecessors of this block.
  3591. if (!B.pred_empty()) {
  3592. const raw_ostream::Colors Color = raw_ostream::BLUE;
  3593. if (ShowColors)
  3594. OS.changeColor(Color);
  3595. OS << " Preds " ;
  3596. if (ShowColors)
  3597. OS.resetColor();
  3598. OS << '(' << B.pred_size() << "):";
  3599. unsigned i = 0;
  3600. if (ShowColors)
  3601. OS.changeColor(Color);
  3602. for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
  3603. I != E; ++I, ++i) {
  3604. if (i % 10 == 8)
  3605. OS << "\n ";
  3606. CFGBlock *B = *I;
  3607. bool Reachable = true;
  3608. if (!B) {
  3609. Reachable = false;
  3610. B = I->getPossiblyUnreachableBlock();
  3611. }
  3612. OS << " B" << B->getBlockID();
  3613. if (!Reachable)
  3614. OS << "(Unreachable)";
  3615. }
  3616. if (ShowColors)
  3617. OS.resetColor();
  3618. OS << '\n';
  3619. }
  3620. // Print the successors of this block.
  3621. if (!B.succ_empty()) {
  3622. const raw_ostream::Colors Color = raw_ostream::MAGENTA;
  3623. if (ShowColors)
  3624. OS.changeColor(Color);
  3625. OS << " Succs ";
  3626. if (ShowColors)
  3627. OS.resetColor();
  3628. OS << '(' << B.succ_size() << "):";
  3629. unsigned i = 0;
  3630. if (ShowColors)
  3631. OS.changeColor(Color);
  3632. for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
  3633. I != E; ++I, ++i) {
  3634. if (i % 10 == 8)
  3635. OS << "\n ";
  3636. CFGBlock *B = *I;
  3637. bool Reachable = true;
  3638. if (!B) {
  3639. Reachable = false;
  3640. B = I->getPossiblyUnreachableBlock();
  3641. }
  3642. if (B) {
  3643. OS << " B" << B->getBlockID();
  3644. if (!Reachable)
  3645. OS << "(Unreachable)";
  3646. }
  3647. else {
  3648. OS << " NULL";
  3649. }
  3650. }
  3651. if (ShowColors)
  3652. OS.resetColor();
  3653. OS << '\n';
  3654. }
  3655. }
  3656. }
  3657. /// dump - A simple pretty printer of a CFG that outputs to stderr.
  3658. void CFG::dump(const LangOptions &LO, bool ShowColors) const {
  3659. print(llvm::errs(), LO, ShowColors);
  3660. }
  3661. /// print - A simple pretty printer of a CFG that outputs to an ostream.
  3662. void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
  3663. StmtPrinterHelper Helper(this, LO);
  3664. // Print the entry block.
  3665. print_block(OS, this, getEntry(), Helper, true, ShowColors);
  3666. // Iterate through the CFGBlocks and print them one by one.
  3667. for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
  3668. // Skip the entry block, because we already printed it.
  3669. if (&(**I) == &getEntry() || &(**I) == &getExit())
  3670. continue;
  3671. print_block(OS, this, **I, Helper, true, ShowColors);
  3672. }
  3673. // Print the exit block.
  3674. print_block(OS, this, getExit(), Helper, true, ShowColors);
  3675. OS << '\n';
  3676. OS.flush();
  3677. }
  3678. /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
  3679. void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
  3680. bool ShowColors) const {
  3681. print(llvm::errs(), cfg, LO, ShowColors);
  3682. }
  3683. void CFGBlock::dump() const {
  3684. dump(getParent(), LangOptions(), false);
  3685. }
  3686. /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
  3687. /// Generally this will only be called from CFG::print.
  3688. void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
  3689. const LangOptions &LO, bool ShowColors) const {
  3690. StmtPrinterHelper Helper(cfg, LO);
  3691. print_block(OS, cfg, *this, Helper, true, ShowColors);
  3692. OS << '\n';
  3693. }
  3694. /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
  3695. void CFGBlock::printTerminator(raw_ostream &OS,
  3696. const LangOptions &LO) const {
  3697. CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
  3698. TPrinter.print(getTerminator());
  3699. }
  3700. Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
  3701. Stmt *Terminator = this->Terminator;
  3702. if (!Terminator)
  3703. return nullptr;
  3704. Expr *E = nullptr;
  3705. switch (Terminator->getStmtClass()) {
  3706. default:
  3707. break;
  3708. case Stmt::CXXForRangeStmtClass:
  3709. E = cast<CXXForRangeStmt>(Terminator)->getCond();
  3710. break;
  3711. case Stmt::ForStmtClass:
  3712. E = cast<ForStmt>(Terminator)->getCond();
  3713. break;
  3714. case Stmt::WhileStmtClass:
  3715. E = cast<WhileStmt>(Terminator)->getCond();
  3716. break;
  3717. case Stmt::DoStmtClass:
  3718. E = cast<DoStmt>(Terminator)->getCond();
  3719. break;
  3720. case Stmt::IfStmtClass:
  3721. E = cast<IfStmt>(Terminator)->getCond();
  3722. break;
  3723. case Stmt::ChooseExprClass:
  3724. E = cast<ChooseExpr>(Terminator)->getCond();
  3725. break;
  3726. case Stmt::IndirectGotoStmtClass:
  3727. E = cast<IndirectGotoStmt>(Terminator)->getTarget();
  3728. break;
  3729. case Stmt::SwitchStmtClass:
  3730. E = cast<SwitchStmt>(Terminator)->getCond();
  3731. break;
  3732. case Stmt::BinaryConditionalOperatorClass:
  3733. E = cast<BinaryConditionalOperator>(Terminator)->getCond();
  3734. break;
  3735. case Stmt::ConditionalOperatorClass:
  3736. E = cast<ConditionalOperator>(Terminator)->getCond();
  3737. break;
  3738. case Stmt::BinaryOperatorClass: // '&&' and '||'
  3739. E = cast<BinaryOperator>(Terminator)->getLHS();
  3740. break;
  3741. case Stmt::ObjCForCollectionStmtClass:
  3742. return Terminator;
  3743. }
  3744. if (!StripParens)
  3745. return E;
  3746. return E ? E->IgnoreParens() : nullptr;
  3747. }
  3748. //===----------------------------------------------------------------------===//
  3749. // CFG Graphviz Visualization
  3750. //===----------------------------------------------------------------------===//
  3751. #ifndef NDEBUG
  3752. static StmtPrinterHelper* GraphHelper;
  3753. #endif
  3754. void CFG::viewCFG(const LangOptions &LO) const {
  3755. #ifndef NDEBUG
  3756. StmtPrinterHelper H(this, LO);
  3757. GraphHelper = &H;
  3758. llvm::ViewGraph(this,"CFG");
  3759. GraphHelper = nullptr;
  3760. #endif
  3761. }
  3762. namespace llvm {
  3763. template<>
  3764. struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
  3765. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  3766. static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
  3767. #ifndef NDEBUG
  3768. std::string OutSStr;
  3769. llvm::raw_string_ostream Out(OutSStr);
  3770. print_block(Out,Graph, *Node, *GraphHelper, false, false);
  3771. std::string& OutStr = Out.str();
  3772. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  3773. // Process string output to make it nicer...
  3774. for (unsigned i = 0; i != OutStr.length(); ++i)
  3775. if (OutStr[i] == '\n') { // Left justify
  3776. OutStr[i] = '\\';
  3777. OutStr.insert(OutStr.begin()+i+1, 'l');
  3778. }
  3779. return OutStr;
  3780. #else
  3781. return "";
  3782. #endif
  3783. }
  3784. };
  3785. } // end namespace llvm