CFG.cpp 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749
  1. //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the CFG and CFGBuilder classes for representing and
  11. // building Control-Flow Graphs (CFGs) from ASTs.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Analysis/Support/SaveAndRestore.h"
  15. #include "clang/Analysis/CFG.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/StmtVisitor.h"
  18. #include "clang/AST/PrettyPrinter.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "llvm/Support/GraphWriter.h"
  21. #include "llvm/Support/Allocator.h"
  22. #include "llvm/Support/Format.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/OwningPtr.h"
  26. using namespace clang;
  27. namespace {
  28. static SourceLocation GetEndLoc(Decl *D) {
  29. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  30. if (Expr *Ex = VD->getInit())
  31. return Ex->getSourceRange().getEnd();
  32. return D->getLocation();
  33. }
  34. class CFGBuilder;
  35. /// The CFG builder uses a recursive algorithm to build the CFG. When
  36. /// we process an expression, sometimes we know that we must add the
  37. /// subexpressions as block-level expressions. For example:
  38. ///
  39. /// exp1 || exp2
  40. ///
  41. /// When processing the '||' expression, we know that exp1 and exp2
  42. /// need to be added as block-level expressions, even though they
  43. /// might not normally need to be. AddStmtChoice records this
  44. /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
  45. /// the builder has an option not to add a subexpression as a
  46. /// block-level expression.
  47. ///
  48. class AddStmtChoice {
  49. public:
  50. enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
  51. AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
  52. bool alwaysAdd(CFGBuilder &builder,
  53. const Stmt *stmt) const;
  54. /// Return a copy of this object, except with the 'always-add' bit
  55. /// set as specified.
  56. AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
  57. return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
  58. }
  59. private:
  60. Kind kind;
  61. };
  62. /// LocalScope - Node in tree of local scopes created for C++ implicit
  63. /// destructor calls generation. It contains list of automatic variables
  64. /// declared in the scope and link to position in previous scope this scope
  65. /// began in.
  66. ///
  67. /// The process of creating local scopes is as follows:
  68. /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
  69. /// - Before processing statements in scope (e.g. CompoundStmt) create
  70. /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
  71. /// and set CFGBuilder::ScopePos to the end of new scope,
  72. /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
  73. /// at this VarDecl,
  74. /// - For every normal (without jump) end of scope add to CFGBlock destructors
  75. /// for objects in the current scope,
  76. /// - For every jump add to CFGBlock destructors for objects
  77. /// between CFGBuilder::ScopePos and local scope position saved for jump
  78. /// target. Thanks to C++ restrictions on goto jumps we can be sure that
  79. /// jump target position will be on the path to root from CFGBuilder::ScopePos
  80. /// (adding any variable that doesn't need constructor to be called to
  81. /// LocalScope can break this assumption),
  82. ///
  83. class LocalScope {
  84. public:
  85. typedef BumpVector<VarDecl*> AutomaticVarsTy;
  86. /// const_iterator - Iterates local scope backwards and jumps to previous
  87. /// scope on reaching the beginning of currently iterated scope.
  88. class const_iterator {
  89. const LocalScope* Scope;
  90. /// VarIter is guaranteed to be greater then 0 for every valid iterator.
  91. /// Invalid iterator (with null Scope) has VarIter equal to 0.
  92. unsigned VarIter;
  93. public:
  94. /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
  95. /// Incrementing invalid iterator is allowed and will result in invalid
  96. /// iterator.
  97. const_iterator()
  98. : Scope(NULL), VarIter(0) {}
  99. /// Create valid iterator. In case when S.Prev is an invalid iterator and
  100. /// I is equal to 0, this will create invalid iterator.
  101. const_iterator(const LocalScope& S, unsigned I)
  102. : Scope(&S), VarIter(I) {
  103. // Iterator to "end" of scope is not allowed. Handle it by going up
  104. // in scopes tree possibly up to invalid iterator in the root.
  105. if (VarIter == 0 && Scope)
  106. *this = Scope->Prev;
  107. }
  108. VarDecl *const* operator->() const {
  109. assert (Scope && "Dereferencing invalid iterator is not allowed");
  110. assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
  111. return &Scope->Vars[VarIter - 1];
  112. }
  113. VarDecl *operator*() const {
  114. return *this->operator->();
  115. }
  116. const_iterator &operator++() {
  117. if (!Scope)
  118. return *this;
  119. assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
  120. --VarIter;
  121. if (VarIter == 0)
  122. *this = Scope->Prev;
  123. return *this;
  124. }
  125. const_iterator operator++(int) {
  126. const_iterator P = *this;
  127. ++*this;
  128. return P;
  129. }
  130. bool operator==(const const_iterator &rhs) const {
  131. return Scope == rhs.Scope && VarIter == rhs.VarIter;
  132. }
  133. bool operator!=(const const_iterator &rhs) const {
  134. return !(*this == rhs);
  135. }
  136. operator bool() const {
  137. return *this != const_iterator();
  138. }
  139. int distance(const_iterator L);
  140. };
  141. friend class const_iterator;
  142. private:
  143. BumpVectorContext ctx;
  144. /// Automatic variables in order of declaration.
  145. AutomaticVarsTy Vars;
  146. /// Iterator to variable in previous scope that was declared just before
  147. /// begin of this scope.
  148. const_iterator Prev;
  149. public:
  150. /// Constructs empty scope linked to previous scope in specified place.
  151. LocalScope(BumpVectorContext &ctx, const_iterator P)
  152. : ctx(ctx), Vars(ctx, 4), Prev(P) {}
  153. /// Begin of scope in direction of CFG building (backwards).
  154. const_iterator begin() const { return const_iterator(*this, Vars.size()); }
  155. void addVar(VarDecl *VD) {
  156. Vars.push_back(VD, ctx);
  157. }
  158. };
  159. /// distance - Calculates distance from this to L. L must be reachable from this
  160. /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
  161. /// number of scopes between this and L.
  162. int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
  163. int D = 0;
  164. const_iterator F = *this;
  165. while (F.Scope != L.Scope) {
  166. assert (F != const_iterator()
  167. && "L iterator is not reachable from F iterator.");
  168. D += F.VarIter;
  169. F = F.Scope->Prev;
  170. }
  171. D += F.VarIter - L.VarIter;
  172. return D;
  173. }
  174. /// BlockScopePosPair - Structure for specifying position in CFG during its
  175. /// build process. It consists of CFGBlock that specifies position in CFG graph
  176. /// and LocalScope::const_iterator that specifies position in LocalScope graph.
  177. struct BlockScopePosPair {
  178. BlockScopePosPair() : block(0) {}
  179. BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
  180. : block(b), scopePosition(scopePos) {}
  181. CFGBlock *block;
  182. LocalScope::const_iterator scopePosition;
  183. };
  184. /// TryResult - a class representing a variant over the values
  185. /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
  186. /// and is used by the CFGBuilder to decide if a branch condition
  187. /// can be decided up front during CFG construction.
  188. class TryResult {
  189. int X;
  190. public:
  191. TryResult(bool b) : X(b ? 1 : 0) {}
  192. TryResult() : X(-1) {}
  193. bool isTrue() const { return X == 1; }
  194. bool isFalse() const { return X == 0; }
  195. bool isKnown() const { return X >= 0; }
  196. void negate() {
  197. assert(isKnown());
  198. X ^= 0x1;
  199. }
  200. };
  201. /// CFGBuilder - This class implements CFG construction from an AST.
  202. /// The builder is stateful: an instance of the builder should be used to only
  203. /// construct a single CFG.
  204. ///
  205. /// Example usage:
  206. ///
  207. /// CFGBuilder builder;
  208. /// CFG* cfg = builder.BuildAST(stmt1);
  209. ///
  210. /// CFG construction is done via a recursive walk of an AST. We actually parse
  211. /// the AST in reverse order so that the successor of a basic block is
  212. /// constructed prior to its predecessor. This allows us to nicely capture
  213. /// implicit fall-throughs without extra basic blocks.
  214. ///
  215. class CFGBuilder {
  216. typedef BlockScopePosPair JumpTarget;
  217. typedef BlockScopePosPair JumpSource;
  218. ASTContext *Context;
  219. llvm::OwningPtr<CFG> cfg;
  220. CFGBlock *Block;
  221. CFGBlock *Succ;
  222. JumpTarget ContinueJumpTarget;
  223. JumpTarget BreakJumpTarget;
  224. CFGBlock *SwitchTerminatedBlock;
  225. CFGBlock *DefaultCaseBlock;
  226. CFGBlock *TryTerminatedBlock;
  227. // Current position in local scope.
  228. LocalScope::const_iterator ScopePos;
  229. // LabelMap records the mapping from Label expressions to their jump targets.
  230. typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
  231. LabelMapTy LabelMap;
  232. // A list of blocks that end with a "goto" that must be backpatched to their
  233. // resolved targets upon completion of CFG construction.
  234. typedef std::vector<JumpSource> BackpatchBlocksTy;
  235. BackpatchBlocksTy BackpatchBlocks;
  236. // A list of labels whose address has been taken (for indirect gotos).
  237. typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
  238. LabelSetTy AddressTakenLabels;
  239. bool badCFG;
  240. const CFG::BuildOptions &BuildOpts;
  241. // State to track for building switch statements.
  242. bool switchExclusivelyCovered;
  243. Expr::EvalResult *switchCond;
  244. CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
  245. const Stmt *lastLookup;
  246. public:
  247. explicit CFGBuilder(ASTContext *astContext,
  248. const CFG::BuildOptions &buildOpts)
  249. : Context(astContext), cfg(new CFG()), // crew a new CFG
  250. Block(NULL), Succ(NULL),
  251. SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
  252. TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts),
  253. switchExclusivelyCovered(false), switchCond(0),
  254. cachedEntry(0), lastLookup(0) {}
  255. // buildCFG - Used by external clients to construct the CFG.
  256. CFG* buildCFG(const Decl *D, Stmt *Statement);
  257. bool alwaysAdd(const Stmt *stmt);
  258. private:
  259. // Visitors to walk an AST and construct the CFG.
  260. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
  261. CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
  262. CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
  263. CFGBlock *VisitBreakStmt(BreakStmt *B);
  264. CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
  265. CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
  266. AddStmtChoice asc);
  267. CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
  268. CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
  269. CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
  270. CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  271. AddStmtChoice asc);
  272. CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
  273. CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  274. AddStmtChoice asc);
  275. CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  276. AddStmtChoice asc);
  277. CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
  278. CFGBlock *VisitCaseStmt(CaseStmt *C);
  279. CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
  280. CFGBlock *VisitCompoundStmt(CompoundStmt *C);
  281. CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
  282. AddStmtChoice asc);
  283. CFGBlock *VisitContinueStmt(ContinueStmt *C);
  284. CFGBlock *VisitDeclStmt(DeclStmt *DS);
  285. CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
  286. CFGBlock *VisitDefaultStmt(DefaultStmt *D);
  287. CFGBlock *VisitDoStmt(DoStmt *D);
  288. CFGBlock *VisitForStmt(ForStmt *F);
  289. CFGBlock *VisitGotoStmt(GotoStmt *G);
  290. CFGBlock *VisitIfStmt(IfStmt *I);
  291. CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
  292. CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
  293. CFGBlock *VisitLabelStmt(LabelStmt *L);
  294. CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
  295. CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
  296. CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  297. CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
  298. CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
  299. CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
  300. CFGBlock *VisitReturnStmt(ReturnStmt *R);
  301. CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  302. AddStmtChoice asc);
  303. CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
  304. CFGBlock *VisitSwitchStmt(SwitchStmt *S);
  305. CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
  306. CFGBlock *VisitWhileStmt(WhileStmt *W);
  307. CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
  308. CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
  309. CFGBlock *VisitChildren(Stmt *S);
  310. // Visitors to walk an AST and generate destructors of temporaries in
  311. // full expression.
  312. CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false);
  313. CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E);
  314. CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E);
  315. CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E,
  316. bool BindToTemporary);
  317. CFGBlock *
  318. VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E,
  319. bool BindToTemporary);
  320. // NYS == Not Yet Supported
  321. CFGBlock *NYS() {
  322. badCFG = true;
  323. return Block;
  324. }
  325. void autoCreateBlock() { if (!Block) Block = createBlock(); }
  326. CFGBlock *createBlock(bool add_successor = true);
  327. CFGBlock *addStmt(Stmt *S) {
  328. return Visit(S, AddStmtChoice::AlwaysAdd);
  329. }
  330. CFGBlock *addInitializer(CXXCtorInitializer *I);
  331. void addAutomaticObjDtors(LocalScope::const_iterator B,
  332. LocalScope::const_iterator E, Stmt *S);
  333. void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
  334. // Local scopes creation.
  335. LocalScope* createOrReuseLocalScope(LocalScope* Scope);
  336. void addLocalScopeForStmt(Stmt *S);
  337. LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL);
  338. LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL);
  339. void addLocalScopeAndDtors(Stmt *S);
  340. // Interface to CFGBlock - adding CFGElements.
  341. void appendStmt(CFGBlock *B, const Stmt *S) {
  342. if (alwaysAdd(S) && cachedEntry)
  343. cachedEntry->second = B;
  344. // All block-level expressions should have already been IgnoreParens()ed.
  345. assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
  346. B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
  347. }
  348. void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
  349. B->appendInitializer(I, cfg->getBumpVectorContext());
  350. }
  351. void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
  352. B->appendBaseDtor(BS, cfg->getBumpVectorContext());
  353. }
  354. void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
  355. B->appendMemberDtor(FD, cfg->getBumpVectorContext());
  356. }
  357. void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
  358. B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
  359. }
  360. void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
  361. B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
  362. }
  363. void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  364. LocalScope::const_iterator B, LocalScope::const_iterator E);
  365. void addSuccessor(CFGBlock *B, CFGBlock *S) {
  366. B->addSuccessor(S, cfg->getBumpVectorContext());
  367. }
  368. /// Try and evaluate an expression to an integer constant.
  369. bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
  370. if (!BuildOpts.PruneTriviallyFalseEdges)
  371. return false;
  372. return !S->isTypeDependent() &&
  373. !S->isValueDependent() &&
  374. S->Evaluate(outResult, *Context);
  375. }
  376. /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
  377. /// if we can evaluate to a known value, otherwise return -1.
  378. TryResult tryEvaluateBool(Expr *S) {
  379. Expr::EvalResult Result;
  380. if (!tryEvaluate(S, Result))
  381. return TryResult();
  382. if (Result.Val.isInt())
  383. return Result.Val.getInt().getBoolValue();
  384. if (Result.Val.isLValue()) {
  385. const Expr *e = Result.Val.getLValueBase();
  386. const CharUnits &c = Result.Val.getLValueOffset();
  387. if (!e && c.isZero())
  388. return false;
  389. }
  390. return TryResult();
  391. }
  392. };
  393. inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
  394. const Stmt *stmt) const {
  395. return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
  396. }
  397. bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
  398. bool shouldAdd = BuildOpts.alwaysAdd(stmt);
  399. if (!BuildOpts.forcedBlkExprs)
  400. return shouldAdd;
  401. if (lastLookup == stmt) {
  402. if (cachedEntry) {
  403. assert(cachedEntry->first == stmt);
  404. return true;
  405. }
  406. return shouldAdd;
  407. }
  408. lastLookup = stmt;
  409. // Perform the lookup!
  410. CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
  411. if (!fb) {
  412. // No need to update 'cachedEntry', since it will always be null.
  413. assert(cachedEntry == 0);
  414. return shouldAdd;
  415. }
  416. CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
  417. if (itr == fb->end()) {
  418. cachedEntry = 0;
  419. return shouldAdd;
  420. }
  421. cachedEntry = &*itr;
  422. return true;
  423. }
  424. // FIXME: Add support for dependent-sized array types in C++?
  425. // Does it even make sense to build a CFG for an uninstantiated template?
  426. static const VariableArrayType *FindVA(const Type *t) {
  427. while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
  428. if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
  429. if (vat->getSizeExpr())
  430. return vat;
  431. t = vt->getElementType().getTypePtr();
  432. }
  433. return 0;
  434. }
  435. /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
  436. /// arbitrary statement. Examples include a single expression or a function
  437. /// body (compound statement). The ownership of the returned CFG is
  438. /// transferred to the caller. If CFG construction fails, this method returns
  439. /// NULL.
  440. CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
  441. assert(cfg.get());
  442. if (!Statement)
  443. return NULL;
  444. // Create an empty block that will serve as the exit block for the CFG. Since
  445. // this is the first block added to the CFG, it will be implicitly registered
  446. // as the exit block.
  447. Succ = createBlock();
  448. assert(Succ == &cfg->getExit());
  449. Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
  450. if (BuildOpts.AddImplicitDtors)
  451. if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
  452. addImplicitDtorsForDestructor(DD);
  453. // Visit the statements and create the CFG.
  454. CFGBlock *B = addStmt(Statement);
  455. if (badCFG)
  456. return NULL;
  457. // For C++ constructor add initializers to CFG.
  458. if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
  459. for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
  460. E = CD->init_rend(); I != E; ++I) {
  461. B = addInitializer(*I);
  462. if (badCFG)
  463. return NULL;
  464. }
  465. }
  466. if (B)
  467. Succ = B;
  468. // Backpatch the gotos whose label -> block mappings we didn't know when we
  469. // encountered them.
  470. for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
  471. E = BackpatchBlocks.end(); I != E; ++I ) {
  472. CFGBlock *B = I->block;
  473. GotoStmt *G = cast<GotoStmt>(B->getTerminator());
  474. LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
  475. // If there is no target for the goto, then we are looking at an
  476. // incomplete AST. Handle this by not registering a successor.
  477. if (LI == LabelMap.end()) continue;
  478. JumpTarget JT = LI->second;
  479. prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
  480. JT.scopePosition);
  481. addSuccessor(B, JT.block);
  482. }
  483. // Add successors to the Indirect Goto Dispatch block (if we have one).
  484. if (CFGBlock *B = cfg->getIndirectGotoBlock())
  485. for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
  486. E = AddressTakenLabels.end(); I != E; ++I ) {
  487. // Lookup the target block.
  488. LabelMapTy::iterator LI = LabelMap.find(*I);
  489. // If there is no target block that contains label, then we are looking
  490. // at an incomplete AST. Handle this by not registering a successor.
  491. if (LI == LabelMap.end()) continue;
  492. addSuccessor(B, LI->second.block);
  493. }
  494. // Create an empty entry block that has no predecessors.
  495. cfg->setEntry(createBlock());
  496. return cfg.take();
  497. }
  498. /// createBlock - Used to lazily create blocks that are connected
  499. /// to the current (global) succcessor.
  500. CFGBlock *CFGBuilder::createBlock(bool add_successor) {
  501. CFGBlock *B = cfg->createBlock();
  502. if (add_successor && Succ)
  503. addSuccessor(B, Succ);
  504. return B;
  505. }
  506. /// addInitializer - Add C++ base or member initializer element to CFG.
  507. CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
  508. if (!BuildOpts.AddInitializers)
  509. return Block;
  510. bool IsReference = false;
  511. bool HasTemporaries = false;
  512. // Destructors of temporaries in initialization expression should be called
  513. // after initialization finishes.
  514. Expr *Init = I->getInit();
  515. if (Init) {
  516. if (FieldDecl *FD = I->getAnyMember())
  517. IsReference = FD->getType()->isReferenceType();
  518. HasTemporaries = isa<ExprWithCleanups>(Init);
  519. if (BuildOpts.AddImplicitDtors && HasTemporaries) {
  520. // Generate destructors for temporaries in initialization expression.
  521. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  522. IsReference);
  523. }
  524. }
  525. autoCreateBlock();
  526. appendInitializer(Block, I);
  527. if (Init) {
  528. if (HasTemporaries) {
  529. // For expression with temporaries go directly to subexpression to omit
  530. // generating destructors for the second time.
  531. return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
  532. }
  533. return Visit(Init);
  534. }
  535. return Block;
  536. }
  537. /// addAutomaticObjDtors - Add to current block automatic objects destructors
  538. /// for objects in range of local scope positions. Use S as trigger statement
  539. /// for destructors.
  540. void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
  541. LocalScope::const_iterator E, Stmt *S) {
  542. if (!BuildOpts.AddImplicitDtors)
  543. return;
  544. if (B == E)
  545. return;
  546. CFGBlock::iterator InsertPos;
  547. // We need to append the destructors in reverse order, but any one of them
  548. // may be a no-return destructor which changes the CFG. As a result, buffer
  549. // this sequence up and replay them in reverse order when appending onto the
  550. // CFGBlock(s).
  551. SmallVector<VarDecl*, 10> Decls;
  552. Decls.reserve(B.distance(E));
  553. for (LocalScope::const_iterator I = B; I != E; ++I)
  554. Decls.push_back(*I);
  555. for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
  556. E = Decls.rend();
  557. I != E; ++I) {
  558. // If this destructor is marked as a no-return destructor, we need to
  559. // create a new block for the destructor which does not have as a successor
  560. // anything built thus far: control won't flow out of this block.
  561. QualType Ty = (*I)->getType().getNonReferenceType();
  562. if (const ArrayType *AT = Context->getAsArrayType(Ty))
  563. Ty = AT->getElementType();
  564. const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
  565. if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) {
  566. Block = createBlock(/*add_successor=*/false);
  567. // Wire up this block directly to the exit block if we're in the
  568. // no-return case. We pruned any other successors because control flow
  569. // won't actually exit this block, but we want to be able to find all of
  570. // these entries in the CFG when doing analyses.
  571. addSuccessor(Block, &cfg->getExit());
  572. } else {
  573. autoCreateBlock();
  574. }
  575. appendAutomaticObjDtor(Block, *I, S);
  576. }
  577. }
  578. /// addImplicitDtorsForDestructor - Add implicit destructors generated for
  579. /// base and member objects in destructor.
  580. void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
  581. assert (BuildOpts.AddImplicitDtors
  582. && "Can be called only when dtors should be added");
  583. const CXXRecordDecl *RD = DD->getParent();
  584. // At the end destroy virtual base objects.
  585. for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
  586. VE = RD->vbases_end(); VI != VE; ++VI) {
  587. const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
  588. if (!CD->hasTrivialDestructor()) {
  589. autoCreateBlock();
  590. appendBaseDtor(Block, VI);
  591. }
  592. }
  593. // Before virtual bases destroy direct base objects.
  594. for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
  595. BE = RD->bases_end(); BI != BE; ++BI) {
  596. if (!BI->isVirtual()) {
  597. const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
  598. if (!CD->hasTrivialDestructor()) {
  599. autoCreateBlock();
  600. appendBaseDtor(Block, BI);
  601. }
  602. }
  603. }
  604. // First destroy member objects.
  605. for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
  606. FE = RD->field_end(); FI != FE; ++FI) {
  607. // Check for constant size array. Set type to array element type.
  608. QualType QT = FI->getType();
  609. if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  610. if (AT->getSize() == 0)
  611. continue;
  612. QT = AT->getElementType();
  613. }
  614. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  615. if (!CD->hasTrivialDestructor()) {
  616. autoCreateBlock();
  617. appendMemberDtor(Block, *FI);
  618. }
  619. }
  620. }
  621. /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
  622. /// way return valid LocalScope object.
  623. LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
  624. if (!Scope) {
  625. llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
  626. Scope = alloc.Allocate<LocalScope>();
  627. BumpVectorContext ctx(alloc);
  628. new (Scope) LocalScope(ctx, ScopePos);
  629. }
  630. return Scope;
  631. }
  632. /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
  633. /// that should create implicit scope (e.g. if/else substatements).
  634. void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
  635. if (!BuildOpts.AddImplicitDtors)
  636. return;
  637. LocalScope *Scope = 0;
  638. // For compound statement we will be creating explicit scope.
  639. if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
  640. for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
  641. ; BI != BE; ++BI) {
  642. Stmt *SI = (*BI)->stripLabelLikeStatements();
  643. if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
  644. Scope = addLocalScopeForDeclStmt(DS, Scope);
  645. }
  646. return;
  647. }
  648. // For any other statement scope will be implicit and as such will be
  649. // interesting only for DeclStmt.
  650. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
  651. addLocalScopeForDeclStmt(DS);
  652. }
  653. /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
  654. /// reuse Scope if not NULL.
  655. LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
  656. LocalScope* Scope) {
  657. if (!BuildOpts.AddImplicitDtors)
  658. return Scope;
  659. for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
  660. ; DI != DE; ++DI) {
  661. if (VarDecl *VD = dyn_cast<VarDecl>(*DI))
  662. Scope = addLocalScopeForVarDecl(VD, Scope);
  663. }
  664. return Scope;
  665. }
  666. /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
  667. /// create add scope for automatic objects and temporary objects bound to
  668. /// const reference. Will reuse Scope if not NULL.
  669. LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
  670. LocalScope* Scope) {
  671. if (!BuildOpts.AddImplicitDtors)
  672. return Scope;
  673. // Check if variable is local.
  674. switch (VD->getStorageClass()) {
  675. case SC_None:
  676. case SC_Auto:
  677. case SC_Register:
  678. break;
  679. default: return Scope;
  680. }
  681. // Check for const references bound to temporary. Set type to pointee.
  682. QualType QT = VD->getType();
  683. if (const ReferenceType* RT = QT.getTypePtr()->getAs<ReferenceType>()) {
  684. QT = RT->getPointeeType();
  685. if (!QT.isConstQualified())
  686. return Scope;
  687. if (!VD->extendsLifetimeOfTemporary())
  688. return Scope;
  689. }
  690. // Check for constant size array. Set type to array element type.
  691. if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  692. if (AT->getSize() == 0)
  693. return Scope;
  694. QT = AT->getElementType();
  695. }
  696. // Check if type is a C++ class with non-trivial destructor.
  697. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  698. if (!CD->hasTrivialDestructor()) {
  699. // Add the variable to scope
  700. Scope = createOrReuseLocalScope(Scope);
  701. Scope->addVar(VD);
  702. ScopePos = Scope->begin();
  703. }
  704. return Scope;
  705. }
  706. /// addLocalScopeAndDtors - For given statement add local scope for it and
  707. /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
  708. void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
  709. if (!BuildOpts.AddImplicitDtors)
  710. return;
  711. LocalScope::const_iterator scopeBeginPos = ScopePos;
  712. addLocalScopeForStmt(S);
  713. addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
  714. }
  715. /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
  716. /// variables with automatic storage duration to CFGBlock's elements vector.
  717. /// Elements will be prepended to physical beginning of the vector which
  718. /// happens to be logical end. Use blocks terminator as statement that specifies
  719. /// destructors call site.
  720. /// FIXME: This mechanism for adding automatic destructors doesn't handle
  721. /// no-return destructors properly.
  722. void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  723. LocalScope::const_iterator B, LocalScope::const_iterator E) {
  724. BumpVectorContext &C = cfg->getBumpVectorContext();
  725. CFGBlock::iterator InsertPos
  726. = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
  727. for (LocalScope::const_iterator I = B; I != E; ++I)
  728. InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
  729. Blk->getTerminator());
  730. }
  731. /// Visit - Walk the subtree of a statement and add extra
  732. /// blocks for ternary operators, &&, and ||. We also process "," and
  733. /// DeclStmts (which may contain nested control-flow).
  734. CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
  735. if (!S) {
  736. badCFG = true;
  737. return 0;
  738. }
  739. if (Expr *E = dyn_cast<Expr>(S))
  740. S = E->IgnoreParens();
  741. switch (S->getStmtClass()) {
  742. default:
  743. return VisitStmt(S, asc);
  744. case Stmt::AddrLabelExprClass:
  745. return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
  746. case Stmt::BinaryConditionalOperatorClass:
  747. return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
  748. case Stmt::BinaryOperatorClass:
  749. return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
  750. case Stmt::BlockExprClass:
  751. return VisitBlockExpr(cast<BlockExpr>(S), asc);
  752. case Stmt::BreakStmtClass:
  753. return VisitBreakStmt(cast<BreakStmt>(S));
  754. case Stmt::CallExprClass:
  755. case Stmt::CXXOperatorCallExprClass:
  756. case Stmt::CXXMemberCallExprClass:
  757. return VisitCallExpr(cast<CallExpr>(S), asc);
  758. case Stmt::CaseStmtClass:
  759. return VisitCaseStmt(cast<CaseStmt>(S));
  760. case Stmt::ChooseExprClass:
  761. return VisitChooseExpr(cast<ChooseExpr>(S), asc);
  762. case Stmt::CompoundStmtClass:
  763. return VisitCompoundStmt(cast<CompoundStmt>(S));
  764. case Stmt::ConditionalOperatorClass:
  765. return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
  766. case Stmt::ContinueStmtClass:
  767. return VisitContinueStmt(cast<ContinueStmt>(S));
  768. case Stmt::CXXCatchStmtClass:
  769. return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
  770. case Stmt::ExprWithCleanupsClass:
  771. return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
  772. case Stmt::CXXBindTemporaryExprClass:
  773. return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
  774. case Stmt::CXXConstructExprClass:
  775. return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
  776. case Stmt::CXXFunctionalCastExprClass:
  777. return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
  778. case Stmt::CXXTemporaryObjectExprClass:
  779. return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
  780. case Stmt::CXXThrowExprClass:
  781. return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
  782. case Stmt::CXXTryStmtClass:
  783. return VisitCXXTryStmt(cast<CXXTryStmt>(S));
  784. case Stmt::CXXForRangeStmtClass:
  785. return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
  786. case Stmt::DeclStmtClass:
  787. return VisitDeclStmt(cast<DeclStmt>(S));
  788. case Stmt::DefaultStmtClass:
  789. return VisitDefaultStmt(cast<DefaultStmt>(S));
  790. case Stmt::DoStmtClass:
  791. return VisitDoStmt(cast<DoStmt>(S));
  792. case Stmt::ForStmtClass:
  793. return VisitForStmt(cast<ForStmt>(S));
  794. case Stmt::GotoStmtClass:
  795. return VisitGotoStmt(cast<GotoStmt>(S));
  796. case Stmt::IfStmtClass:
  797. return VisitIfStmt(cast<IfStmt>(S));
  798. case Stmt::ImplicitCastExprClass:
  799. return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
  800. case Stmt::IndirectGotoStmtClass:
  801. return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
  802. case Stmt::LabelStmtClass:
  803. return VisitLabelStmt(cast<LabelStmt>(S));
  804. case Stmt::MemberExprClass:
  805. return VisitMemberExpr(cast<MemberExpr>(S), asc);
  806. case Stmt::ObjCAtCatchStmtClass:
  807. return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
  808. case Stmt::ObjCAtSynchronizedStmtClass:
  809. return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
  810. case Stmt::ObjCAtThrowStmtClass:
  811. return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
  812. case Stmt::ObjCAtTryStmtClass:
  813. return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
  814. case Stmt::ObjCForCollectionStmtClass:
  815. return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
  816. case Stmt::NullStmtClass:
  817. return Block;
  818. case Stmt::ReturnStmtClass:
  819. return VisitReturnStmt(cast<ReturnStmt>(S));
  820. case Stmt::UnaryExprOrTypeTraitExprClass:
  821. return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  822. asc);
  823. case Stmt::StmtExprClass:
  824. return VisitStmtExpr(cast<StmtExpr>(S), asc);
  825. case Stmt::SwitchStmtClass:
  826. return VisitSwitchStmt(cast<SwitchStmt>(S));
  827. case Stmt::UnaryOperatorClass:
  828. return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
  829. case Stmt::WhileStmtClass:
  830. return VisitWhileStmt(cast<WhileStmt>(S));
  831. }
  832. }
  833. CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
  834. if (asc.alwaysAdd(*this, S)) {
  835. autoCreateBlock();
  836. appendStmt(Block, S);
  837. }
  838. return VisitChildren(S);
  839. }
  840. /// VisitChildren - Visit the children of a Stmt.
  841. CFGBlock *CFGBuilder::VisitChildren(Stmt *Terminator) {
  842. CFGBlock *lastBlock = Block;
  843. for (Stmt::child_range I = Terminator->children(); I; ++I)
  844. if (Stmt *child = *I)
  845. if (CFGBlock *b = Visit(child))
  846. lastBlock = b;
  847. return lastBlock;
  848. }
  849. CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
  850. AddStmtChoice asc) {
  851. AddressTakenLabels.insert(A->getLabel());
  852. if (asc.alwaysAdd(*this, A)) {
  853. autoCreateBlock();
  854. appendStmt(Block, A);
  855. }
  856. return Block;
  857. }
  858. CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
  859. AddStmtChoice asc) {
  860. if (asc.alwaysAdd(*this, U)) {
  861. autoCreateBlock();
  862. appendStmt(Block, U);
  863. }
  864. return Visit(U->getSubExpr(), AddStmtChoice());
  865. }
  866. CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
  867. AddStmtChoice asc) {
  868. if (B->isLogicalOp()) { // && or ||
  869. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  870. appendStmt(ConfluenceBlock, B);
  871. if (badCFG)
  872. return 0;
  873. // create the block evaluating the LHS
  874. CFGBlock *LHSBlock = createBlock(false);
  875. LHSBlock->setTerminator(B);
  876. // create the block evaluating the RHS
  877. Succ = ConfluenceBlock;
  878. Block = NULL;
  879. CFGBlock *RHSBlock = addStmt(B->getRHS());
  880. if (RHSBlock) {
  881. if (badCFG)
  882. return 0;
  883. } else {
  884. // Create an empty block for cases where the RHS doesn't require
  885. // any explicit statements in the CFG.
  886. RHSBlock = createBlock();
  887. }
  888. // See if this is a known constant.
  889. TryResult KnownVal = tryEvaluateBool(B->getLHS());
  890. if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr))
  891. KnownVal.negate();
  892. // Now link the LHSBlock with RHSBlock.
  893. if (B->getOpcode() == BO_LOr) {
  894. addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
  895. addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
  896. } else {
  897. assert(B->getOpcode() == BO_LAnd);
  898. addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
  899. addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
  900. }
  901. // Generate the blocks for evaluating the LHS.
  902. Block = LHSBlock;
  903. return addStmt(B->getLHS());
  904. }
  905. if (B->getOpcode() == BO_Comma) { // ,
  906. autoCreateBlock();
  907. appendStmt(Block, B);
  908. addStmt(B->getRHS());
  909. return addStmt(B->getLHS());
  910. }
  911. if (B->isAssignmentOp()) {
  912. if (asc.alwaysAdd(*this, B)) {
  913. autoCreateBlock();
  914. appendStmt(Block, B);
  915. }
  916. Visit(B->getLHS());
  917. return Visit(B->getRHS());
  918. }
  919. if (asc.alwaysAdd(*this, B)) {
  920. autoCreateBlock();
  921. appendStmt(Block, B);
  922. }
  923. CFGBlock *RBlock = Visit(B->getRHS());
  924. CFGBlock *LBlock = Visit(B->getLHS());
  925. // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
  926. // containing a DoStmt, and the LHS doesn't create a new block, then we should
  927. // return RBlock. Otherwise we'll incorrectly return NULL.
  928. return (LBlock ? LBlock : RBlock);
  929. }
  930. CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
  931. if (asc.alwaysAdd(*this, E)) {
  932. autoCreateBlock();
  933. appendStmt(Block, E);
  934. }
  935. return Block;
  936. }
  937. CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
  938. // "break" is a control-flow statement. Thus we stop processing the current
  939. // block.
  940. if (badCFG)
  941. return 0;
  942. // Now create a new block that ends with the break statement.
  943. Block = createBlock(false);
  944. Block->setTerminator(B);
  945. // If there is no target for the break, then we are looking at an incomplete
  946. // AST. This means that the CFG cannot be constructed.
  947. if (BreakJumpTarget.block) {
  948. addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
  949. addSuccessor(Block, BreakJumpTarget.block);
  950. } else
  951. badCFG = true;
  952. return Block;
  953. }
  954. static bool CanThrow(Expr *E, ASTContext &Ctx) {
  955. QualType Ty = E->getType();
  956. if (Ty->isFunctionPointerType())
  957. Ty = Ty->getAs<PointerType>()->getPointeeType();
  958. else if (Ty->isBlockPointerType())
  959. Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
  960. const FunctionType *FT = Ty->getAs<FunctionType>();
  961. if (FT) {
  962. if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
  963. if (Proto->isNothrow(Ctx))
  964. return false;
  965. }
  966. return true;
  967. }
  968. CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
  969. // Compute the callee type.
  970. QualType calleeType = C->getCallee()->getType();
  971. if (calleeType == Context->BoundMemberTy) {
  972. QualType boundType = Expr::findBoundMemberType(C->getCallee());
  973. // We should only get a null bound type if processing a dependent
  974. // CFG. Recover by assuming nothing.
  975. if (!boundType.isNull()) calleeType = boundType;
  976. }
  977. // If this is a call to a no-return function, this stops the block here.
  978. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
  979. bool AddEHEdge = false;
  980. // Languages without exceptions are assumed to not throw.
  981. if (Context->getLangOptions().Exceptions) {
  982. if (BuildOpts.AddEHEdges)
  983. AddEHEdge = true;
  984. }
  985. if (FunctionDecl *FD = C->getDirectCallee()) {
  986. if (FD->hasAttr<NoReturnAttr>())
  987. NoReturn = true;
  988. if (FD->hasAttr<NoThrowAttr>())
  989. AddEHEdge = false;
  990. }
  991. if (!CanThrow(C->getCallee(), *Context))
  992. AddEHEdge = false;
  993. if (!NoReturn && !AddEHEdge)
  994. return VisitStmt(C, asc.withAlwaysAdd(true));
  995. if (Block) {
  996. Succ = Block;
  997. if (badCFG)
  998. return 0;
  999. }
  1000. Block = createBlock(!NoReturn);
  1001. appendStmt(Block, C);
  1002. if (NoReturn) {
  1003. // Wire this to the exit block directly.
  1004. addSuccessor(Block, &cfg->getExit());
  1005. }
  1006. if (AddEHEdge) {
  1007. // Add exceptional edges.
  1008. if (TryTerminatedBlock)
  1009. addSuccessor(Block, TryTerminatedBlock);
  1010. else
  1011. addSuccessor(Block, &cfg->getExit());
  1012. }
  1013. return VisitChildren(C);
  1014. }
  1015. CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
  1016. AddStmtChoice asc) {
  1017. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  1018. appendStmt(ConfluenceBlock, C);
  1019. if (badCFG)
  1020. return 0;
  1021. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  1022. Succ = ConfluenceBlock;
  1023. Block = NULL;
  1024. CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
  1025. if (badCFG)
  1026. return 0;
  1027. Succ = ConfluenceBlock;
  1028. Block = NULL;
  1029. CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
  1030. if (badCFG)
  1031. return 0;
  1032. Block = createBlock(false);
  1033. // See if this is a known constant.
  1034. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  1035. addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
  1036. addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
  1037. Block->setTerminator(C);
  1038. return addStmt(C->getCond());
  1039. }
  1040. CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
  1041. addLocalScopeAndDtors(C);
  1042. CFGBlock *LastBlock = Block;
  1043. for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
  1044. I != E; ++I ) {
  1045. // If we hit a segment of code just containing ';' (NullStmts), we can
  1046. // get a null block back. In such cases, just use the LastBlock
  1047. if (CFGBlock *newBlock = addStmt(*I))
  1048. LastBlock = newBlock;
  1049. if (badCFG)
  1050. return NULL;
  1051. }
  1052. return LastBlock;
  1053. }
  1054. CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
  1055. AddStmtChoice asc) {
  1056. const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
  1057. const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL);
  1058. // Create the confluence block that will "merge" the results of the ternary
  1059. // expression.
  1060. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  1061. appendStmt(ConfluenceBlock, C);
  1062. if (badCFG)
  1063. return 0;
  1064. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  1065. // Create a block for the LHS expression if there is an LHS expression. A
  1066. // GCC extension allows LHS to be NULL, causing the condition to be the
  1067. // value that is returned instead.
  1068. // e.g: x ?: y is shorthand for: x ? x : y;
  1069. Succ = ConfluenceBlock;
  1070. Block = NULL;
  1071. CFGBlock *LHSBlock = 0;
  1072. const Expr *trueExpr = C->getTrueExpr();
  1073. if (trueExpr != opaqueValue) {
  1074. LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
  1075. if (badCFG)
  1076. return 0;
  1077. Block = NULL;
  1078. }
  1079. else
  1080. LHSBlock = ConfluenceBlock;
  1081. // Create the block for the RHS expression.
  1082. Succ = ConfluenceBlock;
  1083. CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
  1084. if (badCFG)
  1085. return 0;
  1086. // Create the block that will contain the condition.
  1087. Block = createBlock(false);
  1088. // See if this is a known constant.
  1089. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  1090. addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
  1091. addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
  1092. Block->setTerminator(C);
  1093. Expr *condExpr = C->getCond();
  1094. if (opaqueValue) {
  1095. // Run the condition expression if it's not trivially expressed in
  1096. // terms of the opaque value (or if there is no opaque value).
  1097. if (condExpr != opaqueValue)
  1098. addStmt(condExpr);
  1099. // Before that, run the common subexpression if there was one.
  1100. // At least one of this or the above will be run.
  1101. return addStmt(BCO->getCommon());
  1102. }
  1103. return addStmt(condExpr);
  1104. }
  1105. CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
  1106. // Check if the Decl is for an __label__. If so, elide it from the
  1107. // CFG entirely.
  1108. if (isa<LabelDecl>(*DS->decl_begin()))
  1109. return Block;
  1110. // This case also handles static_asserts.
  1111. if (DS->isSingleDecl())
  1112. return VisitDeclSubExpr(DS);
  1113. CFGBlock *B = 0;
  1114. // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
  1115. typedef SmallVector<Decl*,10> BufTy;
  1116. BufTy Buf(DS->decl_begin(), DS->decl_end());
  1117. for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
  1118. // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
  1119. unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
  1120. ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
  1121. // Allocate the DeclStmt using the BumpPtrAllocator. It will get
  1122. // automatically freed with the CFG.
  1123. DeclGroupRef DG(*I);
  1124. Decl *D = *I;
  1125. void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
  1126. DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
  1127. // Append the fake DeclStmt to block.
  1128. B = VisitDeclSubExpr(DSNew);
  1129. }
  1130. return B;
  1131. }
  1132. /// VisitDeclSubExpr - Utility method to add block-level expressions for
  1133. /// DeclStmts and initializers in them.
  1134. CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
  1135. assert(DS->isSingleDecl() && "Can handle single declarations only.");
  1136. Decl *D = DS->getSingleDecl();
  1137. if (isa<StaticAssertDecl>(D)) {
  1138. // static_asserts aren't added to the CFG because they do not impact
  1139. // runtime semantics.
  1140. return Block;
  1141. }
  1142. VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  1143. if (!VD) {
  1144. autoCreateBlock();
  1145. appendStmt(Block, DS);
  1146. return Block;
  1147. }
  1148. bool IsReference = false;
  1149. bool HasTemporaries = false;
  1150. // Destructors of temporaries in initialization expression should be called
  1151. // after initialization finishes.
  1152. Expr *Init = VD->getInit();
  1153. if (Init) {
  1154. IsReference = VD->getType()->isReferenceType();
  1155. HasTemporaries = isa<ExprWithCleanups>(Init);
  1156. if (BuildOpts.AddImplicitDtors && HasTemporaries) {
  1157. // Generate destructors for temporaries in initialization expression.
  1158. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  1159. IsReference);
  1160. }
  1161. }
  1162. autoCreateBlock();
  1163. appendStmt(Block, DS);
  1164. if (Init) {
  1165. if (HasTemporaries)
  1166. // For expression with temporaries go directly to subexpression to omit
  1167. // generating destructors for the second time.
  1168. Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
  1169. else
  1170. Visit(Init);
  1171. }
  1172. // If the type of VD is a VLA, then we must process its size expressions.
  1173. for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
  1174. VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
  1175. Block = addStmt(VA->getSizeExpr());
  1176. // Remove variable from local scope.
  1177. if (ScopePos && VD == *ScopePos)
  1178. ++ScopePos;
  1179. return Block;
  1180. }
  1181. CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
  1182. // We may see an if statement in the middle of a basic block, or it may be the
  1183. // first statement we are processing. In either case, we create a new basic
  1184. // block. First, we create the blocks for the then...else statements, and
  1185. // then we create the block containing the if statement. If we were in the
  1186. // middle of a block, we stop processing that block. That block is then the
  1187. // implicit successor for the "then" and "else" clauses.
  1188. // Save local scope position because in case of condition variable ScopePos
  1189. // won't be restored when traversing AST.
  1190. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  1191. // Create local scope for possible condition variable.
  1192. // Store scope position. Add implicit destructor.
  1193. if (VarDecl *VD = I->getConditionVariable()) {
  1194. LocalScope::const_iterator BeginScopePos = ScopePos;
  1195. addLocalScopeForVarDecl(VD);
  1196. addAutomaticObjDtors(ScopePos, BeginScopePos, I);
  1197. }
  1198. // The block we were processing is now finished. Make it the successor
  1199. // block.
  1200. if (Block) {
  1201. Succ = Block;
  1202. if (badCFG)
  1203. return 0;
  1204. }
  1205. // Process the false branch.
  1206. CFGBlock *ElseBlock = Succ;
  1207. if (Stmt *Else = I->getElse()) {
  1208. SaveAndRestore<CFGBlock*> sv(Succ);
  1209. // NULL out Block so that the recursive call to Visit will
  1210. // create a new basic block.
  1211. Block = NULL;
  1212. // If branch is not a compound statement create implicit scope
  1213. // and add destructors.
  1214. if (!isa<CompoundStmt>(Else))
  1215. addLocalScopeAndDtors(Else);
  1216. ElseBlock = addStmt(Else);
  1217. if (!ElseBlock) // Can occur when the Else body has all NullStmts.
  1218. ElseBlock = sv.get();
  1219. else if (Block) {
  1220. if (badCFG)
  1221. return 0;
  1222. }
  1223. }
  1224. // Process the true branch.
  1225. CFGBlock *ThenBlock;
  1226. {
  1227. Stmt *Then = I->getThen();
  1228. assert(Then);
  1229. SaveAndRestore<CFGBlock*> sv(Succ);
  1230. Block = NULL;
  1231. // If branch is not a compound statement create implicit scope
  1232. // and add destructors.
  1233. if (!isa<CompoundStmt>(Then))
  1234. addLocalScopeAndDtors(Then);
  1235. ThenBlock = addStmt(Then);
  1236. if (!ThenBlock) {
  1237. // We can reach here if the "then" body has all NullStmts.
  1238. // Create an empty block so we can distinguish between true and false
  1239. // branches in path-sensitive analyses.
  1240. ThenBlock = createBlock(false);
  1241. addSuccessor(ThenBlock, sv.get());
  1242. } else if (Block) {
  1243. if (badCFG)
  1244. return 0;
  1245. }
  1246. }
  1247. // Now create a new block containing the if statement.
  1248. Block = createBlock(false);
  1249. // Set the terminator of the new block to the If statement.
  1250. Block->setTerminator(I);
  1251. // See if this is a known constant.
  1252. const TryResult &KnownVal = tryEvaluateBool(I->getCond());
  1253. // Now add the successors.
  1254. addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
  1255. addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
  1256. // Add the condition as the last statement in the new block. This may create
  1257. // new blocks as the condition may contain control-flow. Any newly created
  1258. // blocks will be pointed to be "Block".
  1259. Block = addStmt(I->getCond());
  1260. // Finally, if the IfStmt contains a condition variable, add both the IfStmt
  1261. // and the condition variable initialization to the CFG.
  1262. if (VarDecl *VD = I->getConditionVariable()) {
  1263. if (Expr *Init = VD->getInit()) {
  1264. autoCreateBlock();
  1265. appendStmt(Block, I->getConditionVariableDeclStmt());
  1266. addStmt(Init);
  1267. }
  1268. }
  1269. return Block;
  1270. }
  1271. CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
  1272. // If we were in the middle of a block we stop processing that block.
  1273. //
  1274. // NOTE: If a "return" appears in the middle of a block, this means that the
  1275. // code afterwards is DEAD (unreachable). We still keep a basic block
  1276. // for that code; a simple "mark-and-sweep" from the entry block will be
  1277. // able to report such dead blocks.
  1278. // Create the new block.
  1279. Block = createBlock(false);
  1280. // The Exit block is the only successor.
  1281. addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
  1282. addSuccessor(Block, &cfg->getExit());
  1283. // Add the return statement to the block. This may create new blocks if R
  1284. // contains control-flow (short-circuit operations).
  1285. return VisitStmt(R, AddStmtChoice::AlwaysAdd);
  1286. }
  1287. CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
  1288. // Get the block of the labeled statement. Add it to our map.
  1289. addStmt(L->getSubStmt());
  1290. CFGBlock *LabelBlock = Block;
  1291. if (!LabelBlock) // This can happen when the body is empty, i.e.
  1292. LabelBlock = createBlock(); // scopes that only contains NullStmts.
  1293. assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
  1294. "label already in map");
  1295. LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
  1296. // Labels partition blocks, so this is the end of the basic block we were
  1297. // processing (L is the block's label). Because this is label (and we have
  1298. // already processed the substatement) there is no extra control-flow to worry
  1299. // about.
  1300. LabelBlock->setLabel(L);
  1301. if (badCFG)
  1302. return 0;
  1303. // We set Block to NULL to allow lazy creation of a new block (if necessary);
  1304. Block = NULL;
  1305. // This block is now the implicit successor of other blocks.
  1306. Succ = LabelBlock;
  1307. return LabelBlock;
  1308. }
  1309. CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
  1310. // Goto is a control-flow statement. Thus we stop processing the current
  1311. // block and create a new one.
  1312. Block = createBlock(false);
  1313. Block->setTerminator(G);
  1314. // If we already know the mapping to the label block add the successor now.
  1315. LabelMapTy::iterator I = LabelMap.find(G->getLabel());
  1316. if (I == LabelMap.end())
  1317. // We will need to backpatch this block later.
  1318. BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
  1319. else {
  1320. JumpTarget JT = I->second;
  1321. addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
  1322. addSuccessor(Block, JT.block);
  1323. }
  1324. return Block;
  1325. }
  1326. CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
  1327. CFGBlock *LoopSuccessor = NULL;
  1328. // Save local scope position because in case of condition variable ScopePos
  1329. // won't be restored when traversing AST.
  1330. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  1331. // Create local scope for init statement and possible condition variable.
  1332. // Add destructor for init statement and condition variable.
  1333. // Store scope position for continue statement.
  1334. if (Stmt *Init = F->getInit())
  1335. addLocalScopeForStmt(Init);
  1336. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  1337. if (VarDecl *VD = F->getConditionVariable())
  1338. addLocalScopeForVarDecl(VD);
  1339. LocalScope::const_iterator ContinueScopePos = ScopePos;
  1340. addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
  1341. // "for" is a control-flow statement. Thus we stop processing the current
  1342. // block.
  1343. if (Block) {
  1344. if (badCFG)
  1345. return 0;
  1346. LoopSuccessor = Block;
  1347. } else
  1348. LoopSuccessor = Succ;
  1349. // Save the current value for the break targets.
  1350. // All breaks should go to the code following the loop.
  1351. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  1352. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  1353. // Because of short-circuit evaluation, the condition of the loop can span
  1354. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  1355. // evaluate the condition.
  1356. CFGBlock *ExitConditionBlock = createBlock(false);
  1357. CFGBlock *EntryConditionBlock = ExitConditionBlock;
  1358. // Set the terminator for the "exit" condition block.
  1359. ExitConditionBlock->setTerminator(F);
  1360. // Now add the actual condition to the condition block. Because the condition
  1361. // itself may contain control-flow, new blocks may be created.
  1362. if (Stmt *C = F->getCond()) {
  1363. Block = ExitConditionBlock;
  1364. EntryConditionBlock = addStmt(C);
  1365. if (badCFG)
  1366. return 0;
  1367. assert(Block == EntryConditionBlock ||
  1368. (Block == 0 && EntryConditionBlock == Succ));
  1369. // If this block contains a condition variable, add both the condition
  1370. // variable and initializer to the CFG.
  1371. if (VarDecl *VD = F->getConditionVariable()) {
  1372. if (Expr *Init = VD->getInit()) {
  1373. autoCreateBlock();
  1374. appendStmt(Block, F->getConditionVariableDeclStmt());
  1375. EntryConditionBlock = addStmt(Init);
  1376. assert(Block == EntryConditionBlock);
  1377. }
  1378. }
  1379. if (Block) {
  1380. if (badCFG)
  1381. return 0;
  1382. }
  1383. }
  1384. // The condition block is the implicit successor for the loop body as well as
  1385. // any code above the loop.
  1386. Succ = EntryConditionBlock;
  1387. // See if this is a known constant.
  1388. TryResult KnownVal(true);
  1389. if (F->getCond())
  1390. KnownVal = tryEvaluateBool(F->getCond());
  1391. // Now create the loop body.
  1392. {
  1393. assert(F->getBody());
  1394. // Save the current values for Block, Succ, and continue targets.
  1395. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  1396. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
  1397. // Create a new block to contain the (bottom) of the loop body.
  1398. Block = NULL;
  1399. // Loop body should end with destructor of Condition variable (if any).
  1400. addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
  1401. if (Stmt *I = F->getInc()) {
  1402. // Generate increment code in its own basic block. This is the target of
  1403. // continue statements.
  1404. Succ = addStmt(I);
  1405. } else {
  1406. // No increment code. Create a special, empty, block that is used as the
  1407. // target block for "looping back" to the start of the loop.
  1408. assert(Succ == EntryConditionBlock);
  1409. Succ = Block ? Block : createBlock();
  1410. }
  1411. // Finish up the increment (or empty) block if it hasn't been already.
  1412. if (Block) {
  1413. assert(Block == Succ);
  1414. if (badCFG)
  1415. return 0;
  1416. Block = 0;
  1417. }
  1418. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  1419. // The starting block for the loop increment is the block that should
  1420. // represent the 'loop target' for looping back to the start of the loop.
  1421. ContinueJumpTarget.block->setLoopTarget(F);
  1422. // If body is not a compound statement create implicit scope
  1423. // and add destructors.
  1424. if (!isa<CompoundStmt>(F->getBody()))
  1425. addLocalScopeAndDtors(F->getBody());
  1426. // Now populate the body block, and in the process create new blocks as we
  1427. // walk the body of the loop.
  1428. CFGBlock *BodyBlock = addStmt(F->getBody());
  1429. if (!BodyBlock)
  1430. BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);"
  1431. else if (badCFG)
  1432. return 0;
  1433. // This new body block is a successor to our "exit" condition block.
  1434. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
  1435. }
  1436. // Link up the condition block with the code that follows the loop. (the
  1437. // false branch).
  1438. addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
  1439. // If the loop contains initialization, create a new block for those
  1440. // statements. This block can also contain statements that precede the loop.
  1441. if (Stmt *I = F->getInit()) {
  1442. Block = createBlock();
  1443. return addStmt(I);
  1444. }
  1445. // There is no loop initialization. We are thus basically a while loop.
  1446. // NULL out Block to force lazy block construction.
  1447. Block = NULL;
  1448. Succ = EntryConditionBlock;
  1449. return EntryConditionBlock;
  1450. }
  1451. CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
  1452. if (asc.alwaysAdd(*this, M)) {
  1453. autoCreateBlock();
  1454. appendStmt(Block, M);
  1455. }
  1456. return Visit(M->getBase());
  1457. }
  1458. CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
  1459. // Objective-C fast enumeration 'for' statements:
  1460. // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
  1461. //
  1462. // for ( Type newVariable in collection_expression ) { statements }
  1463. //
  1464. // becomes:
  1465. //
  1466. // prologue:
  1467. // 1. collection_expression
  1468. // T. jump to loop_entry
  1469. // loop_entry:
  1470. // 1. side-effects of element expression
  1471. // 1. ObjCForCollectionStmt [performs binding to newVariable]
  1472. // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
  1473. // TB:
  1474. // statements
  1475. // T. jump to loop_entry
  1476. // FB:
  1477. // what comes after
  1478. //
  1479. // and
  1480. //
  1481. // Type existingItem;
  1482. // for ( existingItem in expression ) { statements }
  1483. //
  1484. // becomes:
  1485. //
  1486. // the same with newVariable replaced with existingItem; the binding works
  1487. // the same except that for one ObjCForCollectionStmt::getElement() returns
  1488. // a DeclStmt and the other returns a DeclRefExpr.
  1489. //
  1490. CFGBlock *LoopSuccessor = 0;
  1491. if (Block) {
  1492. if (badCFG)
  1493. return 0;
  1494. LoopSuccessor = Block;
  1495. Block = 0;
  1496. } else
  1497. LoopSuccessor = Succ;
  1498. // Build the condition blocks.
  1499. CFGBlock *ExitConditionBlock = createBlock(false);
  1500. // Set the terminator for the "exit" condition block.
  1501. ExitConditionBlock->setTerminator(S);
  1502. // The last statement in the block should be the ObjCForCollectionStmt, which
  1503. // performs the actual binding to 'element' and determines if there are any
  1504. // more items in the collection.
  1505. appendStmt(ExitConditionBlock, S);
  1506. Block = ExitConditionBlock;
  1507. // Walk the 'element' expression to see if there are any side-effects. We
  1508. // generate new blocks as necessary. We DON'T add the statement by default to
  1509. // the CFG unless it contains control-flow.
  1510. CFGBlock *EntryConditionBlock = Visit(S->getElement(),
  1511. AddStmtChoice::NotAlwaysAdd);
  1512. if (Block) {
  1513. if (badCFG)
  1514. return 0;
  1515. Block = 0;
  1516. }
  1517. // The condition block is the implicit successor for the loop body as well as
  1518. // any code above the loop.
  1519. Succ = EntryConditionBlock;
  1520. // Now create the true branch.
  1521. {
  1522. // Save the current values for Succ, continue and break targets.
  1523. SaveAndRestore<CFGBlock*> save_Succ(Succ);
  1524. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  1525. save_break(BreakJumpTarget);
  1526. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  1527. ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
  1528. CFGBlock *BodyBlock = addStmt(S->getBody());
  1529. if (!BodyBlock)
  1530. BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
  1531. else if (Block) {
  1532. if (badCFG)
  1533. return 0;
  1534. }
  1535. // This new body block is a successor to our "exit" condition block.
  1536. addSuccessor(ExitConditionBlock, BodyBlock);
  1537. }
  1538. // Link up the condition block with the code that follows the loop.
  1539. // (the false branch).
  1540. addSuccessor(ExitConditionBlock, LoopSuccessor);
  1541. // Now create a prologue block to contain the collection expression.
  1542. Block = createBlock();
  1543. return addStmt(S->getCollection());
  1544. }
  1545. CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  1546. // FIXME: Add locking 'primitives' to CFG for @synchronized.
  1547. // Inline the body.
  1548. CFGBlock *SyncBlock = addStmt(S->getSynchBody());
  1549. // The sync body starts its own basic block. This makes it a little easier
  1550. // for diagnostic clients.
  1551. if (SyncBlock) {
  1552. if (badCFG)
  1553. return 0;
  1554. Block = 0;
  1555. Succ = SyncBlock;
  1556. }
  1557. // Add the @synchronized to the CFG.
  1558. autoCreateBlock();
  1559. appendStmt(Block, S);
  1560. // Inline the sync expression.
  1561. return addStmt(S->getSynchExpr());
  1562. }
  1563. CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
  1564. // FIXME
  1565. return NYS();
  1566. }
  1567. CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
  1568. CFGBlock *LoopSuccessor = NULL;
  1569. // Save local scope position because in case of condition variable ScopePos
  1570. // won't be restored when traversing AST.
  1571. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  1572. // Create local scope for possible condition variable.
  1573. // Store scope position for continue statement.
  1574. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  1575. if (VarDecl *VD = W->getConditionVariable()) {
  1576. addLocalScopeForVarDecl(VD);
  1577. addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
  1578. }
  1579. // "while" is a control-flow statement. Thus we stop processing the current
  1580. // block.
  1581. if (Block) {
  1582. if (badCFG)
  1583. return 0;
  1584. LoopSuccessor = Block;
  1585. Block = 0;
  1586. } else
  1587. LoopSuccessor = Succ;
  1588. // Because of short-circuit evaluation, the condition of the loop can span
  1589. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  1590. // evaluate the condition.
  1591. CFGBlock *ExitConditionBlock = createBlock(false);
  1592. CFGBlock *EntryConditionBlock = ExitConditionBlock;
  1593. // Set the terminator for the "exit" condition block.
  1594. ExitConditionBlock->setTerminator(W);
  1595. // Now add the actual condition to the condition block. Because the condition
  1596. // itself may contain control-flow, new blocks may be created. Thus we update
  1597. // "Succ" after adding the condition.
  1598. if (Stmt *C = W->getCond()) {
  1599. Block = ExitConditionBlock;
  1600. EntryConditionBlock = addStmt(C);
  1601. // The condition might finish the current 'Block'.
  1602. Block = EntryConditionBlock;
  1603. // If this block contains a condition variable, add both the condition
  1604. // variable and initializer to the CFG.
  1605. if (VarDecl *VD = W->getConditionVariable()) {
  1606. if (Expr *Init = VD->getInit()) {
  1607. autoCreateBlock();
  1608. appendStmt(Block, W->getConditionVariableDeclStmt());
  1609. EntryConditionBlock = addStmt(Init);
  1610. assert(Block == EntryConditionBlock);
  1611. }
  1612. }
  1613. if (Block) {
  1614. if (badCFG)
  1615. return 0;
  1616. }
  1617. }
  1618. // The condition block is the implicit successor for the loop body as well as
  1619. // any code above the loop.
  1620. Succ = EntryConditionBlock;
  1621. // See if this is a known constant.
  1622. const TryResult& KnownVal = tryEvaluateBool(W->getCond());
  1623. // Process the loop body.
  1624. {
  1625. assert(W->getBody());
  1626. // Save the current values for Block, Succ, and continue and break targets
  1627. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  1628. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  1629. save_break(BreakJumpTarget);
  1630. // Create an empty block to represent the transition block for looping back
  1631. // to the head of the loop.
  1632. Block = 0;
  1633. assert(Succ == EntryConditionBlock);
  1634. Succ = createBlock();
  1635. Succ->setLoopTarget(W);
  1636. ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
  1637. // All breaks should go to the code following the loop.
  1638. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  1639. // NULL out Block to force lazy instantiation of blocks for the body.
  1640. Block = NULL;
  1641. // Loop body should end with destructor of Condition variable (if any).
  1642. addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
  1643. // If body is not a compound statement create implicit scope
  1644. // and add destructors.
  1645. if (!isa<CompoundStmt>(W->getBody()))
  1646. addLocalScopeAndDtors(W->getBody());
  1647. // Create the body. The returned block is the entry to the loop body.
  1648. CFGBlock *BodyBlock = addStmt(W->getBody());
  1649. if (!BodyBlock)
  1650. BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
  1651. else if (Block) {
  1652. if (badCFG)
  1653. return 0;
  1654. }
  1655. // Add the loop body entry as a successor to the condition.
  1656. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
  1657. }
  1658. // Link up the condition block with the code that follows the loop. (the
  1659. // false branch).
  1660. addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
  1661. // There can be no more statements in the condition block since we loop back
  1662. // to this block. NULL out Block to force lazy creation of another block.
  1663. Block = NULL;
  1664. // Return the condition block, which is the dominating block for the loop.
  1665. Succ = EntryConditionBlock;
  1666. return EntryConditionBlock;
  1667. }
  1668. CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
  1669. // FIXME: For now we pretend that @catch and the code it contains does not
  1670. // exit.
  1671. return Block;
  1672. }
  1673. CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
  1674. // FIXME: This isn't complete. We basically treat @throw like a return
  1675. // statement.
  1676. // If we were in the middle of a block we stop processing that block.
  1677. if (badCFG)
  1678. return 0;
  1679. // Create the new block.
  1680. Block = createBlock(false);
  1681. // The Exit block is the only successor.
  1682. addSuccessor(Block, &cfg->getExit());
  1683. // Add the statement to the block. This may create new blocks if S contains
  1684. // control-flow (short-circuit operations).
  1685. return VisitStmt(S, AddStmtChoice::AlwaysAdd);
  1686. }
  1687. CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
  1688. // If we were in the middle of a block we stop processing that block.
  1689. if (badCFG)
  1690. return 0;
  1691. // Create the new block.
  1692. Block = createBlock(false);
  1693. if (TryTerminatedBlock)
  1694. // The current try statement is the only successor.
  1695. addSuccessor(Block, TryTerminatedBlock);
  1696. else
  1697. // otherwise the Exit block is the only successor.
  1698. addSuccessor(Block, &cfg->getExit());
  1699. // Add the statement to the block. This may create new blocks if S contains
  1700. // control-flow (short-circuit operations).
  1701. return VisitStmt(T, AddStmtChoice::AlwaysAdd);
  1702. }
  1703. CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
  1704. CFGBlock *LoopSuccessor = NULL;
  1705. // "do...while" is a control-flow statement. Thus we stop processing the
  1706. // current block.
  1707. if (Block) {
  1708. if (badCFG)
  1709. return 0;
  1710. LoopSuccessor = Block;
  1711. } else
  1712. LoopSuccessor = Succ;
  1713. // Because of short-circuit evaluation, the condition of the loop can span
  1714. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  1715. // evaluate the condition.
  1716. CFGBlock *ExitConditionBlock = createBlock(false);
  1717. CFGBlock *EntryConditionBlock = ExitConditionBlock;
  1718. // Set the terminator for the "exit" condition block.
  1719. ExitConditionBlock->setTerminator(D);
  1720. // Now add the actual condition to the condition block. Because the condition
  1721. // itself may contain control-flow, new blocks may be created.
  1722. if (Stmt *C = D->getCond()) {
  1723. Block = ExitConditionBlock;
  1724. EntryConditionBlock = addStmt(C);
  1725. if (Block) {
  1726. if (badCFG)
  1727. return 0;
  1728. }
  1729. }
  1730. // The condition block is the implicit successor for the loop body.
  1731. Succ = EntryConditionBlock;
  1732. // See if this is a known constant.
  1733. const TryResult &KnownVal = tryEvaluateBool(D->getCond());
  1734. // Process the loop body.
  1735. CFGBlock *BodyBlock = NULL;
  1736. {
  1737. assert(D->getBody());
  1738. // Save the current values for Block, Succ, and continue and break targets
  1739. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  1740. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
  1741. save_break(BreakJumpTarget);
  1742. // All continues within this loop should go to the condition block
  1743. ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
  1744. // All breaks should go to the code following the loop.
  1745. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  1746. // NULL out Block to force lazy instantiation of blocks for the body.
  1747. Block = NULL;
  1748. // If body is not a compound statement create implicit scope
  1749. // and add destructors.
  1750. if (!isa<CompoundStmt>(D->getBody()))
  1751. addLocalScopeAndDtors(D->getBody());
  1752. // Create the body. The returned block is the entry to the loop body.
  1753. BodyBlock = addStmt(D->getBody());
  1754. if (!BodyBlock)
  1755. BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
  1756. else if (Block) {
  1757. if (badCFG)
  1758. return 0;
  1759. }
  1760. if (!KnownVal.isFalse()) {
  1761. // Add an intermediate block between the BodyBlock and the
  1762. // ExitConditionBlock to represent the "loop back" transition. Create an
  1763. // empty block to represent the transition block for looping back to the
  1764. // head of the loop.
  1765. // FIXME: Can we do this more efficiently without adding another block?
  1766. Block = NULL;
  1767. Succ = BodyBlock;
  1768. CFGBlock *LoopBackBlock = createBlock();
  1769. LoopBackBlock->setLoopTarget(D);
  1770. // Add the loop body entry as a successor to the condition.
  1771. addSuccessor(ExitConditionBlock, LoopBackBlock);
  1772. }
  1773. else
  1774. addSuccessor(ExitConditionBlock, NULL);
  1775. }
  1776. // Link up the condition block with the code that follows the loop.
  1777. // (the false branch).
  1778. addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
  1779. // There can be no more statements in the body block(s) since we loop back to
  1780. // the body. NULL out Block to force lazy creation of another block.
  1781. Block = NULL;
  1782. // Return the loop body, which is the dominating block for the loop.
  1783. Succ = BodyBlock;
  1784. return BodyBlock;
  1785. }
  1786. CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
  1787. // "continue" is a control-flow statement. Thus we stop processing the
  1788. // current block.
  1789. if (badCFG)
  1790. return 0;
  1791. // Now create a new block that ends with the continue statement.
  1792. Block = createBlock(false);
  1793. Block->setTerminator(C);
  1794. // If there is no target for the continue, then we are looking at an
  1795. // incomplete AST. This means the CFG cannot be constructed.
  1796. if (ContinueJumpTarget.block) {
  1797. addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
  1798. addSuccessor(Block, ContinueJumpTarget.block);
  1799. } else
  1800. badCFG = true;
  1801. return Block;
  1802. }
  1803. CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  1804. AddStmtChoice asc) {
  1805. if (asc.alwaysAdd(*this, E)) {
  1806. autoCreateBlock();
  1807. appendStmt(Block, E);
  1808. }
  1809. // VLA types have expressions that must be evaluated.
  1810. CFGBlock *lastBlock = Block;
  1811. if (E->isArgumentType()) {
  1812. for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
  1813. VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
  1814. lastBlock = addStmt(VA->getSizeExpr());
  1815. }
  1816. return lastBlock;
  1817. }
  1818. /// VisitStmtExpr - Utility method to handle (nested) statement
  1819. /// expressions (a GCC extension).
  1820. CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
  1821. if (asc.alwaysAdd(*this, SE)) {
  1822. autoCreateBlock();
  1823. appendStmt(Block, SE);
  1824. }
  1825. return VisitCompoundStmt(SE->getSubStmt());
  1826. }
  1827. CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
  1828. // "switch" is a control-flow statement. Thus we stop processing the current
  1829. // block.
  1830. CFGBlock *SwitchSuccessor = NULL;
  1831. // Save local scope position because in case of condition variable ScopePos
  1832. // won't be restored when traversing AST.
  1833. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  1834. // Create local scope for possible condition variable.
  1835. // Store scope position. Add implicit destructor.
  1836. if (VarDecl *VD = Terminator->getConditionVariable()) {
  1837. LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
  1838. addLocalScopeForVarDecl(VD);
  1839. addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
  1840. }
  1841. if (Block) {
  1842. if (badCFG)
  1843. return 0;
  1844. SwitchSuccessor = Block;
  1845. } else SwitchSuccessor = Succ;
  1846. // Save the current "switch" context.
  1847. SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
  1848. save_default(DefaultCaseBlock);
  1849. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  1850. // Set the "default" case to be the block after the switch statement. If the
  1851. // switch statement contains a "default:", this value will be overwritten with
  1852. // the block for that code.
  1853. DefaultCaseBlock = SwitchSuccessor;
  1854. // Create a new block that will contain the switch statement.
  1855. SwitchTerminatedBlock = createBlock(false);
  1856. // Now process the switch body. The code after the switch is the implicit
  1857. // successor.
  1858. Succ = SwitchSuccessor;
  1859. BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
  1860. // When visiting the body, the case statements should automatically get linked
  1861. // up to the switch. We also don't keep a pointer to the body, since all
  1862. // control-flow from the switch goes to case/default statements.
  1863. assert(Terminator->getBody() && "switch must contain a non-NULL body");
  1864. Block = NULL;
  1865. // For pruning unreachable case statements, save the current state
  1866. // for tracking the condition value.
  1867. SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
  1868. false);
  1869. // Determine if the switch condition can be explicitly evaluated.
  1870. assert(Terminator->getCond() && "switch condition must be non-NULL");
  1871. Expr::EvalResult result;
  1872. bool b = tryEvaluate(Terminator->getCond(), result);
  1873. SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
  1874. b ? &result : 0);
  1875. // If body is not a compound statement create implicit scope
  1876. // and add destructors.
  1877. if (!isa<CompoundStmt>(Terminator->getBody()))
  1878. addLocalScopeAndDtors(Terminator->getBody());
  1879. addStmt(Terminator->getBody());
  1880. if (Block) {
  1881. if (badCFG)
  1882. return 0;
  1883. }
  1884. // If we have no "default:" case, the default transition is to the code
  1885. // following the switch body. Moreover, take into account if all the
  1886. // cases of a switch are covered (e.g., switching on an enum value).
  1887. addSuccessor(SwitchTerminatedBlock,
  1888. switchExclusivelyCovered || Terminator->isAllEnumCasesCovered()
  1889. ? 0 : DefaultCaseBlock);
  1890. // Add the terminator and condition in the switch block.
  1891. SwitchTerminatedBlock->setTerminator(Terminator);
  1892. Block = SwitchTerminatedBlock;
  1893. Block = addStmt(Terminator->getCond());
  1894. // Finally, if the SwitchStmt contains a condition variable, add both the
  1895. // SwitchStmt and the condition variable initialization to the CFG.
  1896. if (VarDecl *VD = Terminator->getConditionVariable()) {
  1897. if (Expr *Init = VD->getInit()) {
  1898. autoCreateBlock();
  1899. appendStmt(Block, Terminator->getConditionVariableDeclStmt());
  1900. addStmt(Init);
  1901. }
  1902. }
  1903. return Block;
  1904. }
  1905. static bool shouldAddCase(bool &switchExclusivelyCovered,
  1906. const Expr::EvalResult *switchCond,
  1907. const CaseStmt *CS,
  1908. ASTContext &Ctx) {
  1909. if (!switchCond)
  1910. return true;
  1911. bool addCase = false;
  1912. if (!switchExclusivelyCovered) {
  1913. if (switchCond->Val.isInt()) {
  1914. // Evaluate the LHS of the case value.
  1915. Expr::EvalResult V1;
  1916. CS->getLHS()->Evaluate(V1, Ctx);
  1917. assert(V1.Val.isInt());
  1918. const llvm::APSInt &condInt = switchCond->Val.getInt();
  1919. const llvm::APSInt &lhsInt = V1.Val.getInt();
  1920. if (condInt == lhsInt) {
  1921. addCase = true;
  1922. switchExclusivelyCovered = true;
  1923. }
  1924. else if (condInt < lhsInt) {
  1925. if (const Expr *RHS = CS->getRHS()) {
  1926. // Evaluate the RHS of the case value.
  1927. Expr::EvalResult V2;
  1928. RHS->Evaluate(V2, Ctx);
  1929. assert(V2.Val.isInt());
  1930. if (V2.Val.getInt() <= condInt) {
  1931. addCase = true;
  1932. switchExclusivelyCovered = true;
  1933. }
  1934. }
  1935. }
  1936. }
  1937. else
  1938. addCase = true;
  1939. }
  1940. return addCase;
  1941. }
  1942. CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
  1943. // CaseStmts are essentially labels, so they are the first statement in a
  1944. // block.
  1945. CFGBlock *TopBlock = 0, *LastBlock = 0;
  1946. if (Stmt *Sub = CS->getSubStmt()) {
  1947. // For deeply nested chains of CaseStmts, instead of doing a recursion
  1948. // (which can blow out the stack), manually unroll and create blocks
  1949. // along the way.
  1950. while (isa<CaseStmt>(Sub)) {
  1951. CFGBlock *currentBlock = createBlock(false);
  1952. currentBlock->setLabel(CS);
  1953. if (TopBlock)
  1954. addSuccessor(LastBlock, currentBlock);
  1955. else
  1956. TopBlock = currentBlock;
  1957. addSuccessor(SwitchTerminatedBlock,
  1958. shouldAddCase(switchExclusivelyCovered, switchCond,
  1959. CS, *Context)
  1960. ? currentBlock : 0);
  1961. LastBlock = currentBlock;
  1962. CS = cast<CaseStmt>(Sub);
  1963. Sub = CS->getSubStmt();
  1964. }
  1965. addStmt(Sub);
  1966. }
  1967. CFGBlock *CaseBlock = Block;
  1968. if (!CaseBlock)
  1969. CaseBlock = createBlock();
  1970. // Cases statements partition blocks, so this is the top of the basic block we
  1971. // were processing (the "case XXX:" is the label).
  1972. CaseBlock->setLabel(CS);
  1973. if (badCFG)
  1974. return 0;
  1975. // Add this block to the list of successors for the block with the switch
  1976. // statement.
  1977. assert(SwitchTerminatedBlock);
  1978. addSuccessor(SwitchTerminatedBlock,
  1979. shouldAddCase(switchExclusivelyCovered, switchCond,
  1980. CS, *Context)
  1981. ? CaseBlock : 0);
  1982. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  1983. Block = NULL;
  1984. if (TopBlock) {
  1985. addSuccessor(LastBlock, CaseBlock);
  1986. Succ = TopBlock;
  1987. } else {
  1988. // This block is now the implicit successor of other blocks.
  1989. Succ = CaseBlock;
  1990. }
  1991. return Succ;
  1992. }
  1993. CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
  1994. if (Terminator->getSubStmt())
  1995. addStmt(Terminator->getSubStmt());
  1996. DefaultCaseBlock = Block;
  1997. if (!DefaultCaseBlock)
  1998. DefaultCaseBlock = createBlock();
  1999. // Default statements partition blocks, so this is the top of the basic block
  2000. // we were processing (the "default:" is the label).
  2001. DefaultCaseBlock->setLabel(Terminator);
  2002. if (badCFG)
  2003. return 0;
  2004. // Unlike case statements, we don't add the default block to the successors
  2005. // for the switch statement immediately. This is done when we finish
  2006. // processing the switch statement. This allows for the default case
  2007. // (including a fall-through to the code after the switch statement) to always
  2008. // be the last successor of a switch-terminated block.
  2009. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  2010. Block = NULL;
  2011. // This block is now the implicit successor of other blocks.
  2012. Succ = DefaultCaseBlock;
  2013. return DefaultCaseBlock;
  2014. }
  2015. CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
  2016. // "try"/"catch" is a control-flow statement. Thus we stop processing the
  2017. // current block.
  2018. CFGBlock *TrySuccessor = NULL;
  2019. if (Block) {
  2020. if (badCFG)
  2021. return 0;
  2022. TrySuccessor = Block;
  2023. } else TrySuccessor = Succ;
  2024. CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
  2025. // Create a new block that will contain the try statement.
  2026. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  2027. // Add the terminator in the try block.
  2028. NewTryTerminatedBlock->setTerminator(Terminator);
  2029. bool HasCatchAll = false;
  2030. for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
  2031. // The code after the try is the implicit successor.
  2032. Succ = TrySuccessor;
  2033. CXXCatchStmt *CS = Terminator->getHandler(h);
  2034. if (CS->getExceptionDecl() == 0) {
  2035. HasCatchAll = true;
  2036. }
  2037. Block = NULL;
  2038. CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
  2039. if (CatchBlock == 0)
  2040. return 0;
  2041. // Add this block to the list of successors for the block with the try
  2042. // statement.
  2043. addSuccessor(NewTryTerminatedBlock, CatchBlock);
  2044. }
  2045. if (!HasCatchAll) {
  2046. if (PrevTryTerminatedBlock)
  2047. addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
  2048. else
  2049. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  2050. }
  2051. // The code after the try is the implicit successor.
  2052. Succ = TrySuccessor;
  2053. // Save the current "try" context.
  2054. SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
  2055. cfg->addTryDispatchBlock(TryTerminatedBlock);
  2056. assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
  2057. Block = NULL;
  2058. Block = addStmt(Terminator->getTryBlock());
  2059. return Block;
  2060. }
  2061. CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
  2062. // CXXCatchStmt are treated like labels, so they are the first statement in a
  2063. // block.
  2064. // Save local scope position because in case of exception variable ScopePos
  2065. // won't be restored when traversing AST.
  2066. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2067. // Create local scope for possible exception variable.
  2068. // Store scope position. Add implicit destructor.
  2069. if (VarDecl *VD = CS->getExceptionDecl()) {
  2070. LocalScope::const_iterator BeginScopePos = ScopePos;
  2071. addLocalScopeForVarDecl(VD);
  2072. addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
  2073. }
  2074. if (CS->getHandlerBlock())
  2075. addStmt(CS->getHandlerBlock());
  2076. CFGBlock *CatchBlock = Block;
  2077. if (!CatchBlock)
  2078. CatchBlock = createBlock();
  2079. CatchBlock->setLabel(CS);
  2080. if (badCFG)
  2081. return 0;
  2082. // We set Block to NULL to allow lazy creation of a new block (if necessary)
  2083. Block = NULL;
  2084. return CatchBlock;
  2085. }
  2086. CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
  2087. // C++0x for-range statements are specified as [stmt.ranged]:
  2088. //
  2089. // {
  2090. // auto && __range = range-init;
  2091. // for ( auto __begin = begin-expr,
  2092. // __end = end-expr;
  2093. // __begin != __end;
  2094. // ++__begin ) {
  2095. // for-range-declaration = *__begin;
  2096. // statement
  2097. // }
  2098. // }
  2099. // Save local scope position before the addition of the implicit variables.
  2100. SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
  2101. // Create local scopes and destructors for range, begin and end variables.
  2102. if (Stmt *Range = S->getRangeStmt())
  2103. addLocalScopeForStmt(Range);
  2104. if (Stmt *BeginEnd = S->getBeginEndStmt())
  2105. addLocalScopeForStmt(BeginEnd);
  2106. addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
  2107. LocalScope::const_iterator ContinueScopePos = ScopePos;
  2108. // "for" is a control-flow statement. Thus we stop processing the current
  2109. // block.
  2110. CFGBlock *LoopSuccessor = NULL;
  2111. if (Block) {
  2112. if (badCFG)
  2113. return 0;
  2114. LoopSuccessor = Block;
  2115. } else
  2116. LoopSuccessor = Succ;
  2117. // Save the current value for the break targets.
  2118. // All breaks should go to the code following the loop.
  2119. SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
  2120. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2121. // The block for the __begin != __end expression.
  2122. CFGBlock *ConditionBlock = createBlock(false);
  2123. ConditionBlock->setTerminator(S);
  2124. // Now add the actual condition to the condition block.
  2125. if (Expr *C = S->getCond()) {
  2126. Block = ConditionBlock;
  2127. CFGBlock *BeginConditionBlock = addStmt(C);
  2128. if (badCFG)
  2129. return 0;
  2130. assert(BeginConditionBlock == ConditionBlock &&
  2131. "condition block in for-range was unexpectedly complex");
  2132. (void)BeginConditionBlock;
  2133. }
  2134. // The condition block is the implicit successor for the loop body as well as
  2135. // any code above the loop.
  2136. Succ = ConditionBlock;
  2137. // See if this is a known constant.
  2138. TryResult KnownVal(true);
  2139. if (S->getCond())
  2140. KnownVal = tryEvaluateBool(S->getCond());
  2141. // Now create the loop body.
  2142. {
  2143. assert(S->getBody());
  2144. // Save the current values for Block, Succ, and continue targets.
  2145. SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
  2146. SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
  2147. // Generate increment code in its own basic block. This is the target of
  2148. // continue statements.
  2149. Block = 0;
  2150. Succ = addStmt(S->getInc());
  2151. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  2152. // The starting block for the loop increment is the block that should
  2153. // represent the 'loop target' for looping back to the start of the loop.
  2154. ContinueJumpTarget.block->setLoopTarget(S);
  2155. // Finish up the increment block and prepare to start the loop body.
  2156. assert(Block);
  2157. if (badCFG)
  2158. return 0;
  2159. Block = 0;
  2160. // Add implicit scope and dtors for loop variable.
  2161. addLocalScopeAndDtors(S->getLoopVarStmt());
  2162. // Populate a new block to contain the loop body and loop variable.
  2163. Block = addStmt(S->getBody());
  2164. if (badCFG)
  2165. return 0;
  2166. Block = addStmt(S->getLoopVarStmt());
  2167. if (badCFG)
  2168. return 0;
  2169. // This new body block is a successor to our condition block.
  2170. addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : Block);
  2171. }
  2172. // Link up the condition block with the code that follows the loop (the
  2173. // false branch).
  2174. addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor);
  2175. // Add the initialization statements.
  2176. Block = createBlock();
  2177. addStmt(S->getBeginEndStmt());
  2178. return addStmt(S->getRangeStmt());
  2179. }
  2180. CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
  2181. AddStmtChoice asc) {
  2182. if (BuildOpts.AddImplicitDtors) {
  2183. // If adding implicit destructors visit the full expression for adding
  2184. // destructors of temporaries.
  2185. VisitForTemporaryDtors(E->getSubExpr());
  2186. // Full expression has to be added as CFGStmt so it will be sequenced
  2187. // before destructors of it's temporaries.
  2188. asc = asc.withAlwaysAdd(true);
  2189. }
  2190. return Visit(E->getSubExpr(), asc);
  2191. }
  2192. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  2193. AddStmtChoice asc) {
  2194. if (asc.alwaysAdd(*this, E)) {
  2195. autoCreateBlock();
  2196. appendStmt(Block, E);
  2197. // We do not want to propagate the AlwaysAdd property.
  2198. asc = asc.withAlwaysAdd(false);
  2199. }
  2200. return Visit(E->getSubExpr(), asc);
  2201. }
  2202. CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
  2203. AddStmtChoice asc) {
  2204. autoCreateBlock();
  2205. if (!C->isElidable())
  2206. appendStmt(Block, C);
  2207. return VisitChildren(C);
  2208. }
  2209. CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  2210. AddStmtChoice asc) {
  2211. if (asc.alwaysAdd(*this, E)) {
  2212. autoCreateBlock();
  2213. appendStmt(Block, E);
  2214. // We do not want to propagate the AlwaysAdd property.
  2215. asc = asc.withAlwaysAdd(false);
  2216. }
  2217. return Visit(E->getSubExpr(), asc);
  2218. }
  2219. CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  2220. AddStmtChoice asc) {
  2221. autoCreateBlock();
  2222. appendStmt(Block, C);
  2223. return VisitChildren(C);
  2224. }
  2225. CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
  2226. AddStmtChoice asc) {
  2227. if (asc.alwaysAdd(*this, E)) {
  2228. autoCreateBlock();
  2229. appendStmt(Block, E);
  2230. }
  2231. return Visit(E->getSubExpr(), AddStmtChoice());
  2232. }
  2233. CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  2234. // Lazily create the indirect-goto dispatch block if there isn't one already.
  2235. CFGBlock *IBlock = cfg->getIndirectGotoBlock();
  2236. if (!IBlock) {
  2237. IBlock = createBlock(false);
  2238. cfg->setIndirectGotoBlock(IBlock);
  2239. }
  2240. // IndirectGoto is a control-flow statement. Thus we stop processing the
  2241. // current block and create a new one.
  2242. if (badCFG)
  2243. return 0;
  2244. Block = createBlock(false);
  2245. Block->setTerminator(I);
  2246. addSuccessor(Block, IBlock);
  2247. return addStmt(I->getTarget());
  2248. }
  2249. CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) {
  2250. tryAgain:
  2251. if (!E) {
  2252. badCFG = true;
  2253. return NULL;
  2254. }
  2255. switch (E->getStmtClass()) {
  2256. default:
  2257. return VisitChildrenForTemporaryDtors(E);
  2258. case Stmt::BinaryOperatorClass:
  2259. return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E));
  2260. case Stmt::CXXBindTemporaryExprClass:
  2261. return VisitCXXBindTemporaryExprForTemporaryDtors(
  2262. cast<CXXBindTemporaryExpr>(E), BindToTemporary);
  2263. case Stmt::BinaryConditionalOperatorClass:
  2264. case Stmt::ConditionalOperatorClass:
  2265. return VisitConditionalOperatorForTemporaryDtors(
  2266. cast<AbstractConditionalOperator>(E), BindToTemporary);
  2267. case Stmt::ImplicitCastExprClass:
  2268. // For implicit cast we want BindToTemporary to be passed further.
  2269. E = cast<CastExpr>(E)->getSubExpr();
  2270. goto tryAgain;
  2271. case Stmt::ParenExprClass:
  2272. E = cast<ParenExpr>(E)->getSubExpr();
  2273. goto tryAgain;
  2274. case Stmt::MaterializeTemporaryExprClass:
  2275. E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr();
  2276. goto tryAgain;
  2277. }
  2278. }
  2279. CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) {
  2280. // When visiting children for destructors we want to visit them in reverse
  2281. // order. Because there's no reverse iterator for children must to reverse
  2282. // them in helper vector.
  2283. typedef SmallVector<Stmt *, 4> ChildrenVect;
  2284. ChildrenVect ChildrenRev;
  2285. for (Stmt::child_range I = E->children(); I; ++I) {
  2286. if (*I) ChildrenRev.push_back(*I);
  2287. }
  2288. CFGBlock *B = Block;
  2289. for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(),
  2290. L = ChildrenRev.rend(); I != L; ++I) {
  2291. if (CFGBlock *R = VisitForTemporaryDtors(*I))
  2292. B = R;
  2293. }
  2294. return B;
  2295. }
  2296. CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) {
  2297. if (E->isLogicalOp()) {
  2298. // Destructors for temporaries in LHS expression should be called after
  2299. // those for RHS expression. Even if this will unnecessarily create a block,
  2300. // this block will be used at least by the full expression.
  2301. autoCreateBlock();
  2302. CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS());
  2303. if (badCFG)
  2304. return NULL;
  2305. Succ = ConfluenceBlock;
  2306. Block = NULL;
  2307. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
  2308. if (RHSBlock) {
  2309. if (badCFG)
  2310. return NULL;
  2311. // If RHS expression did produce destructors we need to connect created
  2312. // blocks to CFG in same manner as for binary operator itself.
  2313. CFGBlock *LHSBlock = createBlock(false);
  2314. LHSBlock->setTerminator(CFGTerminator(E, true));
  2315. // For binary operator LHS block is before RHS in list of predecessors
  2316. // of ConfluenceBlock.
  2317. std::reverse(ConfluenceBlock->pred_begin(),
  2318. ConfluenceBlock->pred_end());
  2319. // See if this is a known constant.
  2320. TryResult KnownVal = tryEvaluateBool(E->getLHS());
  2321. if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr))
  2322. KnownVal.negate();
  2323. // Link LHSBlock with RHSBlock exactly the same way as for binary operator
  2324. // itself.
  2325. if (E->getOpcode() == BO_LOr) {
  2326. addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
  2327. addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
  2328. } else {
  2329. assert (E->getOpcode() == BO_LAnd);
  2330. addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
  2331. addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
  2332. }
  2333. Block = LHSBlock;
  2334. return LHSBlock;
  2335. }
  2336. Block = ConfluenceBlock;
  2337. return ConfluenceBlock;
  2338. }
  2339. if (E->isAssignmentOp()) {
  2340. // For assignment operator (=) LHS expression is visited
  2341. // before RHS expression. For destructors visit them in reverse order.
  2342. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
  2343. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
  2344. return LHSBlock ? LHSBlock : RHSBlock;
  2345. }
  2346. // For any other binary operator RHS expression is visited before
  2347. // LHS expression (order of children). For destructors visit them in reverse
  2348. // order.
  2349. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
  2350. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
  2351. return RHSBlock ? RHSBlock : LHSBlock;
  2352. }
  2353. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
  2354. CXXBindTemporaryExpr *E, bool BindToTemporary) {
  2355. // First add destructors for temporaries in subexpression.
  2356. CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr());
  2357. if (!BindToTemporary) {
  2358. // If lifetime of temporary is not prolonged (by assigning to constant
  2359. // reference) add destructor for it.
  2360. // If the destructor is marked as a no-return destructor, we need to create
  2361. // a new block for the destructor which does not have as a successor
  2362. // anything built thus far. Control won't flow out of this block.
  2363. const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
  2364. if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) {
  2365. Block = createBlock(/*add_successor=*/false);
  2366. // Wire up this block directly to the exit block if we're in the
  2367. // no-return case. We pruned any other successors because control flow
  2368. // won't actually exit this block, but we want to be able to find all of
  2369. // these entries in the CFG when doing analyses.
  2370. addSuccessor(Block, &cfg->getExit());
  2371. } else {
  2372. autoCreateBlock();
  2373. }
  2374. appendTemporaryDtor(Block, E);
  2375. B = Block;
  2376. }
  2377. return B;
  2378. }
  2379. CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
  2380. AbstractConditionalOperator *E, bool BindToTemporary) {
  2381. // First add destructors for condition expression. Even if this will
  2382. // unnecessarily create a block, this block will be used at least by the full
  2383. // expression.
  2384. autoCreateBlock();
  2385. CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond());
  2386. if (badCFG)
  2387. return NULL;
  2388. if (BinaryConditionalOperator *BCO
  2389. = dyn_cast<BinaryConditionalOperator>(E)) {
  2390. ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon());
  2391. if (badCFG)
  2392. return NULL;
  2393. }
  2394. // Try to add block with destructors for LHS expression.
  2395. CFGBlock *LHSBlock = NULL;
  2396. Succ = ConfluenceBlock;
  2397. Block = NULL;
  2398. LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary);
  2399. if (badCFG)
  2400. return NULL;
  2401. // Try to add block with destructors for RHS expression;
  2402. Succ = ConfluenceBlock;
  2403. Block = NULL;
  2404. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(),
  2405. BindToTemporary);
  2406. if (badCFG)
  2407. return NULL;
  2408. if (!RHSBlock && !LHSBlock) {
  2409. // If neither LHS nor RHS expression had temporaries to destroy don't create
  2410. // more blocks.
  2411. Block = ConfluenceBlock;
  2412. return Block;
  2413. }
  2414. Block = createBlock(false);
  2415. Block->setTerminator(CFGTerminator(E, true));
  2416. // See if this is a known constant.
  2417. const TryResult &KnownVal = tryEvaluateBool(E->getCond());
  2418. if (LHSBlock) {
  2419. addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
  2420. } else if (KnownVal.isFalse()) {
  2421. addSuccessor(Block, NULL);
  2422. } else {
  2423. addSuccessor(Block, ConfluenceBlock);
  2424. std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end());
  2425. }
  2426. if (!RHSBlock)
  2427. RHSBlock = ConfluenceBlock;
  2428. addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
  2429. return Block;
  2430. }
  2431. } // end anonymous namespace
  2432. /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
  2433. /// no successors or predecessors. If this is the first block created in the
  2434. /// CFG, it is automatically set to be the Entry and Exit of the CFG.
  2435. CFGBlock *CFG::createBlock() {
  2436. bool first_block = begin() == end();
  2437. // Create the block.
  2438. CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
  2439. new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
  2440. Blocks.push_back(Mem, BlkBVC);
  2441. // If this is the first block, set it as the Entry and Exit.
  2442. if (first_block)
  2443. Entry = Exit = &back();
  2444. // Return the block.
  2445. return &back();
  2446. }
  2447. /// buildCFG - Constructs a CFG from an AST. Ownership of the returned
  2448. /// CFG is returned to the caller.
  2449. CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
  2450. const BuildOptions &BO) {
  2451. CFGBuilder Builder(C, BO);
  2452. return Builder.buildCFG(D, Statement);
  2453. }
  2454. const CXXDestructorDecl *
  2455. CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
  2456. switch (getKind()) {
  2457. case CFGElement::Invalid:
  2458. case CFGElement::Statement:
  2459. case CFGElement::Initializer:
  2460. llvm_unreachable("getDestructorDecl should only be used with "
  2461. "ImplicitDtors");
  2462. case CFGElement::AutomaticObjectDtor: {
  2463. const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl();
  2464. QualType ty = var->getType();
  2465. ty = ty.getNonReferenceType();
  2466. if (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
  2467. ty = arrayType->getElementType();
  2468. }
  2469. const RecordType *recordType = ty->getAs<RecordType>();
  2470. const CXXRecordDecl *classDecl =
  2471. cast<CXXRecordDecl>(recordType->getDecl());
  2472. return classDecl->getDestructor();
  2473. }
  2474. case CFGElement::TemporaryDtor: {
  2475. const CXXBindTemporaryExpr *bindExpr =
  2476. cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr();
  2477. const CXXTemporary *temp = bindExpr->getTemporary();
  2478. return temp->getDestructor();
  2479. }
  2480. case CFGElement::BaseDtor:
  2481. case CFGElement::MemberDtor:
  2482. // Not yet supported.
  2483. return 0;
  2484. }
  2485. llvm_unreachable("getKind() returned bogus value");
  2486. return 0;
  2487. }
  2488. bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
  2489. if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) {
  2490. QualType ty = cdecl->getType();
  2491. return cast<FunctionType>(ty)->getNoReturnAttr();
  2492. }
  2493. return false;
  2494. }
  2495. //===----------------------------------------------------------------------===//
  2496. // CFG: Queries for BlkExprs.
  2497. //===----------------------------------------------------------------------===//
  2498. namespace {
  2499. typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
  2500. }
  2501. static void FindSubExprAssignments(const Stmt *S,
  2502. llvm::SmallPtrSet<const Expr*,50>& Set) {
  2503. if (!S)
  2504. return;
  2505. for (Stmt::const_child_range I = S->children(); I; ++I) {
  2506. const Stmt *child = *I;
  2507. if (!child)
  2508. continue;
  2509. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(child))
  2510. if (B->isAssignmentOp()) Set.insert(B);
  2511. FindSubExprAssignments(child, Set);
  2512. }
  2513. }
  2514. static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
  2515. BlkExprMapTy* M = new BlkExprMapTy();
  2516. // Look for assignments that are used as subexpressions. These are the only
  2517. // assignments that we want to *possibly* register as a block-level
  2518. // expression. Basically, if an assignment occurs both in a subexpression and
  2519. // at the block-level, it is a block-level expression.
  2520. llvm::SmallPtrSet<const Expr*,50> SubExprAssignments;
  2521. for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
  2522. for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
  2523. if (const CFGStmt *S = BI->getAs<CFGStmt>())
  2524. FindSubExprAssignments(S->getStmt(), SubExprAssignments);
  2525. for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
  2526. // Iterate over the statements again on identify the Expr* and Stmt* at the
  2527. // block-level that are block-level expressions.
  2528. for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) {
  2529. const CFGStmt *CS = BI->getAs<CFGStmt>();
  2530. if (!CS)
  2531. continue;
  2532. if (const Expr *Exp = dyn_cast<Expr>(CS->getStmt())) {
  2533. assert((Exp->IgnoreParens() == Exp) && "No parens on block-level exps");
  2534. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
  2535. // Assignment expressions that are not nested within another
  2536. // expression are really "statements" whose value is never used by
  2537. // another expression.
  2538. if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
  2539. continue;
  2540. } else if (const StmtExpr *SE = dyn_cast<StmtExpr>(Exp)) {
  2541. // Special handling for statement expressions. The last statement in
  2542. // the statement expression is also a block-level expr.
  2543. const CompoundStmt *C = SE->getSubStmt();
  2544. if (!C->body_empty()) {
  2545. const Stmt *Last = C->body_back();
  2546. if (const Expr *LastEx = dyn_cast<Expr>(Last))
  2547. Last = LastEx->IgnoreParens();
  2548. unsigned x = M->size();
  2549. (*M)[Last] = x;
  2550. }
  2551. }
  2552. unsigned x = M->size();
  2553. (*M)[Exp] = x;
  2554. }
  2555. }
  2556. // Look at terminators. The condition is a block-level expression.
  2557. Stmt *S = (*I)->getTerminatorCondition();
  2558. if (S && M->find(S) == M->end()) {
  2559. unsigned x = M->size();
  2560. (*M)[S] = x;
  2561. }
  2562. }
  2563. return M;
  2564. }
  2565. CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt *S) {
  2566. assert(S != NULL);
  2567. if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
  2568. BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
  2569. BlkExprMapTy::iterator I = M->find(S);
  2570. return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
  2571. }
  2572. unsigned CFG::getNumBlkExprs() {
  2573. if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
  2574. return M->size();
  2575. // We assume callers interested in the number of BlkExprs will want
  2576. // the map constructed if it doesn't already exist.
  2577. BlkExprMap = (void*) PopulateBlkExprMap(*this);
  2578. return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
  2579. }
  2580. //===----------------------------------------------------------------------===//
  2581. // Filtered walking of the CFG.
  2582. //===----------------------------------------------------------------------===//
  2583. bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
  2584. const CFGBlock *From, const CFGBlock *To) {
  2585. if (To && F.IgnoreDefaultsWithCoveredEnums) {
  2586. // If the 'To' has no label or is labeled but the label isn't a
  2587. // CaseStmt then filter this edge.
  2588. if (const SwitchStmt *S =
  2589. dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
  2590. if (S->isAllEnumCasesCovered()) {
  2591. const Stmt *L = To->getLabel();
  2592. if (!L || !isa<CaseStmt>(L))
  2593. return true;
  2594. }
  2595. }
  2596. }
  2597. return false;
  2598. }
  2599. //===----------------------------------------------------------------------===//
  2600. // Cleanup: CFG dstor.
  2601. //===----------------------------------------------------------------------===//
  2602. CFG::~CFG() {
  2603. delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
  2604. }
  2605. //===----------------------------------------------------------------------===//
  2606. // CFG pretty printing
  2607. //===----------------------------------------------------------------------===//
  2608. namespace {
  2609. class StmtPrinterHelper : public PrinterHelper {
  2610. typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
  2611. typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
  2612. StmtMapTy StmtMap;
  2613. DeclMapTy DeclMap;
  2614. signed currentBlock;
  2615. unsigned currentStmt;
  2616. const LangOptions &LangOpts;
  2617. public:
  2618. StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
  2619. : currentBlock(0), currentStmt(0), LangOpts(LO)
  2620. {
  2621. for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
  2622. unsigned j = 1;
  2623. for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
  2624. BI != BEnd; ++BI, ++j ) {
  2625. if (const CFGStmt *SE = BI->getAs<CFGStmt>()) {
  2626. const Stmt *stmt= SE->getStmt();
  2627. std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
  2628. StmtMap[stmt] = P;
  2629. switch (stmt->getStmtClass()) {
  2630. case Stmt::DeclStmtClass:
  2631. DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
  2632. break;
  2633. case Stmt::IfStmtClass: {
  2634. const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
  2635. if (var)
  2636. DeclMap[var] = P;
  2637. break;
  2638. }
  2639. case Stmt::ForStmtClass: {
  2640. const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
  2641. if (var)
  2642. DeclMap[var] = P;
  2643. break;
  2644. }
  2645. case Stmt::WhileStmtClass: {
  2646. const VarDecl *var =
  2647. cast<WhileStmt>(stmt)->getConditionVariable();
  2648. if (var)
  2649. DeclMap[var] = P;
  2650. break;
  2651. }
  2652. case Stmt::SwitchStmtClass: {
  2653. const VarDecl *var =
  2654. cast<SwitchStmt>(stmt)->getConditionVariable();
  2655. if (var)
  2656. DeclMap[var] = P;
  2657. break;
  2658. }
  2659. case Stmt::CXXCatchStmtClass: {
  2660. const VarDecl *var =
  2661. cast<CXXCatchStmt>(stmt)->getExceptionDecl();
  2662. if (var)
  2663. DeclMap[var] = P;
  2664. break;
  2665. }
  2666. default:
  2667. break;
  2668. }
  2669. }
  2670. }
  2671. }
  2672. }
  2673. virtual ~StmtPrinterHelper() {}
  2674. const LangOptions &getLangOpts() const { return LangOpts; }
  2675. void setBlockID(signed i) { currentBlock = i; }
  2676. void setStmtID(unsigned i) { currentStmt = i; }
  2677. virtual bool handledStmt(Stmt *S, raw_ostream &OS) {
  2678. StmtMapTy::iterator I = StmtMap.find(S);
  2679. if (I == StmtMap.end())
  2680. return false;
  2681. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  2682. && I->second.second == currentStmt) {
  2683. return false;
  2684. }
  2685. OS << "[B" << I->second.first << "." << I->second.second << "]";
  2686. return true;
  2687. }
  2688. bool handleDecl(const Decl *D, raw_ostream &OS) {
  2689. DeclMapTy::iterator I = DeclMap.find(D);
  2690. if (I == DeclMap.end())
  2691. return false;
  2692. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  2693. && I->second.second == currentStmt) {
  2694. return false;
  2695. }
  2696. OS << "[B" << I->second.first << "." << I->second.second << "]";
  2697. return true;
  2698. }
  2699. };
  2700. } // end anonymous namespace
  2701. namespace {
  2702. class CFGBlockTerminatorPrint
  2703. : public StmtVisitor<CFGBlockTerminatorPrint,void> {
  2704. raw_ostream &OS;
  2705. StmtPrinterHelper* Helper;
  2706. PrintingPolicy Policy;
  2707. public:
  2708. CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
  2709. const PrintingPolicy &Policy)
  2710. : OS(os), Helper(helper), Policy(Policy) {}
  2711. void VisitIfStmt(IfStmt *I) {
  2712. OS << "if ";
  2713. I->getCond()->printPretty(OS,Helper,Policy);
  2714. }
  2715. // Default case.
  2716. void VisitStmt(Stmt *Terminator) {
  2717. Terminator->printPretty(OS, Helper, Policy);
  2718. }
  2719. void VisitForStmt(ForStmt *F) {
  2720. OS << "for (" ;
  2721. if (F->getInit())
  2722. OS << "...";
  2723. OS << "; ";
  2724. if (Stmt *C = F->getCond())
  2725. C->printPretty(OS, Helper, Policy);
  2726. OS << "; ";
  2727. if (F->getInc())
  2728. OS << "...";
  2729. OS << ")";
  2730. }
  2731. void VisitWhileStmt(WhileStmt *W) {
  2732. OS << "while " ;
  2733. if (Stmt *C = W->getCond())
  2734. C->printPretty(OS, Helper, Policy);
  2735. }
  2736. void VisitDoStmt(DoStmt *D) {
  2737. OS << "do ... while ";
  2738. if (Stmt *C = D->getCond())
  2739. C->printPretty(OS, Helper, Policy);
  2740. }
  2741. void VisitSwitchStmt(SwitchStmt *Terminator) {
  2742. OS << "switch ";
  2743. Terminator->getCond()->printPretty(OS, Helper, Policy);
  2744. }
  2745. void VisitCXXTryStmt(CXXTryStmt *CS) {
  2746. OS << "try ...";
  2747. }
  2748. void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
  2749. C->getCond()->printPretty(OS, Helper, Policy);
  2750. OS << " ? ... : ...";
  2751. }
  2752. void VisitChooseExpr(ChooseExpr *C) {
  2753. OS << "__builtin_choose_expr( ";
  2754. C->getCond()->printPretty(OS, Helper, Policy);
  2755. OS << " )";
  2756. }
  2757. void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  2758. OS << "goto *";
  2759. I->getTarget()->printPretty(OS, Helper, Policy);
  2760. }
  2761. void VisitBinaryOperator(BinaryOperator* B) {
  2762. if (!B->isLogicalOp()) {
  2763. VisitExpr(B);
  2764. return;
  2765. }
  2766. B->getLHS()->printPretty(OS, Helper, Policy);
  2767. switch (B->getOpcode()) {
  2768. case BO_LOr:
  2769. OS << " || ...";
  2770. return;
  2771. case BO_LAnd:
  2772. OS << " && ...";
  2773. return;
  2774. default:
  2775. assert(false && "Invalid logical operator.");
  2776. }
  2777. }
  2778. void VisitExpr(Expr *E) {
  2779. E->printPretty(OS, Helper, Policy);
  2780. }
  2781. };
  2782. } // end anonymous namespace
  2783. static void print_elem(raw_ostream &OS, StmtPrinterHelper* Helper,
  2784. const CFGElement &E) {
  2785. if (const CFGStmt *CS = E.getAs<CFGStmt>()) {
  2786. const Stmt *S = CS->getStmt();
  2787. if (Helper) {
  2788. // special printing for statement-expressions.
  2789. if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
  2790. const CompoundStmt *Sub = SE->getSubStmt();
  2791. if (Sub->children()) {
  2792. OS << "({ ... ; ";
  2793. Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
  2794. OS << " })\n";
  2795. return;
  2796. }
  2797. }
  2798. // special printing for comma expressions.
  2799. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
  2800. if (B->getOpcode() == BO_Comma) {
  2801. OS << "... , ";
  2802. Helper->handledStmt(B->getRHS(),OS);
  2803. OS << '\n';
  2804. return;
  2805. }
  2806. }
  2807. }
  2808. S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
  2809. if (isa<CXXOperatorCallExpr>(S)) {
  2810. OS << " (OperatorCall)";
  2811. } else if (isa<CXXBindTemporaryExpr>(S)) {
  2812. OS << " (BindTemporary)";
  2813. }
  2814. // Expressions need a newline.
  2815. if (isa<Expr>(S))
  2816. OS << '\n';
  2817. } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) {
  2818. const CXXCtorInitializer *I = IE->getInitializer();
  2819. if (I->isBaseInitializer())
  2820. OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
  2821. else OS << I->getAnyMember()->getName();
  2822. OS << "(";
  2823. if (Expr *IE = I->getInit())
  2824. IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
  2825. OS << ")";
  2826. if (I->isBaseInitializer())
  2827. OS << " (Base initializer)\n";
  2828. else OS << " (Member initializer)\n";
  2829. } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){
  2830. const VarDecl *VD = DE->getVarDecl();
  2831. Helper->handleDecl(VD, OS);
  2832. const Type* T = VD->getType().getTypePtr();
  2833. if (const ReferenceType* RT = T->getAs<ReferenceType>())
  2834. T = RT->getPointeeType().getTypePtr();
  2835. else if (const Type *ET = T->getArrayElementTypeNoTypeQual())
  2836. T = ET;
  2837. OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
  2838. OS << " (Implicit destructor)\n";
  2839. } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) {
  2840. const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
  2841. OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
  2842. OS << " (Base object destructor)\n";
  2843. } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) {
  2844. const FieldDecl *FD = ME->getFieldDecl();
  2845. const Type *T = FD->getType().getTypePtr();
  2846. if (const Type *ET = T->getArrayElementTypeNoTypeQual())
  2847. T = ET;
  2848. OS << "this->" << FD->getName();
  2849. OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
  2850. OS << " (Member object destructor)\n";
  2851. } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) {
  2852. const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
  2853. OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()";
  2854. OS << " (Temporary object destructor)\n";
  2855. }
  2856. }
  2857. static void print_block(raw_ostream &OS, const CFG* cfg,
  2858. const CFGBlock &B,
  2859. StmtPrinterHelper* Helper, bool print_edges) {
  2860. if (Helper) Helper->setBlockID(B.getBlockID());
  2861. // Print the header.
  2862. OS << "\n [ B" << B.getBlockID();
  2863. if (&B == &cfg->getEntry())
  2864. OS << " (ENTRY) ]\n";
  2865. else if (&B == &cfg->getExit())
  2866. OS << " (EXIT) ]\n";
  2867. else if (&B == cfg->getIndirectGotoBlock())
  2868. OS << " (INDIRECT GOTO DISPATCH) ]\n";
  2869. else
  2870. OS << " ]\n";
  2871. // Print the label of this block.
  2872. if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
  2873. if (print_edges)
  2874. OS << " ";
  2875. if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
  2876. OS << L->getName();
  2877. else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  2878. OS << "case ";
  2879. C->getLHS()->printPretty(OS, Helper,
  2880. PrintingPolicy(Helper->getLangOpts()));
  2881. if (C->getRHS()) {
  2882. OS << " ... ";
  2883. C->getRHS()->printPretty(OS, Helper,
  2884. PrintingPolicy(Helper->getLangOpts()));
  2885. }
  2886. } else if (isa<DefaultStmt>(Label))
  2887. OS << "default";
  2888. else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
  2889. OS << "catch (";
  2890. if (CS->getExceptionDecl())
  2891. CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
  2892. 0);
  2893. else
  2894. OS << "...";
  2895. OS << ")";
  2896. } else
  2897. assert(false && "Invalid label statement in CFGBlock.");
  2898. OS << ":\n";
  2899. }
  2900. // Iterate through the statements in the block and print them.
  2901. unsigned j = 1;
  2902. for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
  2903. I != E ; ++I, ++j ) {
  2904. // Print the statement # in the basic block and the statement itself.
  2905. if (print_edges)
  2906. OS << " ";
  2907. OS << llvm::format("%3d", j) << ": ";
  2908. if (Helper)
  2909. Helper->setStmtID(j);
  2910. print_elem(OS,Helper,*I);
  2911. }
  2912. // Print the terminator of this block.
  2913. if (B.getTerminator()) {
  2914. if (print_edges)
  2915. OS << " ";
  2916. OS << " T: ";
  2917. if (Helper) Helper->setBlockID(-1);
  2918. CFGBlockTerminatorPrint TPrinter(OS, Helper,
  2919. PrintingPolicy(Helper->getLangOpts()));
  2920. TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
  2921. OS << '\n';
  2922. }
  2923. if (print_edges) {
  2924. // Print the predecessors of this block.
  2925. OS << " Predecessors (" << B.pred_size() << "):";
  2926. unsigned i = 0;
  2927. for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
  2928. I != E; ++I, ++i) {
  2929. if (i == 8 || (i-8) == 0)
  2930. OS << "\n ";
  2931. OS << " B" << (*I)->getBlockID();
  2932. }
  2933. OS << '\n';
  2934. // Print the successors of this block.
  2935. OS << " Successors (" << B.succ_size() << "):";
  2936. i = 0;
  2937. for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
  2938. I != E; ++I, ++i) {
  2939. if (i == 8 || (i-8) % 10 == 0)
  2940. OS << "\n ";
  2941. if (*I)
  2942. OS << " B" << (*I)->getBlockID();
  2943. else
  2944. OS << " NULL";
  2945. }
  2946. OS << '\n';
  2947. }
  2948. }
  2949. /// dump - A simple pretty printer of a CFG that outputs to stderr.
  2950. void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
  2951. /// print - A simple pretty printer of a CFG that outputs to an ostream.
  2952. void CFG::print(raw_ostream &OS, const LangOptions &LO) const {
  2953. StmtPrinterHelper Helper(this, LO);
  2954. // Print the entry block.
  2955. print_block(OS, this, getEntry(), &Helper, true);
  2956. // Iterate through the CFGBlocks and print them one by one.
  2957. for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
  2958. // Skip the entry block, because we already printed it.
  2959. if (&(**I) == &getEntry() || &(**I) == &getExit())
  2960. continue;
  2961. print_block(OS, this, **I, &Helper, true);
  2962. }
  2963. // Print the exit block.
  2964. print_block(OS, this, getExit(), &Helper, true);
  2965. OS.flush();
  2966. }
  2967. /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
  2968. void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
  2969. print(llvm::errs(), cfg, LO);
  2970. }
  2971. /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
  2972. /// Generally this will only be called from CFG::print.
  2973. void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
  2974. const LangOptions &LO) const {
  2975. StmtPrinterHelper Helper(cfg, LO);
  2976. print_block(OS, cfg, *this, &Helper, true);
  2977. }
  2978. /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
  2979. void CFGBlock::printTerminator(raw_ostream &OS,
  2980. const LangOptions &LO) const {
  2981. CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
  2982. TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt()));
  2983. }
  2984. Stmt *CFGBlock::getTerminatorCondition() {
  2985. Stmt *Terminator = this->Terminator;
  2986. if (!Terminator)
  2987. return NULL;
  2988. Expr *E = NULL;
  2989. switch (Terminator->getStmtClass()) {
  2990. default:
  2991. break;
  2992. case Stmt::ForStmtClass:
  2993. E = cast<ForStmt>(Terminator)->getCond();
  2994. break;
  2995. case Stmt::WhileStmtClass:
  2996. E = cast<WhileStmt>(Terminator)->getCond();
  2997. break;
  2998. case Stmt::DoStmtClass:
  2999. E = cast<DoStmt>(Terminator)->getCond();
  3000. break;
  3001. case Stmt::IfStmtClass:
  3002. E = cast<IfStmt>(Terminator)->getCond();
  3003. break;
  3004. case Stmt::ChooseExprClass:
  3005. E = cast<ChooseExpr>(Terminator)->getCond();
  3006. break;
  3007. case Stmt::IndirectGotoStmtClass:
  3008. E = cast<IndirectGotoStmt>(Terminator)->getTarget();
  3009. break;
  3010. case Stmt::SwitchStmtClass:
  3011. E = cast<SwitchStmt>(Terminator)->getCond();
  3012. break;
  3013. case Stmt::BinaryConditionalOperatorClass:
  3014. E = cast<BinaryConditionalOperator>(Terminator)->getCond();
  3015. break;
  3016. case Stmt::ConditionalOperatorClass:
  3017. E = cast<ConditionalOperator>(Terminator)->getCond();
  3018. break;
  3019. case Stmt::BinaryOperatorClass: // '&&' and '||'
  3020. E = cast<BinaryOperator>(Terminator)->getLHS();
  3021. break;
  3022. case Stmt::ObjCForCollectionStmtClass:
  3023. return Terminator;
  3024. }
  3025. return E ? E->IgnoreParens() : NULL;
  3026. }
  3027. //===----------------------------------------------------------------------===//
  3028. // CFG Graphviz Visualization
  3029. //===----------------------------------------------------------------------===//
  3030. #ifndef NDEBUG
  3031. static StmtPrinterHelper* GraphHelper;
  3032. #endif
  3033. void CFG::viewCFG(const LangOptions &LO) const {
  3034. #ifndef NDEBUG
  3035. StmtPrinterHelper H(this, LO);
  3036. GraphHelper = &H;
  3037. llvm::ViewGraph(this,"CFG");
  3038. GraphHelper = NULL;
  3039. #endif
  3040. }
  3041. namespace llvm {
  3042. template<>
  3043. struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
  3044. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  3045. static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
  3046. #ifndef NDEBUG
  3047. std::string OutSStr;
  3048. llvm::raw_string_ostream Out(OutSStr);
  3049. print_block(Out,Graph, *Node, GraphHelper, false);
  3050. std::string& OutStr = Out.str();
  3051. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  3052. // Process string output to make it nicer...
  3053. for (unsigned i = 0; i != OutStr.length(); ++i)
  3054. if (OutStr[i] == '\n') { // Left justify
  3055. OutStr[i] = '\\';
  3056. OutStr.insert(OutStr.begin()+i+1, 'l');
  3057. }
  3058. return OutStr;
  3059. #else
  3060. return "";
  3061. #endif
  3062. }
  3063. };
  3064. } // end namespace llvm