CFG.cpp 209 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354
  1. //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the CFG and CFGBuilder classes for representing and
  10. // building Control-Flow Graphs (CFGs) from ASTs.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Analysis/CFG.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclBase.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclGroup.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/OperationKinds.h"
  23. #include "clang/AST/PrettyPrinter.h"
  24. #include "clang/AST/Stmt.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/AST/StmtObjC.h"
  27. #include "clang/AST/StmtVisitor.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Analysis/ConstructionContext.h"
  30. #include "clang/Analysis/Support/BumpVector.h"
  31. #include "clang/Basic/Builtins.h"
  32. #include "clang/Basic/ExceptionSpecificationType.h"
  33. #include "clang/Basic/JsonSupport.h"
  34. #include "clang/Basic/LLVM.h"
  35. #include "clang/Basic/LangOptions.h"
  36. #include "clang/Basic/SourceLocation.h"
  37. #include "clang/Basic/Specifiers.h"
  38. #include "llvm/ADT/APInt.h"
  39. #include "llvm/ADT/APSInt.h"
  40. #include "llvm/ADT/ArrayRef.h"
  41. #include "llvm/ADT/DenseMap.h"
  42. #include "llvm/ADT/STLExtras.h"
  43. #include "llvm/ADT/SetVector.h"
  44. #include "llvm/ADT/SmallPtrSet.h"
  45. #include "llvm/ADT/SmallVector.h"
  46. #include "llvm/Support/Allocator.h"
  47. #include "llvm/Support/Casting.h"
  48. #include "llvm/Support/Compiler.h"
  49. #include "llvm/Support/DOTGraphTraits.h"
  50. #include "llvm/Support/ErrorHandling.h"
  51. #include "llvm/Support/Format.h"
  52. #include "llvm/Support/GraphWriter.h"
  53. #include "llvm/Support/SaveAndRestore.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include <cassert>
  56. #include <memory>
  57. #include <optional>
  58. #include <string>
  59. #include <tuple>
  60. #include <utility>
  61. #include <vector>
  62. using namespace clang;
  63. static SourceLocation GetEndLoc(Decl *D) {
  64. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  65. if (Expr *Ex = VD->getInit())
  66. return Ex->getSourceRange().getEnd();
  67. return D->getLocation();
  68. }
  69. /// Returns true on constant values based around a single IntegerLiteral.
  70. /// Allow for use of parentheses, integer casts, and negative signs.
  71. /// FIXME: it would be good to unify this function with
  72. /// getIntegerLiteralSubexpressionValue at some point given the similarity
  73. /// between the functions.
  74. static bool IsIntegerLiteralConstantExpr(const Expr *E) {
  75. // Allow parentheses
  76. E = E->IgnoreParens();
  77. // Allow conversions to different integer kind.
  78. if (const auto *CE = dyn_cast<CastExpr>(E)) {
  79. if (CE->getCastKind() != CK_IntegralCast)
  80. return false;
  81. E = CE->getSubExpr();
  82. }
  83. // Allow negative numbers.
  84. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  85. if (UO->getOpcode() != UO_Minus)
  86. return false;
  87. E = UO->getSubExpr();
  88. }
  89. return isa<IntegerLiteral>(E);
  90. }
  91. /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
  92. /// constant expression or EnumConstantDecl from the given Expr. If it fails,
  93. /// returns nullptr.
  94. static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
  95. E = E->IgnoreParens();
  96. if (IsIntegerLiteralConstantExpr(E))
  97. return E;
  98. if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  99. return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
  100. return nullptr;
  101. }
  102. /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
  103. /// NumExpr is an integer literal or an enum constant.
  104. ///
  105. /// If this fails, at least one of the returned DeclRefExpr or Expr will be
  106. /// null.
  107. static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
  108. tryNormalizeBinaryOperator(const BinaryOperator *B) {
  109. BinaryOperatorKind Op = B->getOpcode();
  110. const Expr *MaybeDecl = B->getLHS();
  111. const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
  112. // Expr looked like `0 == Foo` instead of `Foo == 0`
  113. if (Constant == nullptr) {
  114. // Flip the operator
  115. if (Op == BO_GT)
  116. Op = BO_LT;
  117. else if (Op == BO_GE)
  118. Op = BO_LE;
  119. else if (Op == BO_LT)
  120. Op = BO_GT;
  121. else if (Op == BO_LE)
  122. Op = BO_GE;
  123. MaybeDecl = B->getRHS();
  124. Constant = tryTransformToIntOrEnumConstant(B->getLHS());
  125. }
  126. return std::make_tuple(MaybeDecl, Op, Constant);
  127. }
  128. /// For an expression `x == Foo && x == Bar`, this determines whether the
  129. /// `Foo` and `Bar` are either of the same enumeration type, or both integer
  130. /// literals.
  131. ///
  132. /// It's an error to pass this arguments that are not either IntegerLiterals
  133. /// or DeclRefExprs (that have decls of type EnumConstantDecl)
  134. static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
  135. // User intent isn't clear if they're mixing int literals with enum
  136. // constants.
  137. if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
  138. return false;
  139. // Integer literal comparisons, regardless of literal type, are acceptable.
  140. if (!isa<DeclRefExpr>(E1))
  141. return true;
  142. // IntegerLiterals are handled above and only EnumConstantDecls are expected
  143. // beyond this point
  144. assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
  145. auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
  146. auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
  147. assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
  148. const DeclContext *DC1 = Decl1->getDeclContext();
  149. const DeclContext *DC2 = Decl2->getDeclContext();
  150. assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
  151. return DC1 == DC2;
  152. }
  153. namespace {
  154. class CFGBuilder;
  155. /// The CFG builder uses a recursive algorithm to build the CFG. When
  156. /// we process an expression, sometimes we know that we must add the
  157. /// subexpressions as block-level expressions. For example:
  158. ///
  159. /// exp1 || exp2
  160. ///
  161. /// When processing the '||' expression, we know that exp1 and exp2
  162. /// need to be added as block-level expressions, even though they
  163. /// might not normally need to be. AddStmtChoice records this
  164. /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
  165. /// the builder has an option not to add a subexpression as a
  166. /// block-level expression.
  167. class AddStmtChoice {
  168. public:
  169. enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
  170. AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
  171. bool alwaysAdd(CFGBuilder &builder,
  172. const Stmt *stmt) const;
  173. /// Return a copy of this object, except with the 'always-add' bit
  174. /// set as specified.
  175. AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
  176. return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
  177. }
  178. private:
  179. Kind kind;
  180. };
  181. /// LocalScope - Node in tree of local scopes created for C++ implicit
  182. /// destructor calls generation. It contains list of automatic variables
  183. /// declared in the scope and link to position in previous scope this scope
  184. /// began in.
  185. ///
  186. /// The process of creating local scopes is as follows:
  187. /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
  188. /// - Before processing statements in scope (e.g. CompoundStmt) create
  189. /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
  190. /// and set CFGBuilder::ScopePos to the end of new scope,
  191. /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
  192. /// at this VarDecl,
  193. /// - For every normal (without jump) end of scope add to CFGBlock destructors
  194. /// for objects in the current scope,
  195. /// - For every jump add to CFGBlock destructors for objects
  196. /// between CFGBuilder::ScopePos and local scope position saved for jump
  197. /// target. Thanks to C++ restrictions on goto jumps we can be sure that
  198. /// jump target position will be on the path to root from CFGBuilder::ScopePos
  199. /// (adding any variable that doesn't need constructor to be called to
  200. /// LocalScope can break this assumption),
  201. ///
  202. class LocalScope {
  203. public:
  204. using AutomaticVarsTy = BumpVector<VarDecl *>;
  205. /// const_iterator - Iterates local scope backwards and jumps to previous
  206. /// scope on reaching the beginning of currently iterated scope.
  207. class const_iterator {
  208. const LocalScope* Scope = nullptr;
  209. /// VarIter is guaranteed to be greater then 0 for every valid iterator.
  210. /// Invalid iterator (with null Scope) has VarIter equal to 0.
  211. unsigned VarIter = 0;
  212. public:
  213. /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
  214. /// Incrementing invalid iterator is allowed and will result in invalid
  215. /// iterator.
  216. const_iterator() = default;
  217. /// Create valid iterator. In case when S.Prev is an invalid iterator and
  218. /// I is equal to 0, this will create invalid iterator.
  219. const_iterator(const LocalScope& S, unsigned I)
  220. : Scope(&S), VarIter(I) {
  221. // Iterator to "end" of scope is not allowed. Handle it by going up
  222. // in scopes tree possibly up to invalid iterator in the root.
  223. if (VarIter == 0 && Scope)
  224. *this = Scope->Prev;
  225. }
  226. VarDecl *const* operator->() const {
  227. assert(Scope && "Dereferencing invalid iterator is not allowed");
  228. assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
  229. return &Scope->Vars[VarIter - 1];
  230. }
  231. const VarDecl *getFirstVarInScope() const {
  232. assert(Scope && "Dereferencing invalid iterator is not allowed");
  233. assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
  234. return Scope->Vars[0];
  235. }
  236. VarDecl *operator*() const {
  237. return *this->operator->();
  238. }
  239. const_iterator &operator++() {
  240. if (!Scope)
  241. return *this;
  242. assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
  243. --VarIter;
  244. if (VarIter == 0)
  245. *this = Scope->Prev;
  246. return *this;
  247. }
  248. const_iterator operator++(int) {
  249. const_iterator P = *this;
  250. ++*this;
  251. return P;
  252. }
  253. bool operator==(const const_iterator &rhs) const {
  254. return Scope == rhs.Scope && VarIter == rhs.VarIter;
  255. }
  256. bool operator!=(const const_iterator &rhs) const {
  257. return !(*this == rhs);
  258. }
  259. explicit operator bool() const {
  260. return *this != const_iterator();
  261. }
  262. int distance(const_iterator L);
  263. const_iterator shared_parent(const_iterator L);
  264. bool pointsToFirstDeclaredVar() { return VarIter == 1; }
  265. };
  266. private:
  267. BumpVectorContext ctx;
  268. /// Automatic variables in order of declaration.
  269. AutomaticVarsTy Vars;
  270. /// Iterator to variable in previous scope that was declared just before
  271. /// begin of this scope.
  272. const_iterator Prev;
  273. public:
  274. /// Constructs empty scope linked to previous scope in specified place.
  275. LocalScope(BumpVectorContext ctx, const_iterator P)
  276. : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
  277. /// Begin of scope in direction of CFG building (backwards).
  278. const_iterator begin() const { return const_iterator(*this, Vars.size()); }
  279. void addVar(VarDecl *VD) {
  280. Vars.push_back(VD, ctx);
  281. }
  282. };
  283. } // namespace
  284. /// distance - Calculates distance from this to L. L must be reachable from this
  285. /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
  286. /// number of scopes between this and L.
  287. int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
  288. int D = 0;
  289. const_iterator F = *this;
  290. while (F.Scope != L.Scope) {
  291. assert(F != const_iterator() &&
  292. "L iterator is not reachable from F iterator.");
  293. D += F.VarIter;
  294. F = F.Scope->Prev;
  295. }
  296. D += F.VarIter - L.VarIter;
  297. return D;
  298. }
  299. /// Calculates the closest parent of this iterator
  300. /// that is in a scope reachable through the parents of L.
  301. /// I.e. when using 'goto' from this to L, the lifetime of all variables
  302. /// between this and shared_parent(L) end.
  303. LocalScope::const_iterator
  304. LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
  305. llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
  306. while (true) {
  307. ScopesOfL.insert(L.Scope);
  308. if (L == const_iterator())
  309. break;
  310. L = L.Scope->Prev;
  311. }
  312. const_iterator F = *this;
  313. while (true) {
  314. if (ScopesOfL.count(F.Scope))
  315. return F;
  316. assert(F != const_iterator() &&
  317. "L iterator is not reachable from F iterator.");
  318. F = F.Scope->Prev;
  319. }
  320. }
  321. namespace {
  322. /// Structure for specifying position in CFG during its build process. It
  323. /// consists of CFGBlock that specifies position in CFG and
  324. /// LocalScope::const_iterator that specifies position in LocalScope graph.
  325. struct BlockScopePosPair {
  326. CFGBlock *block = nullptr;
  327. LocalScope::const_iterator scopePosition;
  328. BlockScopePosPair() = default;
  329. BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
  330. : block(b), scopePosition(scopePos) {}
  331. };
  332. /// TryResult - a class representing a variant over the values
  333. /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
  334. /// and is used by the CFGBuilder to decide if a branch condition
  335. /// can be decided up front during CFG construction.
  336. class TryResult {
  337. int X = -1;
  338. public:
  339. TryResult() = default;
  340. TryResult(bool b) : X(b ? 1 : 0) {}
  341. bool isTrue() const { return X == 1; }
  342. bool isFalse() const { return X == 0; }
  343. bool isKnown() const { return X >= 0; }
  344. void negate() {
  345. assert(isKnown());
  346. X ^= 0x1;
  347. }
  348. };
  349. } // namespace
  350. static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
  351. if (!R1.isKnown() || !R2.isKnown())
  352. return TryResult();
  353. return TryResult(R1.isTrue() && R2.isTrue());
  354. }
  355. namespace {
  356. class reverse_children {
  357. llvm::SmallVector<Stmt *, 12> childrenBuf;
  358. ArrayRef<Stmt *> children;
  359. public:
  360. reverse_children(Stmt *S);
  361. using iterator = ArrayRef<Stmt *>::reverse_iterator;
  362. iterator begin() const { return children.rbegin(); }
  363. iterator end() const { return children.rend(); }
  364. };
  365. } // namespace
  366. reverse_children::reverse_children(Stmt *S) {
  367. if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  368. children = CE->getRawSubExprs();
  369. return;
  370. }
  371. switch (S->getStmtClass()) {
  372. // Note: Fill in this switch with more cases we want to optimize.
  373. case Stmt::InitListExprClass: {
  374. InitListExpr *IE = cast<InitListExpr>(S);
  375. children = llvm::ArrayRef(reinterpret_cast<Stmt **>(IE->getInits()),
  376. IE->getNumInits());
  377. return;
  378. }
  379. default:
  380. break;
  381. }
  382. // Default case for all other statements.
  383. llvm::append_range(childrenBuf, S->children());
  384. // This needs to be done *after* childrenBuf has been populated.
  385. children = childrenBuf;
  386. }
  387. namespace {
  388. /// CFGBuilder - This class implements CFG construction from an AST.
  389. /// The builder is stateful: an instance of the builder should be used to only
  390. /// construct a single CFG.
  391. ///
  392. /// Example usage:
  393. ///
  394. /// CFGBuilder builder;
  395. /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
  396. ///
  397. /// CFG construction is done via a recursive walk of an AST. We actually parse
  398. /// the AST in reverse order so that the successor of a basic block is
  399. /// constructed prior to its predecessor. This allows us to nicely capture
  400. /// implicit fall-throughs without extra basic blocks.
  401. class CFGBuilder {
  402. using JumpTarget = BlockScopePosPair;
  403. using JumpSource = BlockScopePosPair;
  404. ASTContext *Context;
  405. std::unique_ptr<CFG> cfg;
  406. // Current block.
  407. CFGBlock *Block = nullptr;
  408. // Block after the current block.
  409. CFGBlock *Succ = nullptr;
  410. JumpTarget ContinueJumpTarget;
  411. JumpTarget BreakJumpTarget;
  412. JumpTarget SEHLeaveJumpTarget;
  413. CFGBlock *SwitchTerminatedBlock = nullptr;
  414. CFGBlock *DefaultCaseBlock = nullptr;
  415. // This can point to either a C++ try, an Objective-C @try, or an SEH __try.
  416. // try and @try can be mixed and generally work the same.
  417. // The frontend forbids mixing SEH __try with either try or @try.
  418. // So having one for all three is enough.
  419. CFGBlock *TryTerminatedBlock = nullptr;
  420. // Current position in local scope.
  421. LocalScope::const_iterator ScopePos;
  422. // LabelMap records the mapping from Label expressions to their jump targets.
  423. using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
  424. LabelMapTy LabelMap;
  425. // A list of blocks that end with a "goto" that must be backpatched to their
  426. // resolved targets upon completion of CFG construction.
  427. using BackpatchBlocksTy = std::vector<JumpSource>;
  428. BackpatchBlocksTy BackpatchBlocks;
  429. // A list of labels whose address has been taken (for indirect gotos).
  430. using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
  431. LabelSetTy AddressTakenLabels;
  432. // Information about the currently visited C++ object construction site.
  433. // This is set in the construction trigger and read when the constructor
  434. // or a function that returns an object by value is being visited.
  435. llvm::DenseMap<Expr *, const ConstructionContextLayer *>
  436. ConstructionContextMap;
  437. using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
  438. DeclsWithEndedScopeSetTy DeclsWithEndedScope;
  439. bool badCFG = false;
  440. const CFG::BuildOptions &BuildOpts;
  441. // State to track for building switch statements.
  442. bool switchExclusivelyCovered = false;
  443. Expr::EvalResult *switchCond = nullptr;
  444. CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
  445. const Stmt *lastLookup = nullptr;
  446. // Caches boolean evaluations of expressions to avoid multiple re-evaluations
  447. // during construction of branches for chained logical operators.
  448. using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
  449. CachedBoolEvalsTy CachedBoolEvals;
  450. public:
  451. explicit CFGBuilder(ASTContext *astContext,
  452. const CFG::BuildOptions &buildOpts)
  453. : Context(astContext), cfg(new CFG()), BuildOpts(buildOpts) {}
  454. // buildCFG - Used by external clients to construct the CFG.
  455. std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
  456. bool alwaysAdd(const Stmt *stmt);
  457. private:
  458. // Visitors to walk an AST and construct the CFG.
  459. CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
  460. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
  461. CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc);
  462. CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
  463. CFGBlock *VisitBreakStmt(BreakStmt *B);
  464. CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
  465. CFGBlock *VisitCaseStmt(CaseStmt *C);
  466. CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
  467. CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
  468. CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
  469. AddStmtChoice asc);
  470. CFGBlock *VisitContinueStmt(ContinueStmt *C);
  471. CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  472. AddStmtChoice asc);
  473. CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
  474. CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
  475. CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
  476. CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
  477. CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
  478. CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  479. AddStmtChoice asc);
  480. CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  481. AddStmtChoice asc);
  482. CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
  483. CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
  484. CFGBlock *VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc);
  485. CFGBlock *VisitDeclStmt(DeclStmt *DS);
  486. CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
  487. CFGBlock *VisitDefaultStmt(DefaultStmt *D);
  488. CFGBlock *VisitDoStmt(DoStmt *D);
  489. CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
  490. AddStmtChoice asc, bool ExternallyDestructed);
  491. CFGBlock *VisitForStmt(ForStmt *F);
  492. CFGBlock *VisitGotoStmt(GotoStmt *G);
  493. CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
  494. CFGBlock *VisitIfStmt(IfStmt *I);
  495. CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
  496. CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
  497. CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
  498. CFGBlock *VisitLabelStmt(LabelStmt *L);
  499. CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
  500. CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
  501. CFGBlock *VisitLogicalOperator(BinaryOperator *B);
  502. std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
  503. Stmt *Term,
  504. CFGBlock *TrueBlock,
  505. CFGBlock *FalseBlock);
  506. CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
  507. AddStmtChoice asc);
  508. CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
  509. CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
  510. CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  511. CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
  512. CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
  513. CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
  514. CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
  515. CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
  516. CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
  517. CFGBlock *VisitReturnStmt(Stmt *S);
  518. CFGBlock *VisitCoroutineSuspendExpr(CoroutineSuspendExpr *S,
  519. AddStmtChoice asc);
  520. CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
  521. CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
  522. CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
  523. CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
  524. CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
  525. CFGBlock *VisitSwitchStmt(SwitchStmt *S);
  526. CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  527. AddStmtChoice asc);
  528. CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
  529. CFGBlock *VisitWhileStmt(WhileStmt *W);
  530. CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
  531. CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
  532. bool ExternallyDestructed = false);
  533. CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
  534. CFGBlock *VisitChildren(Stmt *S);
  535. CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
  536. CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
  537. AddStmtChoice asc);
  538. void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
  539. const Stmt *S) {
  540. if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
  541. appendScopeBegin(B, VD, S);
  542. }
  543. /// When creating the CFG for temporary destructors, we want to mirror the
  544. /// branch structure of the corresponding constructor calls.
  545. /// Thus, while visiting a statement for temporary destructors, we keep a
  546. /// context to keep track of the following information:
  547. /// - whether a subexpression is executed unconditionally
  548. /// - if a subexpression is executed conditionally, the first
  549. /// CXXBindTemporaryExpr we encounter in that subexpression (which
  550. /// corresponds to the last temporary destructor we have to call for this
  551. /// subexpression) and the CFG block at that point (which will become the
  552. /// successor block when inserting the decision point).
  553. ///
  554. /// That way, we can build the branch structure for temporary destructors as
  555. /// follows:
  556. /// 1. If a subexpression is executed unconditionally, we add the temporary
  557. /// destructor calls to the current block.
  558. /// 2. If a subexpression is executed conditionally, when we encounter a
  559. /// CXXBindTemporaryExpr:
  560. /// a) If it is the first temporary destructor call in the subexpression,
  561. /// we remember the CXXBindTemporaryExpr and the current block in the
  562. /// TempDtorContext; we start a new block, and insert the temporary
  563. /// destructor call.
  564. /// b) Otherwise, add the temporary destructor call to the current block.
  565. /// 3. When we finished visiting a conditionally executed subexpression,
  566. /// and we found at least one temporary constructor during the visitation
  567. /// (2.a has executed), we insert a decision block that uses the
  568. /// CXXBindTemporaryExpr as terminator, and branches to the current block
  569. /// if the CXXBindTemporaryExpr was marked executed, and otherwise
  570. /// branches to the stored successor.
  571. struct TempDtorContext {
  572. TempDtorContext() = default;
  573. TempDtorContext(TryResult KnownExecuted)
  574. : IsConditional(true), KnownExecuted(KnownExecuted) {}
  575. /// Returns whether we need to start a new branch for a temporary destructor
  576. /// call. This is the case when the temporary destructor is
  577. /// conditionally executed, and it is the first one we encounter while
  578. /// visiting a subexpression - other temporary destructors at the same level
  579. /// will be added to the same block and are executed under the same
  580. /// condition.
  581. bool needsTempDtorBranch() const {
  582. return IsConditional && !TerminatorExpr;
  583. }
  584. /// Remember the successor S of a temporary destructor decision branch for
  585. /// the corresponding CXXBindTemporaryExpr E.
  586. void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
  587. Succ = S;
  588. TerminatorExpr = E;
  589. }
  590. const bool IsConditional = false;
  591. const TryResult KnownExecuted = true;
  592. CFGBlock *Succ = nullptr;
  593. CXXBindTemporaryExpr *TerminatorExpr = nullptr;
  594. };
  595. // Visitors to walk an AST and generate destructors of temporaries in
  596. // full expression.
  597. CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
  598. TempDtorContext &Context);
  599. CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
  600. TempDtorContext &Context);
  601. CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
  602. bool ExternallyDestructed,
  603. TempDtorContext &Context);
  604. CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
  605. CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
  606. CFGBlock *VisitConditionalOperatorForTemporaryDtors(
  607. AbstractConditionalOperator *E, bool ExternallyDestructed,
  608. TempDtorContext &Context);
  609. void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
  610. CFGBlock *FalseSucc = nullptr);
  611. // NYS == Not Yet Supported
  612. CFGBlock *NYS() {
  613. badCFG = true;
  614. return Block;
  615. }
  616. // Remember to apply the construction context based on the current \p Layer
  617. // when constructing the CFG element for \p CE.
  618. void consumeConstructionContext(const ConstructionContextLayer *Layer,
  619. Expr *E);
  620. // Scan \p Child statement to find constructors in it, while keeping in mind
  621. // that its parent statement is providing a partial construction context
  622. // described by \p Layer. If a constructor is found, it would be assigned
  623. // the context based on the layer. If an additional construction context layer
  624. // is found, the function recurses into that.
  625. void findConstructionContexts(const ConstructionContextLayer *Layer,
  626. Stmt *Child);
  627. // Scan all arguments of a call expression for a construction context.
  628. // These sorts of call expressions don't have a common superclass,
  629. // hence strict duck-typing.
  630. template <typename CallLikeExpr,
  631. typename = std::enable_if_t<
  632. std::is_base_of_v<CallExpr, CallLikeExpr> ||
  633. std::is_base_of_v<CXXConstructExpr, CallLikeExpr> ||
  634. std::is_base_of_v<ObjCMessageExpr, CallLikeExpr>>>
  635. void findConstructionContextsForArguments(CallLikeExpr *E) {
  636. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  637. Expr *Arg = E->getArg(i);
  638. if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
  639. findConstructionContexts(
  640. ConstructionContextLayer::create(cfg->getBumpVectorContext(),
  641. ConstructionContextItem(E, i)),
  642. Arg);
  643. }
  644. }
  645. // Unset the construction context after consuming it. This is done immediately
  646. // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
  647. // there's no need to do this manually in every Visit... function.
  648. void cleanupConstructionContext(Expr *E);
  649. void autoCreateBlock() { if (!Block) Block = createBlock(); }
  650. CFGBlock *createBlock(bool add_successor = true);
  651. CFGBlock *createNoReturnBlock();
  652. CFGBlock *addStmt(Stmt *S) {
  653. return Visit(S, AddStmtChoice::AlwaysAdd);
  654. }
  655. CFGBlock *addInitializer(CXXCtorInitializer *I);
  656. void addLoopExit(const Stmt *LoopStmt);
  657. void addAutomaticObjDtors(LocalScope::const_iterator B,
  658. LocalScope::const_iterator E, Stmt *S);
  659. void addLifetimeEnds(LocalScope::const_iterator B,
  660. LocalScope::const_iterator E, Stmt *S);
  661. void addAutomaticObjHandling(LocalScope::const_iterator B,
  662. LocalScope::const_iterator E, Stmt *S);
  663. void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
  664. void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
  665. Stmt *S);
  666. void getDeclsWithEndedScope(LocalScope::const_iterator B,
  667. LocalScope::const_iterator E, Stmt *S);
  668. // Local scopes creation.
  669. LocalScope* createOrReuseLocalScope(LocalScope* Scope);
  670. void addLocalScopeForStmt(Stmt *S);
  671. LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
  672. LocalScope* Scope = nullptr);
  673. LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
  674. void addLocalScopeAndDtors(Stmt *S);
  675. const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
  676. if (!BuildOpts.AddRichCXXConstructors)
  677. return nullptr;
  678. const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
  679. if (!Layer)
  680. return nullptr;
  681. cleanupConstructionContext(E);
  682. return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
  683. Layer);
  684. }
  685. // Interface to CFGBlock - adding CFGElements.
  686. void appendStmt(CFGBlock *B, const Stmt *S) {
  687. if (alwaysAdd(S) && cachedEntry)
  688. cachedEntry->second = B;
  689. // All block-level expressions should have already been IgnoreParens()ed.
  690. assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
  691. B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
  692. }
  693. void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
  694. if (const ConstructionContext *CC =
  695. retrieveAndCleanupConstructionContext(CE)) {
  696. B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
  697. return;
  698. }
  699. // No valid construction context found. Fall back to statement.
  700. B->appendStmt(CE, cfg->getBumpVectorContext());
  701. }
  702. void appendCall(CFGBlock *B, CallExpr *CE) {
  703. if (alwaysAdd(CE) && cachedEntry)
  704. cachedEntry->second = B;
  705. if (const ConstructionContext *CC =
  706. retrieveAndCleanupConstructionContext(CE)) {
  707. B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
  708. return;
  709. }
  710. // No valid construction context found. Fall back to statement.
  711. B->appendStmt(CE, cfg->getBumpVectorContext());
  712. }
  713. void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
  714. B->appendInitializer(I, cfg->getBumpVectorContext());
  715. }
  716. void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
  717. B->appendNewAllocator(NE, cfg->getBumpVectorContext());
  718. }
  719. void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
  720. B->appendBaseDtor(BS, cfg->getBumpVectorContext());
  721. }
  722. void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
  723. B->appendMemberDtor(FD, cfg->getBumpVectorContext());
  724. }
  725. void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
  726. if (alwaysAdd(ME) && cachedEntry)
  727. cachedEntry->second = B;
  728. if (const ConstructionContext *CC =
  729. retrieveAndCleanupConstructionContext(ME)) {
  730. B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
  731. return;
  732. }
  733. B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
  734. cfg->getBumpVectorContext());
  735. }
  736. void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
  737. B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
  738. }
  739. void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
  740. B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
  741. }
  742. void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
  743. B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
  744. }
  745. void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
  746. B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
  747. }
  748. void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
  749. B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
  750. }
  751. void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  752. LocalScope::const_iterator B, LocalScope::const_iterator E);
  753. void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
  754. LocalScope::const_iterator B,
  755. LocalScope::const_iterator E);
  756. const VarDecl *
  757. prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
  758. LocalScope::const_iterator B,
  759. LocalScope::const_iterator E);
  760. void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
  761. B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
  762. cfg->getBumpVectorContext());
  763. }
  764. /// Add a reachable successor to a block, with the alternate variant that is
  765. /// unreachable.
  766. void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
  767. B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
  768. cfg->getBumpVectorContext());
  769. }
  770. void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  771. if (BuildOpts.AddScopes)
  772. B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
  773. }
  774. void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  775. if (BuildOpts.AddScopes)
  776. B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
  777. }
  778. void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  779. if (BuildOpts.AddScopes)
  780. B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
  781. }
  782. void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
  783. if (BuildOpts.AddScopes)
  784. B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
  785. }
  786. /// Find a relational comparison with an expression evaluating to a
  787. /// boolean and a constant other than 0 and 1.
  788. /// e.g. if ((x < y) == 10)
  789. TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
  790. const Expr *LHSExpr = B->getLHS()->IgnoreParens();
  791. const Expr *RHSExpr = B->getRHS()->IgnoreParens();
  792. const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
  793. const Expr *BoolExpr = RHSExpr;
  794. bool IntFirst = true;
  795. if (!IntLiteral) {
  796. IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
  797. BoolExpr = LHSExpr;
  798. IntFirst = false;
  799. }
  800. if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
  801. return TryResult();
  802. llvm::APInt IntValue = IntLiteral->getValue();
  803. if ((IntValue == 1) || (IntValue == 0))
  804. return TryResult();
  805. bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
  806. !IntValue.isNegative();
  807. BinaryOperatorKind Bok = B->getOpcode();
  808. if (Bok == BO_GT || Bok == BO_GE) {
  809. // Always true for 10 > bool and bool > -1
  810. // Always false for -1 > bool and bool > 10
  811. return TryResult(IntFirst == IntLarger);
  812. } else {
  813. // Always true for -1 < bool and bool < 10
  814. // Always false for 10 < bool and bool < -1
  815. return TryResult(IntFirst != IntLarger);
  816. }
  817. }
  818. /// Find an incorrect equality comparison. Either with an expression
  819. /// evaluating to a boolean and a constant other than 0 and 1.
  820. /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
  821. /// true/false e.q. (x & 8) == 4.
  822. TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
  823. const Expr *LHSExpr = B->getLHS()->IgnoreParens();
  824. const Expr *RHSExpr = B->getRHS()->IgnoreParens();
  825. std::optional<llvm::APInt> IntLiteral1 =
  826. getIntegerLiteralSubexpressionValue(LHSExpr);
  827. const Expr *BoolExpr = RHSExpr;
  828. if (!IntLiteral1) {
  829. IntLiteral1 = getIntegerLiteralSubexpressionValue(RHSExpr);
  830. BoolExpr = LHSExpr;
  831. }
  832. if (!IntLiteral1)
  833. return TryResult();
  834. const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
  835. if (BitOp && (BitOp->getOpcode() == BO_And ||
  836. BitOp->getOpcode() == BO_Or)) {
  837. const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
  838. const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
  839. std::optional<llvm::APInt> IntLiteral2 =
  840. getIntegerLiteralSubexpressionValue(LHSExpr2);
  841. if (!IntLiteral2)
  842. IntLiteral2 = getIntegerLiteralSubexpressionValue(RHSExpr2);
  843. if (!IntLiteral2)
  844. return TryResult();
  845. if ((BitOp->getOpcode() == BO_And &&
  846. (*IntLiteral2 & *IntLiteral1) != *IntLiteral1) ||
  847. (BitOp->getOpcode() == BO_Or &&
  848. (*IntLiteral2 | *IntLiteral1) != *IntLiteral1)) {
  849. if (BuildOpts.Observer)
  850. BuildOpts.Observer->compareBitwiseEquality(B,
  851. B->getOpcode() != BO_EQ);
  852. return TryResult(B->getOpcode() != BO_EQ);
  853. }
  854. } else if (BoolExpr->isKnownToHaveBooleanValue()) {
  855. if ((*IntLiteral1 == 1) || (*IntLiteral1 == 0)) {
  856. return TryResult();
  857. }
  858. return TryResult(B->getOpcode() != BO_EQ);
  859. }
  860. return TryResult();
  861. }
  862. // Helper function to get an APInt from an expression. Supports expressions
  863. // which are an IntegerLiteral or a UnaryOperator and returns the value with
  864. // all operations performed on it.
  865. // FIXME: it would be good to unify this function with
  866. // IsIntegerLiteralConstantExpr at some point given the similarity between the
  867. // functions.
  868. std::optional<llvm::APInt>
  869. getIntegerLiteralSubexpressionValue(const Expr *E) {
  870. // If unary.
  871. if (const auto *UnOp = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
  872. // Get the sub expression of the unary expression and get the Integer
  873. // Literal.
  874. const Expr *SubExpr = UnOp->getSubExpr()->IgnoreParens();
  875. if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(SubExpr)) {
  876. llvm::APInt Value = IntLiteral->getValue();
  877. // Perform the operation manually.
  878. switch (UnOp->getOpcode()) {
  879. case UO_Plus:
  880. return Value;
  881. case UO_Minus:
  882. return -Value;
  883. case UO_Not:
  884. return ~Value;
  885. case UO_LNot:
  886. return llvm::APInt(Context->getTypeSize(Context->IntTy), !Value);
  887. default:
  888. assert(false && "Unexpected unary operator!");
  889. return std::nullopt;
  890. }
  891. }
  892. } else if (const auto *IntLiteral =
  893. dyn_cast<IntegerLiteral>(E->IgnoreParens()))
  894. return IntLiteral->getValue();
  895. return std::nullopt;
  896. }
  897. TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
  898. const llvm::APSInt &Value1,
  899. const llvm::APSInt &Value2) {
  900. assert(Value1.isSigned() == Value2.isSigned());
  901. switch (Relation) {
  902. default:
  903. return TryResult();
  904. case BO_EQ:
  905. return TryResult(Value1 == Value2);
  906. case BO_NE:
  907. return TryResult(Value1 != Value2);
  908. case BO_LT:
  909. return TryResult(Value1 < Value2);
  910. case BO_LE:
  911. return TryResult(Value1 <= Value2);
  912. case BO_GT:
  913. return TryResult(Value1 > Value2);
  914. case BO_GE:
  915. return TryResult(Value1 >= Value2);
  916. }
  917. }
  918. /// Find a pair of comparison expressions with or without parentheses
  919. /// with a shared variable and constants and a logical operator between them
  920. /// that always evaluates to either true or false.
  921. /// e.g. if (x != 3 || x != 4)
  922. TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
  923. assert(B->isLogicalOp());
  924. const BinaryOperator *LHS =
  925. dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
  926. const BinaryOperator *RHS =
  927. dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
  928. if (!LHS || !RHS)
  929. return {};
  930. if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
  931. return {};
  932. const Expr *DeclExpr1;
  933. const Expr *NumExpr1;
  934. BinaryOperatorKind BO1;
  935. std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
  936. if (!DeclExpr1 || !NumExpr1)
  937. return {};
  938. const Expr *DeclExpr2;
  939. const Expr *NumExpr2;
  940. BinaryOperatorKind BO2;
  941. std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
  942. if (!DeclExpr2 || !NumExpr2)
  943. return {};
  944. // Check that it is the same variable on both sides.
  945. if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
  946. return {};
  947. // Make sure the user's intent is clear (e.g. they're comparing against two
  948. // int literals, or two things from the same enum)
  949. if (!areExprTypesCompatible(NumExpr1, NumExpr2))
  950. return {};
  951. Expr::EvalResult L1Result, L2Result;
  952. if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
  953. !NumExpr2->EvaluateAsInt(L2Result, *Context))
  954. return {};
  955. llvm::APSInt L1 = L1Result.Val.getInt();
  956. llvm::APSInt L2 = L2Result.Val.getInt();
  957. // Can't compare signed with unsigned or with different bit width.
  958. if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
  959. return {};
  960. // Values that will be used to determine if result of logical
  961. // operator is always true/false
  962. const llvm::APSInt Values[] = {
  963. // Value less than both Value1 and Value2
  964. llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
  965. // L1
  966. L1,
  967. // Value between Value1 and Value2
  968. ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
  969. L1.isUnsigned()),
  970. // L2
  971. L2,
  972. // Value greater than both Value1 and Value2
  973. llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
  974. };
  975. // Check whether expression is always true/false by evaluating the following
  976. // * variable x is less than the smallest literal.
  977. // * variable x is equal to the smallest literal.
  978. // * Variable x is between smallest and largest literal.
  979. // * Variable x is equal to the largest literal.
  980. // * Variable x is greater than largest literal.
  981. bool AlwaysTrue = true, AlwaysFalse = true;
  982. // Track value of both subexpressions. If either side is always
  983. // true/false, another warning should have already been emitted.
  984. bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
  985. bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
  986. for (const llvm::APSInt &Value : Values) {
  987. TryResult Res1, Res2;
  988. Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
  989. Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
  990. if (!Res1.isKnown() || !Res2.isKnown())
  991. return {};
  992. if (B->getOpcode() == BO_LAnd) {
  993. AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
  994. AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
  995. } else {
  996. AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
  997. AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
  998. }
  999. LHSAlwaysTrue &= Res1.isTrue();
  1000. LHSAlwaysFalse &= Res1.isFalse();
  1001. RHSAlwaysTrue &= Res2.isTrue();
  1002. RHSAlwaysFalse &= Res2.isFalse();
  1003. }
  1004. if (AlwaysTrue || AlwaysFalse) {
  1005. if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
  1006. !RHSAlwaysFalse && BuildOpts.Observer)
  1007. BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
  1008. return TryResult(AlwaysTrue);
  1009. }
  1010. return {};
  1011. }
  1012. /// A bitwise-or with a non-zero constant always evaluates to true.
  1013. TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
  1014. const Expr *LHSConstant =
  1015. tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
  1016. const Expr *RHSConstant =
  1017. tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
  1018. if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
  1019. return {};
  1020. const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
  1021. Expr::EvalResult Result;
  1022. if (!Constant->EvaluateAsInt(Result, *Context))
  1023. return {};
  1024. if (Result.Val.getInt() == 0)
  1025. return {};
  1026. if (BuildOpts.Observer)
  1027. BuildOpts.Observer->compareBitwiseOr(B);
  1028. return TryResult(true);
  1029. }
  1030. /// Try and evaluate an expression to an integer constant.
  1031. bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
  1032. if (!BuildOpts.PruneTriviallyFalseEdges)
  1033. return false;
  1034. return !S->isTypeDependent() &&
  1035. !S->isValueDependent() &&
  1036. S->EvaluateAsRValue(outResult, *Context);
  1037. }
  1038. /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
  1039. /// if we can evaluate to a known value, otherwise return -1.
  1040. TryResult tryEvaluateBool(Expr *S) {
  1041. if (!BuildOpts.PruneTriviallyFalseEdges ||
  1042. S->isTypeDependent() || S->isValueDependent())
  1043. return {};
  1044. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
  1045. if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
  1046. // Check the cache first.
  1047. CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
  1048. if (I != CachedBoolEvals.end())
  1049. return I->second; // already in map;
  1050. // Retrieve result at first, or the map might be updated.
  1051. TryResult Result = evaluateAsBooleanConditionNoCache(S);
  1052. CachedBoolEvals[S] = Result; // update or insert
  1053. return Result;
  1054. }
  1055. else {
  1056. switch (Bop->getOpcode()) {
  1057. default: break;
  1058. // For 'x & 0' and 'x * 0', we can determine that
  1059. // the value is always false.
  1060. case BO_Mul:
  1061. case BO_And: {
  1062. // If either operand is zero, we know the value
  1063. // must be false.
  1064. Expr::EvalResult LHSResult;
  1065. if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
  1066. llvm::APSInt IntVal = LHSResult.Val.getInt();
  1067. if (!IntVal.getBoolValue()) {
  1068. return TryResult(false);
  1069. }
  1070. }
  1071. Expr::EvalResult RHSResult;
  1072. if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
  1073. llvm::APSInt IntVal = RHSResult.Val.getInt();
  1074. if (!IntVal.getBoolValue()) {
  1075. return TryResult(false);
  1076. }
  1077. }
  1078. }
  1079. break;
  1080. }
  1081. }
  1082. }
  1083. return evaluateAsBooleanConditionNoCache(S);
  1084. }
  1085. /// Evaluate as boolean \param E without using the cache.
  1086. TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
  1087. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
  1088. if (Bop->isLogicalOp()) {
  1089. TryResult LHS = tryEvaluateBool(Bop->getLHS());
  1090. if (LHS.isKnown()) {
  1091. // We were able to evaluate the LHS, see if we can get away with not
  1092. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  1093. if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
  1094. return LHS.isTrue();
  1095. TryResult RHS = tryEvaluateBool(Bop->getRHS());
  1096. if (RHS.isKnown()) {
  1097. if (Bop->getOpcode() == BO_LOr)
  1098. return LHS.isTrue() || RHS.isTrue();
  1099. else
  1100. return LHS.isTrue() && RHS.isTrue();
  1101. }
  1102. } else {
  1103. TryResult RHS = tryEvaluateBool(Bop->getRHS());
  1104. if (RHS.isKnown()) {
  1105. // We can't evaluate the LHS; however, sometimes the result
  1106. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  1107. if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
  1108. return RHS.isTrue();
  1109. } else {
  1110. TryResult BopRes = checkIncorrectLogicOperator(Bop);
  1111. if (BopRes.isKnown())
  1112. return BopRes.isTrue();
  1113. }
  1114. }
  1115. return {};
  1116. } else if (Bop->isEqualityOp()) {
  1117. TryResult BopRes = checkIncorrectEqualityOperator(Bop);
  1118. if (BopRes.isKnown())
  1119. return BopRes.isTrue();
  1120. } else if (Bop->isRelationalOp()) {
  1121. TryResult BopRes = checkIncorrectRelationalOperator(Bop);
  1122. if (BopRes.isKnown())
  1123. return BopRes.isTrue();
  1124. } else if (Bop->getOpcode() == BO_Or) {
  1125. TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
  1126. if (BopRes.isKnown())
  1127. return BopRes.isTrue();
  1128. }
  1129. }
  1130. bool Result;
  1131. if (E->EvaluateAsBooleanCondition(Result, *Context))
  1132. return Result;
  1133. return {};
  1134. }
  1135. bool hasTrivialDestructor(VarDecl *VD);
  1136. };
  1137. } // namespace
  1138. Expr *
  1139. clang::extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE) {
  1140. if (!AILE)
  1141. return nullptr;
  1142. Expr *AILEInit = AILE->getSubExpr();
  1143. while (const auto *E = dyn_cast<ArrayInitLoopExpr>(AILEInit))
  1144. AILEInit = E->getSubExpr();
  1145. return AILEInit;
  1146. }
  1147. inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
  1148. const Stmt *stmt) const {
  1149. return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
  1150. }
  1151. bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
  1152. bool shouldAdd = BuildOpts.alwaysAdd(stmt);
  1153. if (!BuildOpts.forcedBlkExprs)
  1154. return shouldAdd;
  1155. if (lastLookup == stmt) {
  1156. if (cachedEntry) {
  1157. assert(cachedEntry->first == stmt);
  1158. return true;
  1159. }
  1160. return shouldAdd;
  1161. }
  1162. lastLookup = stmt;
  1163. // Perform the lookup!
  1164. CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
  1165. if (!fb) {
  1166. // No need to update 'cachedEntry', since it will always be null.
  1167. assert(!cachedEntry);
  1168. return shouldAdd;
  1169. }
  1170. CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
  1171. if (itr == fb->end()) {
  1172. cachedEntry = nullptr;
  1173. return shouldAdd;
  1174. }
  1175. cachedEntry = &*itr;
  1176. return true;
  1177. }
  1178. // FIXME: Add support for dependent-sized array types in C++?
  1179. // Does it even make sense to build a CFG for an uninstantiated template?
  1180. static const VariableArrayType *FindVA(const Type *t) {
  1181. while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
  1182. if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
  1183. if (vat->getSizeExpr())
  1184. return vat;
  1185. t = vt->getElementType().getTypePtr();
  1186. }
  1187. return nullptr;
  1188. }
  1189. void CFGBuilder::consumeConstructionContext(
  1190. const ConstructionContextLayer *Layer, Expr *E) {
  1191. assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
  1192. isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
  1193. if (const ConstructionContextLayer *PreviouslyStoredLayer =
  1194. ConstructionContextMap.lookup(E)) {
  1195. (void)PreviouslyStoredLayer;
  1196. // We might have visited this child when we were finding construction
  1197. // contexts within its parents.
  1198. assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
  1199. "Already within a different construction context!");
  1200. } else {
  1201. ConstructionContextMap[E] = Layer;
  1202. }
  1203. }
  1204. void CFGBuilder::findConstructionContexts(
  1205. const ConstructionContextLayer *Layer, Stmt *Child) {
  1206. if (!BuildOpts.AddRichCXXConstructors)
  1207. return;
  1208. if (!Child)
  1209. return;
  1210. auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
  1211. return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
  1212. Layer);
  1213. };
  1214. switch(Child->getStmtClass()) {
  1215. case Stmt::CXXConstructExprClass:
  1216. case Stmt::CXXTemporaryObjectExprClass: {
  1217. // Support pre-C++17 copy elision AST.
  1218. auto *CE = cast<CXXConstructExpr>(Child);
  1219. if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
  1220. findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
  1221. }
  1222. consumeConstructionContext(Layer, CE);
  1223. break;
  1224. }
  1225. // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
  1226. // FIXME: An isa<> would look much better but this whole switch is a
  1227. // workaround for an internal compiler error in MSVC 2015 (see r326021).
  1228. case Stmt::CallExprClass:
  1229. case Stmt::CXXMemberCallExprClass:
  1230. case Stmt::CXXOperatorCallExprClass:
  1231. case Stmt::UserDefinedLiteralClass:
  1232. case Stmt::ObjCMessageExprClass: {
  1233. auto *E = cast<Expr>(Child);
  1234. if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
  1235. consumeConstructionContext(Layer, E);
  1236. break;
  1237. }
  1238. case Stmt::ExprWithCleanupsClass: {
  1239. auto *Cleanups = cast<ExprWithCleanups>(Child);
  1240. findConstructionContexts(Layer, Cleanups->getSubExpr());
  1241. break;
  1242. }
  1243. case Stmt::CXXFunctionalCastExprClass: {
  1244. auto *Cast = cast<CXXFunctionalCastExpr>(Child);
  1245. findConstructionContexts(Layer, Cast->getSubExpr());
  1246. break;
  1247. }
  1248. case Stmt::ImplicitCastExprClass: {
  1249. auto *Cast = cast<ImplicitCastExpr>(Child);
  1250. // Should we support other implicit cast kinds?
  1251. switch (Cast->getCastKind()) {
  1252. case CK_NoOp:
  1253. case CK_ConstructorConversion:
  1254. findConstructionContexts(Layer, Cast->getSubExpr());
  1255. break;
  1256. default:
  1257. break;
  1258. }
  1259. break;
  1260. }
  1261. case Stmt::CXXBindTemporaryExprClass: {
  1262. auto *BTE = cast<CXXBindTemporaryExpr>(Child);
  1263. findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
  1264. break;
  1265. }
  1266. case Stmt::MaterializeTemporaryExprClass: {
  1267. // Normally we don't want to search in MaterializeTemporaryExpr because
  1268. // it indicates the beginning of a temporary object construction context,
  1269. // so it shouldn't be found in the middle. However, if it is the beginning
  1270. // of an elidable copy or move construction context, we need to include it.
  1271. if (Layer->getItem().getKind() ==
  1272. ConstructionContextItem::ElidableConstructorKind) {
  1273. auto *MTE = cast<MaterializeTemporaryExpr>(Child);
  1274. findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr());
  1275. }
  1276. break;
  1277. }
  1278. case Stmt::ConditionalOperatorClass: {
  1279. auto *CO = cast<ConditionalOperator>(Child);
  1280. if (Layer->getItem().getKind() !=
  1281. ConstructionContextItem::MaterializationKind) {
  1282. // If the object returned by the conditional operator is not going to be a
  1283. // temporary object that needs to be immediately materialized, then
  1284. // it must be C++17 with its mandatory copy elision. Do not yet promise
  1285. // to support this case.
  1286. assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
  1287. Context->getLangOpts().CPlusPlus17);
  1288. break;
  1289. }
  1290. findConstructionContexts(Layer, CO->getLHS());
  1291. findConstructionContexts(Layer, CO->getRHS());
  1292. break;
  1293. }
  1294. case Stmt::InitListExprClass: {
  1295. auto *ILE = cast<InitListExpr>(Child);
  1296. if (ILE->isTransparent()) {
  1297. findConstructionContexts(Layer, ILE->getInit(0));
  1298. break;
  1299. }
  1300. // TODO: Handle other cases. For now, fail to find construction contexts.
  1301. break;
  1302. }
  1303. case Stmt::ParenExprClass: {
  1304. // If expression is placed into parenthesis we should propagate the parent
  1305. // construction context to subexpressions.
  1306. auto *PE = cast<ParenExpr>(Child);
  1307. findConstructionContexts(Layer, PE->getSubExpr());
  1308. break;
  1309. }
  1310. default:
  1311. break;
  1312. }
  1313. }
  1314. void CFGBuilder::cleanupConstructionContext(Expr *E) {
  1315. assert(BuildOpts.AddRichCXXConstructors &&
  1316. "We should not be managing construction contexts!");
  1317. assert(ConstructionContextMap.count(E) &&
  1318. "Cannot exit construction context without the context!");
  1319. ConstructionContextMap.erase(E);
  1320. }
  1321. /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
  1322. /// arbitrary statement. Examples include a single expression or a function
  1323. /// body (compound statement). The ownership of the returned CFG is
  1324. /// transferred to the caller. If CFG construction fails, this method returns
  1325. /// NULL.
  1326. std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
  1327. assert(cfg.get());
  1328. if (!Statement)
  1329. return nullptr;
  1330. // Create an empty block that will serve as the exit block for the CFG. Since
  1331. // this is the first block added to the CFG, it will be implicitly registered
  1332. // as the exit block.
  1333. Succ = createBlock();
  1334. assert(Succ == &cfg->getExit());
  1335. Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
  1336. assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
  1337. "AddImplicitDtors and AddLifetime cannot be used at the same time");
  1338. if (BuildOpts.AddImplicitDtors)
  1339. if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
  1340. addImplicitDtorsForDestructor(DD);
  1341. // Visit the statements and create the CFG.
  1342. CFGBlock *B = addStmt(Statement);
  1343. if (badCFG)
  1344. return nullptr;
  1345. // For C++ constructor add initializers to CFG. Constructors of virtual bases
  1346. // are ignored unless the object is of the most derived class.
  1347. // class VBase { VBase() = default; VBase(int) {} };
  1348. // class A : virtual public VBase { A() : VBase(0) {} };
  1349. // class B : public A {};
  1350. // B b; // Constructor calls in order: VBase(), A(), B().
  1351. // // VBase(0) is ignored because A isn't the most derived class.
  1352. // This may result in the virtual base(s) being already initialized at this
  1353. // point, in which case we should jump right onto non-virtual bases and
  1354. // fields. To handle this, make a CFG branch. We only need to add one such
  1355. // branch per constructor, since the Standard states that all virtual bases
  1356. // shall be initialized before non-virtual bases and direct data members.
  1357. if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
  1358. CFGBlock *VBaseSucc = nullptr;
  1359. for (auto *I : llvm::reverse(CD->inits())) {
  1360. if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
  1361. I->isBaseInitializer() && I->isBaseVirtual()) {
  1362. // We've reached the first virtual base init while iterating in reverse
  1363. // order. Make a new block for virtual base initializers so that we
  1364. // could skip them.
  1365. VBaseSucc = Succ = B ? B : &cfg->getExit();
  1366. Block = createBlock();
  1367. }
  1368. B = addInitializer(I);
  1369. if (badCFG)
  1370. return nullptr;
  1371. }
  1372. if (VBaseSucc) {
  1373. // Make a branch block for potentially skipping virtual base initializers.
  1374. Succ = VBaseSucc;
  1375. B = createBlock();
  1376. B->setTerminator(
  1377. CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
  1378. addSuccessor(B, Block, true);
  1379. }
  1380. }
  1381. if (B)
  1382. Succ = B;
  1383. // Backpatch the gotos whose label -> block mappings we didn't know when we
  1384. // encountered them.
  1385. for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
  1386. E = BackpatchBlocks.end(); I != E; ++I ) {
  1387. CFGBlock *B = I->block;
  1388. if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
  1389. LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
  1390. // If there is no target for the goto, then we are looking at an
  1391. // incomplete AST. Handle this by not registering a successor.
  1392. if (LI == LabelMap.end())
  1393. continue;
  1394. JumpTarget JT = LI->second;
  1395. prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
  1396. JT.scopePosition);
  1397. prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
  1398. JT.scopePosition);
  1399. const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
  1400. B, I->scopePosition, JT.scopePosition);
  1401. appendScopeBegin(JT.block, VD, G);
  1402. addSuccessor(B, JT.block);
  1403. };
  1404. if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
  1405. CFGBlock *Successor = (I+1)->block;
  1406. for (auto *L : G->labels()) {
  1407. LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
  1408. // If there is no target for the goto, then we are looking at an
  1409. // incomplete AST. Handle this by not registering a successor.
  1410. if (LI == LabelMap.end())
  1411. continue;
  1412. JumpTarget JT = LI->second;
  1413. // Successor has been added, so skip it.
  1414. if (JT.block == Successor)
  1415. continue;
  1416. addSuccessor(B, JT.block);
  1417. }
  1418. I++;
  1419. }
  1420. }
  1421. // Add successors to the Indirect Goto Dispatch block (if we have one).
  1422. if (CFGBlock *B = cfg->getIndirectGotoBlock())
  1423. for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
  1424. E = AddressTakenLabels.end(); I != E; ++I ) {
  1425. // Lookup the target block.
  1426. LabelMapTy::iterator LI = LabelMap.find(*I);
  1427. // If there is no target block that contains label, then we are looking
  1428. // at an incomplete AST. Handle this by not registering a successor.
  1429. if (LI == LabelMap.end()) continue;
  1430. addSuccessor(B, LI->second.block);
  1431. }
  1432. // Create an empty entry block that has no predecessors.
  1433. cfg->setEntry(createBlock());
  1434. if (BuildOpts.AddRichCXXConstructors)
  1435. assert(ConstructionContextMap.empty() &&
  1436. "Not all construction contexts were cleaned up!");
  1437. return std::move(cfg);
  1438. }
  1439. /// createBlock - Used to lazily create blocks that are connected
  1440. /// to the current (global) successor.
  1441. CFGBlock *CFGBuilder::createBlock(bool add_successor) {
  1442. CFGBlock *B = cfg->createBlock();
  1443. if (add_successor && Succ)
  1444. addSuccessor(B, Succ);
  1445. return B;
  1446. }
  1447. /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
  1448. /// CFG. It is *not* connected to the current (global) successor, and instead
  1449. /// directly tied to the exit block in order to be reachable.
  1450. CFGBlock *CFGBuilder::createNoReturnBlock() {
  1451. CFGBlock *B = createBlock(false);
  1452. B->setHasNoReturnElement();
  1453. addSuccessor(B, &cfg->getExit(), Succ);
  1454. return B;
  1455. }
  1456. /// addInitializer - Add C++ base or member initializer element to CFG.
  1457. CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
  1458. if (!BuildOpts.AddInitializers)
  1459. return Block;
  1460. bool HasTemporaries = false;
  1461. // Destructors of temporaries in initialization expression should be called
  1462. // after initialization finishes.
  1463. Expr *Init = I->getInit();
  1464. if (Init) {
  1465. HasTemporaries = isa<ExprWithCleanups>(Init);
  1466. if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
  1467. // Generate destructors for temporaries in initialization expression.
  1468. TempDtorContext Context;
  1469. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  1470. /*ExternallyDestructed=*/false, Context);
  1471. }
  1472. }
  1473. autoCreateBlock();
  1474. appendInitializer(Block, I);
  1475. if (Init) {
  1476. // If the initializer is an ArrayInitLoopExpr, we want to extract the
  1477. // initializer, that's used for each element.
  1478. auto *AILEInit = extractElementInitializerFromNestedAILE(
  1479. dyn_cast<ArrayInitLoopExpr>(Init));
  1480. findConstructionContexts(
  1481. ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
  1482. AILEInit ? AILEInit : Init);
  1483. if (HasTemporaries) {
  1484. // For expression with temporaries go directly to subexpression to omit
  1485. // generating destructors for the second time.
  1486. return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
  1487. }
  1488. if (BuildOpts.AddCXXDefaultInitExprInCtors) {
  1489. if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
  1490. // In general, appending the expression wrapped by a CXXDefaultInitExpr
  1491. // may cause the same Expr to appear more than once in the CFG. Doing it
  1492. // here is safe because there's only one initializer per field.
  1493. autoCreateBlock();
  1494. appendStmt(Block, Default);
  1495. if (Stmt *Child = Default->getExpr())
  1496. if (CFGBlock *R = Visit(Child))
  1497. Block = R;
  1498. return Block;
  1499. }
  1500. }
  1501. return Visit(Init);
  1502. }
  1503. return Block;
  1504. }
  1505. /// Retrieve the type of the temporary object whose lifetime was
  1506. /// extended by a local reference with the given initializer.
  1507. static QualType getReferenceInitTemporaryType(const Expr *Init,
  1508. bool *FoundMTE = nullptr) {
  1509. while (true) {
  1510. // Skip parentheses.
  1511. Init = Init->IgnoreParens();
  1512. // Skip through cleanups.
  1513. if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
  1514. Init = EWC->getSubExpr();
  1515. continue;
  1516. }
  1517. // Skip through the temporary-materialization expression.
  1518. if (const MaterializeTemporaryExpr *MTE
  1519. = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  1520. Init = MTE->getSubExpr();
  1521. if (FoundMTE)
  1522. *FoundMTE = true;
  1523. continue;
  1524. }
  1525. // Skip sub-object accesses into rvalues.
  1526. SmallVector<const Expr *, 2> CommaLHSs;
  1527. SmallVector<SubobjectAdjustment, 2> Adjustments;
  1528. const Expr *SkippedInit =
  1529. Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  1530. if (SkippedInit != Init) {
  1531. Init = SkippedInit;
  1532. continue;
  1533. }
  1534. break;
  1535. }
  1536. return Init->getType();
  1537. }
  1538. // TODO: Support adding LoopExit element to the CFG in case where the loop is
  1539. // ended by ReturnStmt, GotoStmt or ThrowExpr.
  1540. void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
  1541. if(!BuildOpts.AddLoopExit)
  1542. return;
  1543. autoCreateBlock();
  1544. appendLoopExit(Block, LoopStmt);
  1545. }
  1546. void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
  1547. LocalScope::const_iterator E, Stmt *S) {
  1548. if (!BuildOpts.AddScopes)
  1549. return;
  1550. if (B == E)
  1551. return;
  1552. // To go from B to E, one first goes up the scopes from B to P
  1553. // then sideways in one scope from P to P' and then down
  1554. // the scopes from P' to E.
  1555. // The lifetime of all objects between B and P end.
  1556. LocalScope::const_iterator P = B.shared_parent(E);
  1557. int Dist = B.distance(P);
  1558. if (Dist <= 0)
  1559. return;
  1560. for (LocalScope::const_iterator I = B; I != P; ++I)
  1561. if (I.pointsToFirstDeclaredVar())
  1562. DeclsWithEndedScope.insert(*I);
  1563. }
  1564. void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
  1565. LocalScope::const_iterator E,
  1566. Stmt *S) {
  1567. getDeclsWithEndedScope(B, E, S);
  1568. if (BuildOpts.AddScopes)
  1569. addScopesEnd(B, E, S);
  1570. if (BuildOpts.AddImplicitDtors)
  1571. addAutomaticObjDtors(B, E, S);
  1572. if (BuildOpts.AddLifetime)
  1573. addLifetimeEnds(B, E, S);
  1574. }
  1575. /// Add to current block automatic objects that leave the scope.
  1576. void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
  1577. LocalScope::const_iterator E, Stmt *S) {
  1578. if (!BuildOpts.AddLifetime)
  1579. return;
  1580. if (B == E)
  1581. return;
  1582. // To go from B to E, one first goes up the scopes from B to P
  1583. // then sideways in one scope from P to P' and then down
  1584. // the scopes from P' to E.
  1585. // The lifetime of all objects between B and P end.
  1586. LocalScope::const_iterator P = B.shared_parent(E);
  1587. int dist = B.distance(P);
  1588. if (dist <= 0)
  1589. return;
  1590. // We need to perform the scope leaving in reverse order
  1591. SmallVector<VarDecl *, 10> DeclsTrivial;
  1592. SmallVector<VarDecl *, 10> DeclsNonTrivial;
  1593. DeclsTrivial.reserve(dist);
  1594. DeclsNonTrivial.reserve(dist);
  1595. for (LocalScope::const_iterator I = B; I != P; ++I)
  1596. if (hasTrivialDestructor(*I))
  1597. DeclsTrivial.push_back(*I);
  1598. else
  1599. DeclsNonTrivial.push_back(*I);
  1600. autoCreateBlock();
  1601. // object with trivial destructor end their lifetime last (when storage
  1602. // duration ends)
  1603. for (VarDecl *VD : llvm::reverse(DeclsTrivial))
  1604. appendLifetimeEnds(Block, VD, S);
  1605. for (VarDecl *VD : llvm::reverse(DeclsNonTrivial))
  1606. appendLifetimeEnds(Block, VD, S);
  1607. }
  1608. /// Add to current block markers for ending scopes.
  1609. void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
  1610. LocalScope::const_iterator E, Stmt *S) {
  1611. // If implicit destructors are enabled, we'll add scope ends in
  1612. // addAutomaticObjDtors.
  1613. if (BuildOpts.AddImplicitDtors)
  1614. return;
  1615. autoCreateBlock();
  1616. for (VarDecl *VD : llvm::reverse(DeclsWithEndedScope))
  1617. appendScopeEnd(Block, VD, S);
  1618. }
  1619. /// addAutomaticObjDtors - Add to current block automatic objects destructors
  1620. /// for objects in range of local scope positions. Use S as trigger statement
  1621. /// for destructors.
  1622. void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
  1623. LocalScope::const_iterator E, Stmt *S) {
  1624. if (!BuildOpts.AddImplicitDtors)
  1625. return;
  1626. if (B == E)
  1627. return;
  1628. // We need to append the destructors in reverse order, but any one of them
  1629. // may be a no-return destructor which changes the CFG. As a result, buffer
  1630. // this sequence up and replay them in reverse order when appending onto the
  1631. // CFGBlock(s).
  1632. SmallVector<VarDecl*, 10> Decls;
  1633. Decls.reserve(B.distance(E));
  1634. for (LocalScope::const_iterator I = B; I != E; ++I)
  1635. Decls.push_back(*I);
  1636. for (VarDecl *VD : llvm::reverse(Decls)) {
  1637. if (hasTrivialDestructor(VD)) {
  1638. // If AddScopes is enabled and *I is a first variable in a scope, add a
  1639. // ScopeEnd marker in a Block.
  1640. if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) {
  1641. autoCreateBlock();
  1642. appendScopeEnd(Block, VD, S);
  1643. }
  1644. continue;
  1645. }
  1646. // If this destructor is marked as a no-return destructor, we need to
  1647. // create a new block for the destructor which does not have as a successor
  1648. // anything built thus far: control won't flow out of this block.
  1649. QualType Ty = VD->getType();
  1650. if (Ty->isReferenceType()) {
  1651. Ty = getReferenceInitTemporaryType(VD->getInit());
  1652. }
  1653. Ty = Context->getBaseElementType(Ty);
  1654. if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
  1655. Block = createNoReturnBlock();
  1656. else
  1657. autoCreateBlock();
  1658. // Add ScopeEnd just after automatic obj destructor.
  1659. if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD))
  1660. appendScopeEnd(Block, VD, S);
  1661. appendAutomaticObjDtor(Block, VD, S);
  1662. }
  1663. }
  1664. /// addImplicitDtorsForDestructor - Add implicit destructors generated for
  1665. /// base and member objects in destructor.
  1666. void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
  1667. assert(BuildOpts.AddImplicitDtors &&
  1668. "Can be called only when dtors should be added");
  1669. const CXXRecordDecl *RD = DD->getParent();
  1670. // At the end destroy virtual base objects.
  1671. for (const auto &VI : RD->vbases()) {
  1672. // TODO: Add a VirtualBaseBranch to see if the most derived class
  1673. // (which is different from the current class) is responsible for
  1674. // destroying them.
  1675. const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
  1676. if (CD && !CD->hasTrivialDestructor()) {
  1677. autoCreateBlock();
  1678. appendBaseDtor(Block, &VI);
  1679. }
  1680. }
  1681. // Before virtual bases destroy direct base objects.
  1682. for (const auto &BI : RD->bases()) {
  1683. if (!BI.isVirtual()) {
  1684. const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
  1685. if (CD && !CD->hasTrivialDestructor()) {
  1686. autoCreateBlock();
  1687. appendBaseDtor(Block, &BI);
  1688. }
  1689. }
  1690. }
  1691. // First destroy member objects.
  1692. for (auto *FI : RD->fields()) {
  1693. // Check for constant size array. Set type to array element type.
  1694. QualType QT = FI->getType();
  1695. // It may be a multidimensional array.
  1696. while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  1697. if (AT->getSize() == 0)
  1698. break;
  1699. QT = AT->getElementType();
  1700. }
  1701. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  1702. if (!CD->hasTrivialDestructor()) {
  1703. autoCreateBlock();
  1704. appendMemberDtor(Block, FI);
  1705. }
  1706. }
  1707. }
  1708. /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
  1709. /// way return valid LocalScope object.
  1710. LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
  1711. if (Scope)
  1712. return Scope;
  1713. llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
  1714. return new (alloc.Allocate<LocalScope>())
  1715. LocalScope(BumpVectorContext(alloc), ScopePos);
  1716. }
  1717. /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
  1718. /// that should create implicit scope (e.g. if/else substatements).
  1719. void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
  1720. if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
  1721. !BuildOpts.AddScopes)
  1722. return;
  1723. LocalScope *Scope = nullptr;
  1724. // For compound statement we will be creating explicit scope.
  1725. if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
  1726. for (auto *BI : CS->body()) {
  1727. Stmt *SI = BI->stripLabelLikeStatements();
  1728. if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
  1729. Scope = addLocalScopeForDeclStmt(DS, Scope);
  1730. }
  1731. return;
  1732. }
  1733. // For any other statement scope will be implicit and as such will be
  1734. // interesting only for DeclStmt.
  1735. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
  1736. addLocalScopeForDeclStmt(DS);
  1737. }
  1738. /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
  1739. /// reuse Scope if not NULL.
  1740. LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
  1741. LocalScope* Scope) {
  1742. if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
  1743. !BuildOpts.AddScopes)
  1744. return Scope;
  1745. for (auto *DI : DS->decls())
  1746. if (VarDecl *VD = dyn_cast<VarDecl>(DI))
  1747. Scope = addLocalScopeForVarDecl(VD, Scope);
  1748. return Scope;
  1749. }
  1750. bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
  1751. // Check for const references bound to temporary. Set type to pointee.
  1752. QualType QT = VD->getType();
  1753. if (QT->isReferenceType()) {
  1754. // Attempt to determine whether this declaration lifetime-extends a
  1755. // temporary.
  1756. //
  1757. // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
  1758. // temporaries, and a single declaration can extend multiple temporaries.
  1759. // We should look at the storage duration on each nested
  1760. // MaterializeTemporaryExpr instead.
  1761. const Expr *Init = VD->getInit();
  1762. if (!Init) {
  1763. // Probably an exception catch-by-reference variable.
  1764. // FIXME: It doesn't really mean that the object has a trivial destructor.
  1765. // Also are there other cases?
  1766. return true;
  1767. }
  1768. // Lifetime-extending a temporary?
  1769. bool FoundMTE = false;
  1770. QT = getReferenceInitTemporaryType(Init, &FoundMTE);
  1771. if (!FoundMTE)
  1772. return true;
  1773. }
  1774. // Check for constant size array. Set type to array element type.
  1775. while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
  1776. if (AT->getSize() == 0)
  1777. return true;
  1778. QT = AT->getElementType();
  1779. }
  1780. // Check if type is a C++ class with non-trivial destructor.
  1781. if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
  1782. return !CD->hasDefinition() || CD->hasTrivialDestructor();
  1783. return true;
  1784. }
  1785. /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
  1786. /// create add scope for automatic objects and temporary objects bound to
  1787. /// const reference. Will reuse Scope if not NULL.
  1788. LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
  1789. LocalScope* Scope) {
  1790. assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
  1791. "AddImplicitDtors and AddLifetime cannot be used at the same time");
  1792. if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
  1793. !BuildOpts.AddScopes)
  1794. return Scope;
  1795. // Check if variable is local.
  1796. if (!VD->hasLocalStorage())
  1797. return Scope;
  1798. if (BuildOpts.AddImplicitDtors) {
  1799. if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
  1800. // Add the variable to scope
  1801. Scope = createOrReuseLocalScope(Scope);
  1802. Scope->addVar(VD);
  1803. ScopePos = Scope->begin();
  1804. }
  1805. return Scope;
  1806. }
  1807. assert(BuildOpts.AddLifetime);
  1808. // Add the variable to scope
  1809. Scope = createOrReuseLocalScope(Scope);
  1810. Scope->addVar(VD);
  1811. ScopePos = Scope->begin();
  1812. return Scope;
  1813. }
  1814. /// addLocalScopeAndDtors - For given statement add local scope for it and
  1815. /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
  1816. void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
  1817. LocalScope::const_iterator scopeBeginPos = ScopePos;
  1818. addLocalScopeForStmt(S);
  1819. addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
  1820. }
  1821. /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
  1822. /// variables with automatic storage duration to CFGBlock's elements vector.
  1823. /// Elements will be prepended to physical beginning of the vector which
  1824. /// happens to be logical end. Use blocks terminator as statement that specifies
  1825. /// destructors call site.
  1826. /// FIXME: This mechanism for adding automatic destructors doesn't handle
  1827. /// no-return destructors properly.
  1828. void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
  1829. LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1830. if (!BuildOpts.AddImplicitDtors)
  1831. return;
  1832. BumpVectorContext &C = cfg->getBumpVectorContext();
  1833. CFGBlock::iterator InsertPos
  1834. = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
  1835. for (LocalScope::const_iterator I = B; I != E; ++I)
  1836. InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
  1837. Blk->getTerminatorStmt());
  1838. }
  1839. /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
  1840. /// variables with automatic storage duration to CFGBlock's elements vector.
  1841. /// Elements will be prepended to physical beginning of the vector which
  1842. /// happens to be logical end. Use blocks terminator as statement that specifies
  1843. /// where lifetime ends.
  1844. void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
  1845. CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1846. if (!BuildOpts.AddLifetime)
  1847. return;
  1848. BumpVectorContext &C = cfg->getBumpVectorContext();
  1849. CFGBlock::iterator InsertPos =
  1850. Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
  1851. for (LocalScope::const_iterator I = B; I != E; ++I) {
  1852. InsertPos =
  1853. Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
  1854. }
  1855. }
  1856. /// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
  1857. /// variables with automatic storage duration to CFGBlock's elements vector.
  1858. /// Elements will be prepended to physical beginning of the vector which
  1859. /// happens to be logical end. Use blocks terminator as statement that specifies
  1860. /// where scope ends.
  1861. const VarDecl *
  1862. CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
  1863. CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
  1864. if (!BuildOpts.AddScopes)
  1865. return nullptr;
  1866. BumpVectorContext &C = cfg->getBumpVectorContext();
  1867. CFGBlock::iterator InsertPos =
  1868. Blk->beginScopeEndInsert(Blk->end(), 1, C);
  1869. LocalScope::const_iterator PlaceToInsert = B;
  1870. for (LocalScope::const_iterator I = B; I != E; ++I)
  1871. PlaceToInsert = I;
  1872. Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
  1873. return *PlaceToInsert;
  1874. }
  1875. /// Visit - Walk the subtree of a statement and add extra
  1876. /// blocks for ternary operators, &&, and ||. We also process "," and
  1877. /// DeclStmts (which may contain nested control-flow).
  1878. CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
  1879. bool ExternallyDestructed) {
  1880. if (!S) {
  1881. badCFG = true;
  1882. return nullptr;
  1883. }
  1884. if (Expr *E = dyn_cast<Expr>(S))
  1885. S = E->IgnoreParens();
  1886. if (Context->getLangOpts().OpenMP)
  1887. if (auto *D = dyn_cast<OMPExecutableDirective>(S))
  1888. return VisitOMPExecutableDirective(D, asc);
  1889. switch (S->getStmtClass()) {
  1890. default:
  1891. return VisitStmt(S, asc);
  1892. case Stmt::ImplicitValueInitExprClass:
  1893. if (BuildOpts.OmitImplicitValueInitializers)
  1894. return Block;
  1895. return VisitStmt(S, asc);
  1896. case Stmt::InitListExprClass:
  1897. return VisitInitListExpr(cast<InitListExpr>(S), asc);
  1898. case Stmt::AttributedStmtClass:
  1899. return VisitAttributedStmt(cast<AttributedStmt>(S), asc);
  1900. case Stmt::AddrLabelExprClass:
  1901. return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
  1902. case Stmt::BinaryConditionalOperatorClass:
  1903. return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
  1904. case Stmt::BinaryOperatorClass:
  1905. return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
  1906. case Stmt::BlockExprClass:
  1907. return VisitBlockExpr(cast<BlockExpr>(S), asc);
  1908. case Stmt::BreakStmtClass:
  1909. return VisitBreakStmt(cast<BreakStmt>(S));
  1910. case Stmt::CallExprClass:
  1911. case Stmt::CXXOperatorCallExprClass:
  1912. case Stmt::CXXMemberCallExprClass:
  1913. case Stmt::UserDefinedLiteralClass:
  1914. return VisitCallExpr(cast<CallExpr>(S), asc);
  1915. case Stmt::CaseStmtClass:
  1916. return VisitCaseStmt(cast<CaseStmt>(S));
  1917. case Stmt::ChooseExprClass:
  1918. return VisitChooseExpr(cast<ChooseExpr>(S), asc);
  1919. case Stmt::CompoundStmtClass:
  1920. return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
  1921. case Stmt::ConditionalOperatorClass:
  1922. return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
  1923. case Stmt::ContinueStmtClass:
  1924. return VisitContinueStmt(cast<ContinueStmt>(S));
  1925. case Stmt::CXXCatchStmtClass:
  1926. return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
  1927. case Stmt::ExprWithCleanupsClass:
  1928. return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
  1929. asc, ExternallyDestructed);
  1930. case Stmt::CXXDefaultArgExprClass:
  1931. case Stmt::CXXDefaultInitExprClass:
  1932. // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
  1933. // called function's declaration, not by the caller. If we simply add
  1934. // this expression to the CFG, we could end up with the same Expr
  1935. // appearing multiple times.
  1936. // PR13385 / <rdar://problem/12156507>
  1937. //
  1938. // It's likewise possible for multiple CXXDefaultInitExprs for the same
  1939. // expression to be used in the same function (through aggregate
  1940. // initialization).
  1941. return VisitStmt(S, asc);
  1942. case Stmt::CXXBindTemporaryExprClass:
  1943. return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
  1944. case Stmt::CXXConstructExprClass:
  1945. return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
  1946. case Stmt::CXXNewExprClass:
  1947. return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
  1948. case Stmt::CXXDeleteExprClass:
  1949. return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
  1950. case Stmt::CXXFunctionalCastExprClass:
  1951. return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
  1952. case Stmt::CXXTemporaryObjectExprClass:
  1953. return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
  1954. case Stmt::CXXThrowExprClass:
  1955. return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
  1956. case Stmt::CXXTryStmtClass:
  1957. return VisitCXXTryStmt(cast<CXXTryStmt>(S));
  1958. case Stmt::CXXTypeidExprClass:
  1959. return VisitCXXTypeidExpr(cast<CXXTypeidExpr>(S), asc);
  1960. case Stmt::CXXForRangeStmtClass:
  1961. return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
  1962. case Stmt::DeclStmtClass:
  1963. return VisitDeclStmt(cast<DeclStmt>(S));
  1964. case Stmt::DefaultStmtClass:
  1965. return VisitDefaultStmt(cast<DefaultStmt>(S));
  1966. case Stmt::DoStmtClass:
  1967. return VisitDoStmt(cast<DoStmt>(S));
  1968. case Stmt::ForStmtClass:
  1969. return VisitForStmt(cast<ForStmt>(S));
  1970. case Stmt::GotoStmtClass:
  1971. return VisitGotoStmt(cast<GotoStmt>(S));
  1972. case Stmt::GCCAsmStmtClass:
  1973. return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
  1974. case Stmt::IfStmtClass:
  1975. return VisitIfStmt(cast<IfStmt>(S));
  1976. case Stmt::ImplicitCastExprClass:
  1977. return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
  1978. case Stmt::ConstantExprClass:
  1979. return VisitConstantExpr(cast<ConstantExpr>(S), asc);
  1980. case Stmt::IndirectGotoStmtClass:
  1981. return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
  1982. case Stmt::LabelStmtClass:
  1983. return VisitLabelStmt(cast<LabelStmt>(S));
  1984. case Stmt::LambdaExprClass:
  1985. return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
  1986. case Stmt::MaterializeTemporaryExprClass:
  1987. return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
  1988. asc);
  1989. case Stmt::MemberExprClass:
  1990. return VisitMemberExpr(cast<MemberExpr>(S), asc);
  1991. case Stmt::NullStmtClass:
  1992. return Block;
  1993. case Stmt::ObjCAtCatchStmtClass:
  1994. return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
  1995. case Stmt::ObjCAutoreleasePoolStmtClass:
  1996. return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
  1997. case Stmt::ObjCAtSynchronizedStmtClass:
  1998. return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
  1999. case Stmt::ObjCAtThrowStmtClass:
  2000. return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
  2001. case Stmt::ObjCAtTryStmtClass:
  2002. return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
  2003. case Stmt::ObjCForCollectionStmtClass:
  2004. return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
  2005. case Stmt::ObjCMessageExprClass:
  2006. return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
  2007. case Stmt::OpaqueValueExprClass:
  2008. return Block;
  2009. case Stmt::PseudoObjectExprClass:
  2010. return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
  2011. case Stmt::ReturnStmtClass:
  2012. case Stmt::CoreturnStmtClass:
  2013. return VisitReturnStmt(S);
  2014. case Stmt::CoyieldExprClass:
  2015. case Stmt::CoawaitExprClass:
  2016. return VisitCoroutineSuspendExpr(cast<CoroutineSuspendExpr>(S), asc);
  2017. case Stmt::SEHExceptStmtClass:
  2018. return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
  2019. case Stmt::SEHFinallyStmtClass:
  2020. return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
  2021. case Stmt::SEHLeaveStmtClass:
  2022. return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
  2023. case Stmt::SEHTryStmtClass:
  2024. return VisitSEHTryStmt(cast<SEHTryStmt>(S));
  2025. case Stmt::UnaryExprOrTypeTraitExprClass:
  2026. return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  2027. asc);
  2028. case Stmt::StmtExprClass:
  2029. return VisitStmtExpr(cast<StmtExpr>(S), asc);
  2030. case Stmt::SwitchStmtClass:
  2031. return VisitSwitchStmt(cast<SwitchStmt>(S));
  2032. case Stmt::UnaryOperatorClass:
  2033. return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
  2034. case Stmt::WhileStmtClass:
  2035. return VisitWhileStmt(cast<WhileStmt>(S));
  2036. case Stmt::ArrayInitLoopExprClass:
  2037. return VisitArrayInitLoopExpr(cast<ArrayInitLoopExpr>(S), asc);
  2038. }
  2039. }
  2040. CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
  2041. if (asc.alwaysAdd(*this, S)) {
  2042. autoCreateBlock();
  2043. appendStmt(Block, S);
  2044. }
  2045. return VisitChildren(S);
  2046. }
  2047. /// VisitChildren - Visit the children of a Stmt.
  2048. CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
  2049. CFGBlock *B = Block;
  2050. // Visit the children in their reverse order so that they appear in
  2051. // left-to-right (natural) order in the CFG.
  2052. reverse_children RChildren(S);
  2053. for (Stmt *Child : RChildren) {
  2054. if (Child)
  2055. if (CFGBlock *R = Visit(Child))
  2056. B = R;
  2057. }
  2058. return B;
  2059. }
  2060. CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
  2061. if (asc.alwaysAdd(*this, ILE)) {
  2062. autoCreateBlock();
  2063. appendStmt(Block, ILE);
  2064. }
  2065. CFGBlock *B = Block;
  2066. reverse_children RChildren(ILE);
  2067. for (Stmt *Child : RChildren) {
  2068. if (!Child)
  2069. continue;
  2070. if (CFGBlock *R = Visit(Child))
  2071. B = R;
  2072. if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
  2073. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child))
  2074. if (Stmt *Child = DIE->getExpr())
  2075. if (CFGBlock *R = Visit(Child))
  2076. B = R;
  2077. }
  2078. }
  2079. return B;
  2080. }
  2081. CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
  2082. AddStmtChoice asc) {
  2083. AddressTakenLabels.insert(A->getLabel());
  2084. if (asc.alwaysAdd(*this, A)) {
  2085. autoCreateBlock();
  2086. appendStmt(Block, A);
  2087. }
  2088. return Block;
  2089. }
  2090. static bool isFallthroughStatement(const AttributedStmt *A) {
  2091. bool isFallthrough = hasSpecificAttr<FallThroughAttr>(A->getAttrs());
  2092. assert((!isFallthrough || isa<NullStmt>(A->getSubStmt())) &&
  2093. "expected fallthrough not to have children");
  2094. return isFallthrough;
  2095. }
  2096. CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
  2097. AddStmtChoice asc) {
  2098. // AttributedStmts for [[likely]] can have arbitrary statements as children,
  2099. // and the current visitation order here would add the AttributedStmts
  2100. // for [[likely]] after the child nodes, which is undesirable: For example,
  2101. // if the child contains an unconditional return, the [[likely]] would be
  2102. // considered unreachable.
  2103. // So only add the AttributedStmt for FallThrough, which has CFG effects and
  2104. // also no children, and omit the others. None of the other current StmtAttrs
  2105. // have semantic meaning for the CFG.
  2106. if (isFallthroughStatement(A) && asc.alwaysAdd(*this, A)) {
  2107. autoCreateBlock();
  2108. appendStmt(Block, A);
  2109. }
  2110. return VisitChildren(A);
  2111. }
  2112. CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) {
  2113. if (asc.alwaysAdd(*this, U)) {
  2114. autoCreateBlock();
  2115. appendStmt(Block, U);
  2116. }
  2117. if (U->getOpcode() == UO_LNot)
  2118. tryEvaluateBool(U->getSubExpr()->IgnoreParens());
  2119. return Visit(U->getSubExpr(), AddStmtChoice());
  2120. }
  2121. CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
  2122. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  2123. appendStmt(ConfluenceBlock, B);
  2124. if (badCFG)
  2125. return nullptr;
  2126. return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
  2127. ConfluenceBlock).first;
  2128. }
  2129. std::pair<CFGBlock*, CFGBlock*>
  2130. CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
  2131. Stmt *Term,
  2132. CFGBlock *TrueBlock,
  2133. CFGBlock *FalseBlock) {
  2134. // Introspect the RHS. If it is a nested logical operation, we recursively
  2135. // build the CFG using this function. Otherwise, resort to default
  2136. // CFG construction behavior.
  2137. Expr *RHS = B->getRHS()->IgnoreParens();
  2138. CFGBlock *RHSBlock, *ExitBlock;
  2139. do {
  2140. if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
  2141. if (B_RHS->isLogicalOp()) {
  2142. std::tie(RHSBlock, ExitBlock) =
  2143. VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
  2144. break;
  2145. }
  2146. // The RHS is not a nested logical operation. Don't push the terminator
  2147. // down further, but instead visit RHS and construct the respective
  2148. // pieces of the CFG, and link up the RHSBlock with the terminator
  2149. // we have been provided.
  2150. ExitBlock = RHSBlock = createBlock(false);
  2151. // Even though KnownVal is only used in the else branch of the next
  2152. // conditional, tryEvaluateBool performs additional checking on the
  2153. // Expr, so it should be called unconditionally.
  2154. TryResult KnownVal = tryEvaluateBool(RHS);
  2155. if (!KnownVal.isKnown())
  2156. KnownVal = tryEvaluateBool(B);
  2157. if (!Term) {
  2158. assert(TrueBlock == FalseBlock);
  2159. addSuccessor(RHSBlock, TrueBlock);
  2160. }
  2161. else {
  2162. RHSBlock->setTerminator(Term);
  2163. addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
  2164. addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
  2165. }
  2166. Block = RHSBlock;
  2167. RHSBlock = addStmt(RHS);
  2168. }
  2169. while (false);
  2170. if (badCFG)
  2171. return std::make_pair(nullptr, nullptr);
  2172. // Generate the blocks for evaluating the LHS.
  2173. Expr *LHS = B->getLHS()->IgnoreParens();
  2174. if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
  2175. if (B_LHS->isLogicalOp()) {
  2176. if (B->getOpcode() == BO_LOr)
  2177. FalseBlock = RHSBlock;
  2178. else
  2179. TrueBlock = RHSBlock;
  2180. // For the LHS, treat 'B' as the terminator that we want to sink
  2181. // into the nested branch. The RHS always gets the top-most
  2182. // terminator.
  2183. return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
  2184. }
  2185. // Create the block evaluating the LHS.
  2186. // This contains the '&&' or '||' as the terminator.
  2187. CFGBlock *LHSBlock = createBlock(false);
  2188. LHSBlock->setTerminator(B);
  2189. Block = LHSBlock;
  2190. CFGBlock *EntryLHSBlock = addStmt(LHS);
  2191. if (badCFG)
  2192. return std::make_pair(nullptr, nullptr);
  2193. // See if this is a known constant.
  2194. TryResult KnownVal = tryEvaluateBool(LHS);
  2195. // Now link the LHSBlock with RHSBlock.
  2196. if (B->getOpcode() == BO_LOr) {
  2197. addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
  2198. addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
  2199. } else {
  2200. assert(B->getOpcode() == BO_LAnd);
  2201. addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
  2202. addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
  2203. }
  2204. return std::make_pair(EntryLHSBlock, ExitBlock);
  2205. }
  2206. CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
  2207. AddStmtChoice asc) {
  2208. // && or ||
  2209. if (B->isLogicalOp())
  2210. return VisitLogicalOperator(B);
  2211. if (B->getOpcode() == BO_Comma) { // ,
  2212. autoCreateBlock();
  2213. appendStmt(Block, B);
  2214. addStmt(B->getRHS());
  2215. return addStmt(B->getLHS());
  2216. }
  2217. if (B->isAssignmentOp()) {
  2218. if (asc.alwaysAdd(*this, B)) {
  2219. autoCreateBlock();
  2220. appendStmt(Block, B);
  2221. }
  2222. Visit(B->getLHS());
  2223. return Visit(B->getRHS());
  2224. }
  2225. if (asc.alwaysAdd(*this, B)) {
  2226. autoCreateBlock();
  2227. appendStmt(Block, B);
  2228. }
  2229. if (B->isEqualityOp() || B->isRelationalOp())
  2230. tryEvaluateBool(B);
  2231. CFGBlock *RBlock = Visit(B->getRHS());
  2232. CFGBlock *LBlock = Visit(B->getLHS());
  2233. // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
  2234. // containing a DoStmt, and the LHS doesn't create a new block, then we should
  2235. // return RBlock. Otherwise we'll incorrectly return NULL.
  2236. return (LBlock ? LBlock : RBlock);
  2237. }
  2238. CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
  2239. if (asc.alwaysAdd(*this, E)) {
  2240. autoCreateBlock();
  2241. appendStmt(Block, E);
  2242. }
  2243. return Block;
  2244. }
  2245. CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
  2246. // "break" is a control-flow statement. Thus we stop processing the current
  2247. // block.
  2248. if (badCFG)
  2249. return nullptr;
  2250. // Now create a new block that ends with the break statement.
  2251. Block = createBlock(false);
  2252. Block->setTerminator(B);
  2253. // If there is no target for the break, then we are looking at an incomplete
  2254. // AST. This means that the CFG cannot be constructed.
  2255. if (BreakJumpTarget.block) {
  2256. addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
  2257. addSuccessor(Block, BreakJumpTarget.block);
  2258. } else
  2259. badCFG = true;
  2260. return Block;
  2261. }
  2262. static bool CanThrow(Expr *E, ASTContext &Ctx) {
  2263. QualType Ty = E->getType();
  2264. if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
  2265. Ty = Ty->getPointeeType();
  2266. const FunctionType *FT = Ty->getAs<FunctionType>();
  2267. if (FT) {
  2268. if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
  2269. if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
  2270. Proto->isNothrow())
  2271. return false;
  2272. }
  2273. return true;
  2274. }
  2275. CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
  2276. // Compute the callee type.
  2277. QualType calleeType = C->getCallee()->getType();
  2278. if (calleeType == Context->BoundMemberTy) {
  2279. QualType boundType = Expr::findBoundMemberType(C->getCallee());
  2280. // We should only get a null bound type if processing a dependent
  2281. // CFG. Recover by assuming nothing.
  2282. if (!boundType.isNull()) calleeType = boundType;
  2283. }
  2284. // If this is a call to a no-return function, this stops the block here.
  2285. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
  2286. bool AddEHEdge = false;
  2287. // Languages without exceptions are assumed to not throw.
  2288. if (Context->getLangOpts().Exceptions) {
  2289. if (BuildOpts.AddEHEdges)
  2290. AddEHEdge = true;
  2291. }
  2292. // If this is a call to a builtin function, it might not actually evaluate
  2293. // its arguments. Don't add them to the CFG if this is the case.
  2294. bool OmitArguments = false;
  2295. if (FunctionDecl *FD = C->getDirectCallee()) {
  2296. // TODO: Support construction contexts for variadic function arguments.
  2297. // These are a bit problematic and not very useful because passing
  2298. // C++ objects as C-style variadic arguments doesn't work in general
  2299. // (see [expr.call]).
  2300. if (!FD->isVariadic())
  2301. findConstructionContextsForArguments(C);
  2302. if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
  2303. NoReturn = true;
  2304. if (FD->hasAttr<NoThrowAttr>())
  2305. AddEHEdge = false;
  2306. if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
  2307. FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
  2308. OmitArguments = true;
  2309. }
  2310. if (!CanThrow(C->getCallee(), *Context))
  2311. AddEHEdge = false;
  2312. if (OmitArguments) {
  2313. assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
  2314. assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
  2315. autoCreateBlock();
  2316. appendStmt(Block, C);
  2317. return Visit(C->getCallee());
  2318. }
  2319. if (!NoReturn && !AddEHEdge) {
  2320. autoCreateBlock();
  2321. appendCall(Block, C);
  2322. return VisitChildren(C);
  2323. }
  2324. if (Block) {
  2325. Succ = Block;
  2326. if (badCFG)
  2327. return nullptr;
  2328. }
  2329. if (NoReturn)
  2330. Block = createNoReturnBlock();
  2331. else
  2332. Block = createBlock();
  2333. appendCall(Block, C);
  2334. if (AddEHEdge) {
  2335. // Add exceptional edges.
  2336. if (TryTerminatedBlock)
  2337. addSuccessor(Block, TryTerminatedBlock);
  2338. else
  2339. addSuccessor(Block, &cfg->getExit());
  2340. }
  2341. return VisitChildren(C);
  2342. }
  2343. CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
  2344. AddStmtChoice asc) {
  2345. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  2346. appendStmt(ConfluenceBlock, C);
  2347. if (badCFG)
  2348. return nullptr;
  2349. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  2350. Succ = ConfluenceBlock;
  2351. Block = nullptr;
  2352. CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
  2353. if (badCFG)
  2354. return nullptr;
  2355. Succ = ConfluenceBlock;
  2356. Block = nullptr;
  2357. CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
  2358. if (badCFG)
  2359. return nullptr;
  2360. Block = createBlock(false);
  2361. // See if this is a known constant.
  2362. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  2363. addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
  2364. addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
  2365. Block->setTerminator(C);
  2366. return addStmt(C->getCond());
  2367. }
  2368. CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C,
  2369. bool ExternallyDestructed) {
  2370. LocalScope::const_iterator scopeBeginPos = ScopePos;
  2371. addLocalScopeForStmt(C);
  2372. if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
  2373. // If the body ends with a ReturnStmt, the dtors will be added in
  2374. // VisitReturnStmt.
  2375. addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
  2376. }
  2377. CFGBlock *LastBlock = Block;
  2378. for (Stmt *S : llvm::reverse(C->body())) {
  2379. // If we hit a segment of code just containing ';' (NullStmts), we can
  2380. // get a null block back. In such cases, just use the LastBlock
  2381. CFGBlock *newBlock = Visit(S, AddStmtChoice::AlwaysAdd,
  2382. ExternallyDestructed);
  2383. if (newBlock)
  2384. LastBlock = newBlock;
  2385. if (badCFG)
  2386. return nullptr;
  2387. ExternallyDestructed = false;
  2388. }
  2389. return LastBlock;
  2390. }
  2391. CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
  2392. AddStmtChoice asc) {
  2393. const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
  2394. const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
  2395. // Create the confluence block that will "merge" the results of the ternary
  2396. // expression.
  2397. CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
  2398. appendStmt(ConfluenceBlock, C);
  2399. if (badCFG)
  2400. return nullptr;
  2401. AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
  2402. // Create a block for the LHS expression if there is an LHS expression. A
  2403. // GCC extension allows LHS to be NULL, causing the condition to be the
  2404. // value that is returned instead.
  2405. // e.g: x ?: y is shorthand for: x ? x : y;
  2406. Succ = ConfluenceBlock;
  2407. Block = nullptr;
  2408. CFGBlock *LHSBlock = nullptr;
  2409. const Expr *trueExpr = C->getTrueExpr();
  2410. if (trueExpr != opaqueValue) {
  2411. LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
  2412. if (badCFG)
  2413. return nullptr;
  2414. Block = nullptr;
  2415. }
  2416. else
  2417. LHSBlock = ConfluenceBlock;
  2418. // Create the block for the RHS expression.
  2419. Succ = ConfluenceBlock;
  2420. CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
  2421. if (badCFG)
  2422. return nullptr;
  2423. // If the condition is a logical '&&' or '||', build a more accurate CFG.
  2424. if (BinaryOperator *Cond =
  2425. dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
  2426. if (Cond->isLogicalOp())
  2427. return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
  2428. // Create the block that will contain the condition.
  2429. Block = createBlock(false);
  2430. // See if this is a known constant.
  2431. const TryResult& KnownVal = tryEvaluateBool(C->getCond());
  2432. addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
  2433. addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
  2434. Block->setTerminator(C);
  2435. Expr *condExpr = C->getCond();
  2436. if (opaqueValue) {
  2437. // Run the condition expression if it's not trivially expressed in
  2438. // terms of the opaque value (or if there is no opaque value).
  2439. if (condExpr != opaqueValue)
  2440. addStmt(condExpr);
  2441. // Before that, run the common subexpression if there was one.
  2442. // At least one of this or the above will be run.
  2443. return addStmt(BCO->getCommon());
  2444. }
  2445. return addStmt(condExpr);
  2446. }
  2447. CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
  2448. // Check if the Decl is for an __label__. If so, elide it from the
  2449. // CFG entirely.
  2450. if (isa<LabelDecl>(*DS->decl_begin()))
  2451. return Block;
  2452. // This case also handles static_asserts.
  2453. if (DS->isSingleDecl())
  2454. return VisitDeclSubExpr(DS);
  2455. CFGBlock *B = nullptr;
  2456. // Build an individual DeclStmt for each decl.
  2457. for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
  2458. E = DS->decl_rend();
  2459. I != E; ++I) {
  2460. // Allocate the DeclStmt using the BumpPtrAllocator. It will get
  2461. // automatically freed with the CFG.
  2462. DeclGroupRef DG(*I);
  2463. Decl *D = *I;
  2464. DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
  2465. cfg->addSyntheticDeclStmt(DSNew, DS);
  2466. // Append the fake DeclStmt to block.
  2467. B = VisitDeclSubExpr(DSNew);
  2468. }
  2469. return B;
  2470. }
  2471. /// VisitDeclSubExpr - Utility method to add block-level expressions for
  2472. /// DeclStmts and initializers in them.
  2473. CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
  2474. assert(DS->isSingleDecl() && "Can handle single declarations only.");
  2475. if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl())) {
  2476. // If we encounter a VLA, process its size expressions.
  2477. const Type *T = TND->getUnderlyingType().getTypePtr();
  2478. if (!T->isVariablyModifiedType())
  2479. return Block;
  2480. autoCreateBlock();
  2481. appendStmt(Block, DS);
  2482. CFGBlock *LastBlock = Block;
  2483. for (const VariableArrayType *VA = FindVA(T); VA != nullptr;
  2484. VA = FindVA(VA->getElementType().getTypePtr())) {
  2485. if (CFGBlock *NewBlock = addStmt(VA->getSizeExpr()))
  2486. LastBlock = NewBlock;
  2487. }
  2488. return LastBlock;
  2489. }
  2490. VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  2491. if (!VD) {
  2492. // Of everything that can be declared in a DeclStmt, only VarDecls and the
  2493. // exceptions above impact runtime semantics.
  2494. return Block;
  2495. }
  2496. bool HasTemporaries = false;
  2497. // Guard static initializers under a branch.
  2498. CFGBlock *blockAfterStaticInit = nullptr;
  2499. if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
  2500. // For static variables, we need to create a branch to track
  2501. // whether or not they are initialized.
  2502. if (Block) {
  2503. Succ = Block;
  2504. Block = nullptr;
  2505. if (badCFG)
  2506. return nullptr;
  2507. }
  2508. blockAfterStaticInit = Succ;
  2509. }
  2510. // Destructors of temporaries in initialization expression should be called
  2511. // after initialization finishes.
  2512. Expr *Init = VD->getInit();
  2513. if (Init) {
  2514. HasTemporaries = isa<ExprWithCleanups>(Init);
  2515. if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
  2516. // Generate destructors for temporaries in initialization expression.
  2517. TempDtorContext Context;
  2518. VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
  2519. /*ExternallyDestructed=*/true, Context);
  2520. }
  2521. }
  2522. // If we bind to a tuple-like type, we iterate over the HoldingVars, and
  2523. // create a DeclStmt for each of them.
  2524. if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
  2525. for (auto *BD : llvm::reverse(DD->bindings())) {
  2526. if (auto *VD = BD->getHoldingVar()) {
  2527. DeclGroupRef DG(VD);
  2528. DeclStmt *DSNew =
  2529. new (Context) DeclStmt(DG, VD->getLocation(), GetEndLoc(VD));
  2530. cfg->addSyntheticDeclStmt(DSNew, DS);
  2531. Block = VisitDeclSubExpr(DSNew);
  2532. }
  2533. }
  2534. }
  2535. autoCreateBlock();
  2536. appendStmt(Block, DS);
  2537. // If the initializer is an ArrayInitLoopExpr, we want to extract the
  2538. // initializer, that's used for each element.
  2539. const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init);
  2540. findConstructionContexts(
  2541. ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
  2542. AILE ? AILE->getSubExpr() : Init);
  2543. // Keep track of the last non-null block, as 'Block' can be nulled out
  2544. // if the initializer expression is something like a 'while' in a
  2545. // statement-expression.
  2546. CFGBlock *LastBlock = Block;
  2547. if (Init) {
  2548. if (HasTemporaries) {
  2549. // For expression with temporaries go directly to subexpression to omit
  2550. // generating destructors for the second time.
  2551. ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
  2552. if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
  2553. LastBlock = newBlock;
  2554. }
  2555. else {
  2556. if (CFGBlock *newBlock = Visit(Init))
  2557. LastBlock = newBlock;
  2558. }
  2559. }
  2560. // If the type of VD is a VLA, then we must process its size expressions.
  2561. // FIXME: This does not find the VLA if it is embedded in other types,
  2562. // like here: `int (*p_vla)[x];`
  2563. for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
  2564. VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
  2565. if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
  2566. LastBlock = newBlock;
  2567. }
  2568. maybeAddScopeBeginForVarDecl(Block, VD, DS);
  2569. // Remove variable from local scope.
  2570. if (ScopePos && VD == *ScopePos)
  2571. ++ScopePos;
  2572. CFGBlock *B = LastBlock;
  2573. if (blockAfterStaticInit) {
  2574. Succ = B;
  2575. Block = createBlock(false);
  2576. Block->setTerminator(DS);
  2577. addSuccessor(Block, blockAfterStaticInit);
  2578. addSuccessor(Block, B);
  2579. B = Block;
  2580. }
  2581. return B;
  2582. }
  2583. CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
  2584. // We may see an if statement in the middle of a basic block, or it may be the
  2585. // first statement we are processing. In either case, we create a new basic
  2586. // block. First, we create the blocks for the then...else statements, and
  2587. // then we create the block containing the if statement. If we were in the
  2588. // middle of a block, we stop processing that block. That block is then the
  2589. // implicit successor for the "then" and "else" clauses.
  2590. // Save local scope position because in case of condition variable ScopePos
  2591. // won't be restored when traversing AST.
  2592. SaveAndRestore save_scope_pos(ScopePos);
  2593. // Create local scope for C++17 if init-stmt if one exists.
  2594. if (Stmt *Init = I->getInit())
  2595. addLocalScopeForStmt(Init);
  2596. // Create local scope for possible condition variable.
  2597. // Store scope position. Add implicit destructor.
  2598. if (VarDecl *VD = I->getConditionVariable())
  2599. addLocalScopeForVarDecl(VD);
  2600. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
  2601. // The block we were processing is now finished. Make it the successor
  2602. // block.
  2603. if (Block) {
  2604. Succ = Block;
  2605. if (badCFG)
  2606. return nullptr;
  2607. }
  2608. // Process the false branch.
  2609. CFGBlock *ElseBlock = Succ;
  2610. if (Stmt *Else = I->getElse()) {
  2611. SaveAndRestore sv(Succ);
  2612. // NULL out Block so that the recursive call to Visit will
  2613. // create a new basic block.
  2614. Block = nullptr;
  2615. // If branch is not a compound statement create implicit scope
  2616. // and add destructors.
  2617. if (!isa<CompoundStmt>(Else))
  2618. addLocalScopeAndDtors(Else);
  2619. ElseBlock = addStmt(Else);
  2620. if (!ElseBlock) // Can occur when the Else body has all NullStmts.
  2621. ElseBlock = sv.get();
  2622. else if (Block) {
  2623. if (badCFG)
  2624. return nullptr;
  2625. }
  2626. }
  2627. // Process the true branch.
  2628. CFGBlock *ThenBlock;
  2629. {
  2630. Stmt *Then = I->getThen();
  2631. assert(Then);
  2632. SaveAndRestore sv(Succ);
  2633. Block = nullptr;
  2634. // If branch is not a compound statement create implicit scope
  2635. // and add destructors.
  2636. if (!isa<CompoundStmt>(Then))
  2637. addLocalScopeAndDtors(Then);
  2638. ThenBlock = addStmt(Then);
  2639. if (!ThenBlock) {
  2640. // We can reach here if the "then" body has all NullStmts.
  2641. // Create an empty block so we can distinguish between true and false
  2642. // branches in path-sensitive analyses.
  2643. ThenBlock = createBlock(false);
  2644. addSuccessor(ThenBlock, sv.get());
  2645. } else if (Block) {
  2646. if (badCFG)
  2647. return nullptr;
  2648. }
  2649. }
  2650. // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
  2651. // having these handle the actual control-flow jump. Note that
  2652. // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
  2653. // we resort to the old control-flow behavior. This special handling
  2654. // removes infeasible paths from the control-flow graph by having the
  2655. // control-flow transfer of '&&' or '||' go directly into the then/else
  2656. // blocks directly.
  2657. BinaryOperator *Cond =
  2658. (I->isConsteval() || I->getConditionVariable())
  2659. ? nullptr
  2660. : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
  2661. CFGBlock *LastBlock;
  2662. if (Cond && Cond->isLogicalOp())
  2663. LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
  2664. else {
  2665. // Now create a new block containing the if statement.
  2666. Block = createBlock(false);
  2667. // Set the terminator of the new block to the If statement.
  2668. Block->setTerminator(I);
  2669. // See if this is a known constant.
  2670. TryResult KnownVal;
  2671. if (!I->isConsteval())
  2672. KnownVal = tryEvaluateBool(I->getCond());
  2673. // Add the successors. If we know that specific branches are
  2674. // unreachable, inform addSuccessor() of that knowledge.
  2675. addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
  2676. addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
  2677. // Add the condition as the last statement in the new block. This may
  2678. // create new blocks as the condition may contain control-flow. Any newly
  2679. // created blocks will be pointed to be "Block".
  2680. LastBlock = addStmt(I->getCond());
  2681. // If the IfStmt contains a condition variable, add it and its
  2682. // initializer to the CFG.
  2683. if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
  2684. autoCreateBlock();
  2685. LastBlock = addStmt(const_cast<DeclStmt *>(DS));
  2686. }
  2687. }
  2688. // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
  2689. if (Stmt *Init = I->getInit()) {
  2690. autoCreateBlock();
  2691. LastBlock = addStmt(Init);
  2692. }
  2693. return LastBlock;
  2694. }
  2695. CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
  2696. // If we were in the middle of a block we stop processing that block.
  2697. //
  2698. // NOTE: If a "return" or "co_return" appears in the middle of a block, this
  2699. // means that the code afterwards is DEAD (unreachable). We still keep
  2700. // a basic block for that code; a simple "mark-and-sweep" from the entry
  2701. // block will be able to report such dead blocks.
  2702. assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
  2703. // Create the new block.
  2704. Block = createBlock(false);
  2705. addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
  2706. if (auto *R = dyn_cast<ReturnStmt>(S))
  2707. findConstructionContexts(
  2708. ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
  2709. R->getRetValue());
  2710. // If the one of the destructors does not return, we already have the Exit
  2711. // block as a successor.
  2712. if (!Block->hasNoReturnElement())
  2713. addSuccessor(Block, &cfg->getExit());
  2714. // Add the return statement to the block.
  2715. appendStmt(Block, S);
  2716. // Visit children
  2717. if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
  2718. if (Expr *O = RS->getRetValue())
  2719. return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
  2720. return Block;
  2721. }
  2722. CoreturnStmt *CRS = cast<CoreturnStmt>(S);
  2723. auto *B = Block;
  2724. if (CFGBlock *R = Visit(CRS->getPromiseCall()))
  2725. B = R;
  2726. if (Expr *RV = CRS->getOperand())
  2727. if (RV->getType()->isVoidType() && !isa<InitListExpr>(RV))
  2728. // A non-initlist void expression.
  2729. if (CFGBlock *R = Visit(RV))
  2730. B = R;
  2731. return B;
  2732. }
  2733. CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E,
  2734. AddStmtChoice asc) {
  2735. // We're modelling the pre-coro-xform CFG. Thus just evalate the various
  2736. // active components of the co_await or co_yield. Note we do not model the
  2737. // edge from the builtin_suspend to the exit node.
  2738. if (asc.alwaysAdd(*this, E)) {
  2739. autoCreateBlock();
  2740. appendStmt(Block, E);
  2741. }
  2742. CFGBlock *B = Block;
  2743. if (auto *R = Visit(E->getResumeExpr()))
  2744. B = R;
  2745. if (auto *R = Visit(E->getSuspendExpr()))
  2746. B = R;
  2747. if (auto *R = Visit(E->getReadyExpr()))
  2748. B = R;
  2749. if (auto *R = Visit(E->getCommonExpr()))
  2750. B = R;
  2751. return B;
  2752. }
  2753. CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
  2754. // SEHExceptStmt are treated like labels, so they are the first statement in a
  2755. // block.
  2756. // Save local scope position because in case of exception variable ScopePos
  2757. // won't be restored when traversing AST.
  2758. SaveAndRestore save_scope_pos(ScopePos);
  2759. addStmt(ES->getBlock());
  2760. CFGBlock *SEHExceptBlock = Block;
  2761. if (!SEHExceptBlock)
  2762. SEHExceptBlock = createBlock();
  2763. appendStmt(SEHExceptBlock, ES);
  2764. // Also add the SEHExceptBlock as a label, like with regular labels.
  2765. SEHExceptBlock->setLabel(ES);
  2766. // Bail out if the CFG is bad.
  2767. if (badCFG)
  2768. return nullptr;
  2769. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  2770. Block = nullptr;
  2771. return SEHExceptBlock;
  2772. }
  2773. CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
  2774. return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
  2775. }
  2776. CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
  2777. // "__leave" is a control-flow statement. Thus we stop processing the current
  2778. // block.
  2779. if (badCFG)
  2780. return nullptr;
  2781. // Now create a new block that ends with the __leave statement.
  2782. Block = createBlock(false);
  2783. Block->setTerminator(LS);
  2784. // If there is no target for the __leave, then we are looking at an incomplete
  2785. // AST. This means that the CFG cannot be constructed.
  2786. if (SEHLeaveJumpTarget.block) {
  2787. addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
  2788. addSuccessor(Block, SEHLeaveJumpTarget.block);
  2789. } else
  2790. badCFG = true;
  2791. return Block;
  2792. }
  2793. CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
  2794. // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
  2795. // processing the current block.
  2796. CFGBlock *SEHTrySuccessor = nullptr;
  2797. if (Block) {
  2798. if (badCFG)
  2799. return nullptr;
  2800. SEHTrySuccessor = Block;
  2801. } else SEHTrySuccessor = Succ;
  2802. // FIXME: Implement __finally support.
  2803. if (Terminator->getFinallyHandler())
  2804. return NYS();
  2805. CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
  2806. // Create a new block that will contain the __try statement.
  2807. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  2808. // Add the terminator in the __try block.
  2809. NewTryTerminatedBlock->setTerminator(Terminator);
  2810. if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
  2811. // The code after the try is the implicit successor if there's an __except.
  2812. Succ = SEHTrySuccessor;
  2813. Block = nullptr;
  2814. CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
  2815. if (!ExceptBlock)
  2816. return nullptr;
  2817. // Add this block to the list of successors for the block with the try
  2818. // statement.
  2819. addSuccessor(NewTryTerminatedBlock, ExceptBlock);
  2820. }
  2821. if (PrevSEHTryTerminatedBlock)
  2822. addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
  2823. else
  2824. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  2825. // The code after the try is the implicit successor.
  2826. Succ = SEHTrySuccessor;
  2827. // Save the current "__try" context.
  2828. SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
  2829. cfg->addTryDispatchBlock(TryTerminatedBlock);
  2830. // Save the current value for the __leave target.
  2831. // All __leaves should go to the code following the __try
  2832. // (FIXME: or if the __try has a __finally, to the __finally.)
  2833. SaveAndRestore save_break(SEHLeaveJumpTarget);
  2834. SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
  2835. assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
  2836. Block = nullptr;
  2837. return addStmt(Terminator->getTryBlock());
  2838. }
  2839. CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
  2840. // Get the block of the labeled statement. Add it to our map.
  2841. addStmt(L->getSubStmt());
  2842. CFGBlock *LabelBlock = Block;
  2843. if (!LabelBlock) // This can happen when the body is empty, i.e.
  2844. LabelBlock = createBlock(); // scopes that only contains NullStmts.
  2845. assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
  2846. "label already in map");
  2847. LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
  2848. // Labels partition blocks, so this is the end of the basic block we were
  2849. // processing (L is the block's label). Because this is label (and we have
  2850. // already processed the substatement) there is no extra control-flow to worry
  2851. // about.
  2852. LabelBlock->setLabel(L);
  2853. if (badCFG)
  2854. return nullptr;
  2855. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  2856. Block = nullptr;
  2857. // This block is now the implicit successor of other blocks.
  2858. Succ = LabelBlock;
  2859. return LabelBlock;
  2860. }
  2861. CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
  2862. CFGBlock *LastBlock = VisitNoRecurse(E, asc);
  2863. for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
  2864. if (Expr *CopyExpr = CI.getCopyExpr()) {
  2865. CFGBlock *Tmp = Visit(CopyExpr);
  2866. if (Tmp)
  2867. LastBlock = Tmp;
  2868. }
  2869. }
  2870. return LastBlock;
  2871. }
  2872. CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
  2873. CFGBlock *LastBlock = VisitNoRecurse(E, asc);
  2874. unsigned Idx = 0;
  2875. for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
  2876. et = E->capture_init_end();
  2877. it != et; ++it, ++Idx) {
  2878. if (Expr *Init = *it) {
  2879. // If the initializer is an ArrayInitLoopExpr, we want to extract the
  2880. // initializer, that's used for each element.
  2881. auto *AILEInit = extractElementInitializerFromNestedAILE(
  2882. dyn_cast<ArrayInitLoopExpr>(Init));
  2883. findConstructionContexts(ConstructionContextLayer::create(
  2884. cfg->getBumpVectorContext(), {E, Idx}),
  2885. AILEInit ? AILEInit : Init);
  2886. CFGBlock *Tmp = Visit(Init);
  2887. if (Tmp)
  2888. LastBlock = Tmp;
  2889. }
  2890. }
  2891. return LastBlock;
  2892. }
  2893. CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
  2894. // Goto is a control-flow statement. Thus we stop processing the current
  2895. // block and create a new one.
  2896. Block = createBlock(false);
  2897. Block->setTerminator(G);
  2898. // If we already know the mapping to the label block add the successor now.
  2899. LabelMapTy::iterator I = LabelMap.find(G->getLabel());
  2900. if (I == LabelMap.end())
  2901. // We will need to backpatch this block later.
  2902. BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
  2903. else {
  2904. JumpTarget JT = I->second;
  2905. addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
  2906. addSuccessor(Block, JT.block);
  2907. }
  2908. return Block;
  2909. }
  2910. CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
  2911. // Goto is a control-flow statement. Thus we stop processing the current
  2912. // block and create a new one.
  2913. if (!G->isAsmGoto())
  2914. return VisitStmt(G, asc);
  2915. if (Block) {
  2916. Succ = Block;
  2917. if (badCFG)
  2918. return nullptr;
  2919. }
  2920. Block = createBlock();
  2921. Block->setTerminator(G);
  2922. // We will backpatch this block later for all the labels.
  2923. BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
  2924. // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
  2925. // used to avoid adding "Succ" again.
  2926. BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
  2927. return VisitChildren(G);
  2928. }
  2929. CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
  2930. CFGBlock *LoopSuccessor = nullptr;
  2931. // Save local scope position because in case of condition variable ScopePos
  2932. // won't be restored when traversing AST.
  2933. SaveAndRestore save_scope_pos(ScopePos);
  2934. // Create local scope for init statement and possible condition variable.
  2935. // Add destructor for init statement and condition variable.
  2936. // Store scope position for continue statement.
  2937. if (Stmt *Init = F->getInit())
  2938. addLocalScopeForStmt(Init);
  2939. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  2940. if (VarDecl *VD = F->getConditionVariable())
  2941. addLocalScopeForVarDecl(VD);
  2942. LocalScope::const_iterator ContinueScopePos = ScopePos;
  2943. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
  2944. addLoopExit(F);
  2945. // "for" is a control-flow statement. Thus we stop processing the current
  2946. // block.
  2947. if (Block) {
  2948. if (badCFG)
  2949. return nullptr;
  2950. LoopSuccessor = Block;
  2951. } else
  2952. LoopSuccessor = Succ;
  2953. // Save the current value for the break targets.
  2954. // All breaks should go to the code following the loop.
  2955. SaveAndRestore save_break(BreakJumpTarget);
  2956. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  2957. CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
  2958. // Now create the loop body.
  2959. {
  2960. assert(F->getBody());
  2961. // Save the current values for Block, Succ, continue and break targets.
  2962. SaveAndRestore save_Block(Block), save_Succ(Succ);
  2963. SaveAndRestore save_continue(ContinueJumpTarget);
  2964. // Create an empty block to represent the transition block for looping back
  2965. // to the head of the loop. If we have increment code, it will
  2966. // go in this block as well.
  2967. Block = Succ = TransitionBlock = createBlock(false);
  2968. TransitionBlock->setLoopTarget(F);
  2969. if (Stmt *I = F->getInc()) {
  2970. // Generate increment code in its own basic block. This is the target of
  2971. // continue statements.
  2972. Succ = addStmt(I);
  2973. }
  2974. // Finish up the increment (or empty) block if it hasn't been already.
  2975. if (Block) {
  2976. assert(Block == Succ);
  2977. if (badCFG)
  2978. return nullptr;
  2979. Block = nullptr;
  2980. }
  2981. // The starting block for the loop increment is the block that should
  2982. // represent the 'loop target' for looping back to the start of the loop.
  2983. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  2984. ContinueJumpTarget.block->setLoopTarget(F);
  2985. // Loop body should end with destructor of Condition variable (if any).
  2986. addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
  2987. // If body is not a compound statement create implicit scope
  2988. // and add destructors.
  2989. if (!isa<CompoundStmt>(F->getBody()))
  2990. addLocalScopeAndDtors(F->getBody());
  2991. // Now populate the body block, and in the process create new blocks as we
  2992. // walk the body of the loop.
  2993. BodyBlock = addStmt(F->getBody());
  2994. if (!BodyBlock) {
  2995. // In the case of "for (...;...;...);" we can have a null BodyBlock.
  2996. // Use the continue jump target as the proxy for the body.
  2997. BodyBlock = ContinueJumpTarget.block;
  2998. }
  2999. else if (badCFG)
  3000. return nullptr;
  3001. }
  3002. // Because of short-circuit evaluation, the condition of the loop can span
  3003. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  3004. // evaluate the condition.
  3005. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
  3006. do {
  3007. Expr *C = F->getCond();
  3008. SaveAndRestore save_scope_pos(ScopePos);
  3009. // Specially handle logical operators, which have a slightly
  3010. // more optimal CFG representation.
  3011. if (BinaryOperator *Cond =
  3012. dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
  3013. if (Cond->isLogicalOp()) {
  3014. std::tie(EntryConditionBlock, ExitConditionBlock) =
  3015. VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
  3016. break;
  3017. }
  3018. // The default case when not handling logical operators.
  3019. EntryConditionBlock = ExitConditionBlock = createBlock(false);
  3020. ExitConditionBlock->setTerminator(F);
  3021. // See if this is a known constant.
  3022. TryResult KnownVal(true);
  3023. if (C) {
  3024. // Now add the actual condition to the condition block.
  3025. // Because the condition itself may contain control-flow, new blocks may
  3026. // be created. Thus we update "Succ" after adding the condition.
  3027. Block = ExitConditionBlock;
  3028. EntryConditionBlock = addStmt(C);
  3029. // If this block contains a condition variable, add both the condition
  3030. // variable and initializer to the CFG.
  3031. if (VarDecl *VD = F->getConditionVariable()) {
  3032. if (Expr *Init = VD->getInit()) {
  3033. autoCreateBlock();
  3034. const DeclStmt *DS = F->getConditionVariableDeclStmt();
  3035. assert(DS->isSingleDecl());
  3036. findConstructionContexts(
  3037. ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
  3038. Init);
  3039. appendStmt(Block, DS);
  3040. EntryConditionBlock = addStmt(Init);
  3041. assert(Block == EntryConditionBlock);
  3042. maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
  3043. }
  3044. }
  3045. if (Block && badCFG)
  3046. return nullptr;
  3047. KnownVal = tryEvaluateBool(C);
  3048. }
  3049. // Add the loop body entry as a successor to the condition.
  3050. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
  3051. // Link up the condition block with the code that follows the loop. (the
  3052. // false branch).
  3053. addSuccessor(ExitConditionBlock,
  3054. KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3055. } while (false);
  3056. // Link up the loop-back block to the entry condition block.
  3057. addSuccessor(TransitionBlock, EntryConditionBlock);
  3058. // The condition block is the implicit successor for any code above the loop.
  3059. Succ = EntryConditionBlock;
  3060. // If the loop contains initialization, create a new block for those
  3061. // statements. This block can also contain statements that precede the loop.
  3062. if (Stmt *I = F->getInit()) {
  3063. SaveAndRestore save_scope_pos(ScopePos);
  3064. ScopePos = LoopBeginScopePos;
  3065. Block = createBlock();
  3066. return addStmt(I);
  3067. }
  3068. // There is no loop initialization. We are thus basically a while loop.
  3069. // NULL out Block to force lazy block construction.
  3070. Block = nullptr;
  3071. Succ = EntryConditionBlock;
  3072. return EntryConditionBlock;
  3073. }
  3074. CFGBlock *
  3075. CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
  3076. AddStmtChoice asc) {
  3077. findConstructionContexts(
  3078. ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
  3079. MTE->getSubExpr());
  3080. return VisitStmt(MTE, asc);
  3081. }
  3082. CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
  3083. if (asc.alwaysAdd(*this, M)) {
  3084. autoCreateBlock();
  3085. appendStmt(Block, M);
  3086. }
  3087. return Visit(M->getBase());
  3088. }
  3089. CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
  3090. // Objective-C fast enumeration 'for' statements:
  3091. // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
  3092. //
  3093. // for ( Type newVariable in collection_expression ) { statements }
  3094. //
  3095. // becomes:
  3096. //
  3097. // prologue:
  3098. // 1. collection_expression
  3099. // T. jump to loop_entry
  3100. // loop_entry:
  3101. // 1. side-effects of element expression
  3102. // 1. ObjCForCollectionStmt [performs binding to newVariable]
  3103. // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
  3104. // TB:
  3105. // statements
  3106. // T. jump to loop_entry
  3107. // FB:
  3108. // what comes after
  3109. //
  3110. // and
  3111. //
  3112. // Type existingItem;
  3113. // for ( existingItem in expression ) { statements }
  3114. //
  3115. // becomes:
  3116. //
  3117. // the same with newVariable replaced with existingItem; the binding works
  3118. // the same except that for one ObjCForCollectionStmt::getElement() returns
  3119. // a DeclStmt and the other returns a DeclRefExpr.
  3120. CFGBlock *LoopSuccessor = nullptr;
  3121. if (Block) {
  3122. if (badCFG)
  3123. return nullptr;
  3124. LoopSuccessor = Block;
  3125. Block = nullptr;
  3126. } else
  3127. LoopSuccessor = Succ;
  3128. // Build the condition blocks.
  3129. CFGBlock *ExitConditionBlock = createBlock(false);
  3130. // Set the terminator for the "exit" condition block.
  3131. ExitConditionBlock->setTerminator(S);
  3132. // The last statement in the block should be the ObjCForCollectionStmt, which
  3133. // performs the actual binding to 'element' and determines if there are any
  3134. // more items in the collection.
  3135. appendStmt(ExitConditionBlock, S);
  3136. Block = ExitConditionBlock;
  3137. // Walk the 'element' expression to see if there are any side-effects. We
  3138. // generate new blocks as necessary. We DON'T add the statement by default to
  3139. // the CFG unless it contains control-flow.
  3140. CFGBlock *EntryConditionBlock = Visit(S->getElement(),
  3141. AddStmtChoice::NotAlwaysAdd);
  3142. if (Block) {
  3143. if (badCFG)
  3144. return nullptr;
  3145. Block = nullptr;
  3146. }
  3147. // The condition block is the implicit successor for the loop body as well as
  3148. // any code above the loop.
  3149. Succ = EntryConditionBlock;
  3150. // Now create the true branch.
  3151. {
  3152. // Save the current values for Succ, continue and break targets.
  3153. SaveAndRestore save_Block(Block), save_Succ(Succ);
  3154. SaveAndRestore save_continue(ContinueJumpTarget),
  3155. save_break(BreakJumpTarget);
  3156. // Add an intermediate block between the BodyBlock and the
  3157. // EntryConditionBlock to represent the "loop back" transition, for looping
  3158. // back to the head of the loop.
  3159. CFGBlock *LoopBackBlock = nullptr;
  3160. Succ = LoopBackBlock = createBlock();
  3161. LoopBackBlock->setLoopTarget(S);
  3162. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3163. ContinueJumpTarget = JumpTarget(Succ, ScopePos);
  3164. CFGBlock *BodyBlock = addStmt(S->getBody());
  3165. if (!BodyBlock)
  3166. BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
  3167. else if (Block) {
  3168. if (badCFG)
  3169. return nullptr;
  3170. }
  3171. // This new body block is a successor to our "exit" condition block.
  3172. addSuccessor(ExitConditionBlock, BodyBlock);
  3173. }
  3174. // Link up the condition block with the code that follows the loop.
  3175. // (the false branch).
  3176. addSuccessor(ExitConditionBlock, LoopSuccessor);
  3177. // Now create a prologue block to contain the collection expression.
  3178. Block = createBlock();
  3179. return addStmt(S->getCollection());
  3180. }
  3181. CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
  3182. // Inline the body.
  3183. return addStmt(S->getSubStmt());
  3184. // TODO: consider adding cleanups for the end of @autoreleasepool scope.
  3185. }
  3186. CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  3187. // FIXME: Add locking 'primitives' to CFG for @synchronized.
  3188. // Inline the body.
  3189. CFGBlock *SyncBlock = addStmt(S->getSynchBody());
  3190. // The sync body starts its own basic block. This makes it a little easier
  3191. // for diagnostic clients.
  3192. if (SyncBlock) {
  3193. if (badCFG)
  3194. return nullptr;
  3195. Block = nullptr;
  3196. Succ = SyncBlock;
  3197. }
  3198. // Add the @synchronized to the CFG.
  3199. autoCreateBlock();
  3200. appendStmt(Block, S);
  3201. // Inline the sync expression.
  3202. return addStmt(S->getSynchExpr());
  3203. }
  3204. CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  3205. autoCreateBlock();
  3206. // Add the PseudoObject as the last thing.
  3207. appendStmt(Block, E);
  3208. CFGBlock *lastBlock = Block;
  3209. // Before that, evaluate all of the semantics in order. In
  3210. // CFG-land, that means appending them in reverse order.
  3211. for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
  3212. Expr *Semantic = E->getSemanticExpr(--i);
  3213. // If the semantic is an opaque value, we're being asked to bind
  3214. // it to its source expression.
  3215. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  3216. Semantic = OVE->getSourceExpr();
  3217. if (CFGBlock *B = Visit(Semantic))
  3218. lastBlock = B;
  3219. }
  3220. return lastBlock;
  3221. }
  3222. CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
  3223. CFGBlock *LoopSuccessor = nullptr;
  3224. // Save local scope position because in case of condition variable ScopePos
  3225. // won't be restored when traversing AST.
  3226. SaveAndRestore save_scope_pos(ScopePos);
  3227. // Create local scope for possible condition variable.
  3228. // Store scope position for continue statement.
  3229. LocalScope::const_iterator LoopBeginScopePos = ScopePos;
  3230. if (VarDecl *VD = W->getConditionVariable()) {
  3231. addLocalScopeForVarDecl(VD);
  3232. addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
  3233. }
  3234. addLoopExit(W);
  3235. // "while" is a control-flow statement. Thus we stop processing the current
  3236. // block.
  3237. if (Block) {
  3238. if (badCFG)
  3239. return nullptr;
  3240. LoopSuccessor = Block;
  3241. Block = nullptr;
  3242. } else {
  3243. LoopSuccessor = Succ;
  3244. }
  3245. CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
  3246. // Process the loop body.
  3247. {
  3248. assert(W->getBody());
  3249. // Save the current values for Block, Succ, continue and break targets.
  3250. SaveAndRestore save_Block(Block), save_Succ(Succ);
  3251. SaveAndRestore save_continue(ContinueJumpTarget),
  3252. save_break(BreakJumpTarget);
  3253. // Create an empty block to represent the transition block for looping back
  3254. // to the head of the loop.
  3255. Succ = TransitionBlock = createBlock(false);
  3256. TransitionBlock->setLoopTarget(W);
  3257. ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
  3258. // All breaks should go to the code following the loop.
  3259. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3260. // Loop body should end with destructor of Condition variable (if any).
  3261. addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
  3262. // If body is not a compound statement create implicit scope
  3263. // and add destructors.
  3264. if (!isa<CompoundStmt>(W->getBody()))
  3265. addLocalScopeAndDtors(W->getBody());
  3266. // Create the body. The returned block is the entry to the loop body.
  3267. BodyBlock = addStmt(W->getBody());
  3268. if (!BodyBlock)
  3269. BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
  3270. else if (Block && badCFG)
  3271. return nullptr;
  3272. }
  3273. // Because of short-circuit evaluation, the condition of the loop can span
  3274. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  3275. // evaluate the condition.
  3276. CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
  3277. do {
  3278. Expr *C = W->getCond();
  3279. // Specially handle logical operators, which have a slightly
  3280. // more optimal CFG representation.
  3281. if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
  3282. if (Cond->isLogicalOp()) {
  3283. std::tie(EntryConditionBlock, ExitConditionBlock) =
  3284. VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
  3285. break;
  3286. }
  3287. // The default case when not handling logical operators.
  3288. ExitConditionBlock = createBlock(false);
  3289. ExitConditionBlock->setTerminator(W);
  3290. // Now add the actual condition to the condition block.
  3291. // Because the condition itself may contain control-flow, new blocks may
  3292. // be created. Thus we update "Succ" after adding the condition.
  3293. Block = ExitConditionBlock;
  3294. Block = EntryConditionBlock = addStmt(C);
  3295. // If this block contains a condition variable, add both the condition
  3296. // variable and initializer to the CFG.
  3297. if (VarDecl *VD = W->getConditionVariable()) {
  3298. if (Expr *Init = VD->getInit()) {
  3299. autoCreateBlock();
  3300. const DeclStmt *DS = W->getConditionVariableDeclStmt();
  3301. assert(DS->isSingleDecl());
  3302. findConstructionContexts(
  3303. ConstructionContextLayer::create(cfg->getBumpVectorContext(),
  3304. const_cast<DeclStmt *>(DS)),
  3305. Init);
  3306. appendStmt(Block, DS);
  3307. EntryConditionBlock = addStmt(Init);
  3308. assert(Block == EntryConditionBlock);
  3309. maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
  3310. }
  3311. }
  3312. if (Block && badCFG)
  3313. return nullptr;
  3314. // See if this is a known constant.
  3315. const TryResult& KnownVal = tryEvaluateBool(C);
  3316. // Add the loop body entry as a successor to the condition.
  3317. addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
  3318. // Link up the condition block with the code that follows the loop. (the
  3319. // false branch).
  3320. addSuccessor(ExitConditionBlock,
  3321. KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3322. } while(false);
  3323. // Link up the loop-back block to the entry condition block.
  3324. addSuccessor(TransitionBlock, EntryConditionBlock);
  3325. // There can be no more statements in the condition block since we loop back
  3326. // to this block. NULL out Block to force lazy creation of another block.
  3327. Block = nullptr;
  3328. // Return the condition block, which is the dominating block for the loop.
  3329. Succ = EntryConditionBlock;
  3330. return EntryConditionBlock;
  3331. }
  3332. CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
  3333. AddStmtChoice asc) {
  3334. if (asc.alwaysAdd(*this, A)) {
  3335. autoCreateBlock();
  3336. appendStmt(Block, A);
  3337. }
  3338. CFGBlock *B = Block;
  3339. if (CFGBlock *R = Visit(A->getSubExpr()))
  3340. B = R;
  3341. auto *OVE = dyn_cast<OpaqueValueExpr>(A->getCommonExpr());
  3342. assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
  3343. "OpaqueValueExpr!");
  3344. if (CFGBlock *R = Visit(OVE->getSourceExpr()))
  3345. B = R;
  3346. return B;
  3347. }
  3348. CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
  3349. // ObjCAtCatchStmt are treated like labels, so they are the first statement
  3350. // in a block.
  3351. // Save local scope position because in case of exception variable ScopePos
  3352. // won't be restored when traversing AST.
  3353. SaveAndRestore save_scope_pos(ScopePos);
  3354. if (CS->getCatchBody())
  3355. addStmt(CS->getCatchBody());
  3356. CFGBlock *CatchBlock = Block;
  3357. if (!CatchBlock)
  3358. CatchBlock = createBlock();
  3359. appendStmt(CatchBlock, CS);
  3360. // Also add the ObjCAtCatchStmt as a label, like with regular labels.
  3361. CatchBlock->setLabel(CS);
  3362. // Bail out if the CFG is bad.
  3363. if (badCFG)
  3364. return nullptr;
  3365. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  3366. Block = nullptr;
  3367. return CatchBlock;
  3368. }
  3369. CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
  3370. // If we were in the middle of a block we stop processing that block.
  3371. if (badCFG)
  3372. return nullptr;
  3373. // Create the new block.
  3374. Block = createBlock(false);
  3375. if (TryTerminatedBlock)
  3376. // The current try statement is the only successor.
  3377. addSuccessor(Block, TryTerminatedBlock);
  3378. else
  3379. // otherwise the Exit block is the only successor.
  3380. addSuccessor(Block, &cfg->getExit());
  3381. // Add the statement to the block. This may create new blocks if S contains
  3382. // control-flow (short-circuit operations).
  3383. return VisitStmt(S, AddStmtChoice::AlwaysAdd);
  3384. }
  3385. CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
  3386. // "@try"/"@catch" is a control-flow statement. Thus we stop processing the
  3387. // current block.
  3388. CFGBlock *TrySuccessor = nullptr;
  3389. if (Block) {
  3390. if (badCFG)
  3391. return nullptr;
  3392. TrySuccessor = Block;
  3393. } else
  3394. TrySuccessor = Succ;
  3395. // FIXME: Implement @finally support.
  3396. if (Terminator->getFinallyStmt())
  3397. return NYS();
  3398. CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
  3399. // Create a new block that will contain the try statement.
  3400. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  3401. // Add the terminator in the try block.
  3402. NewTryTerminatedBlock->setTerminator(Terminator);
  3403. bool HasCatchAll = false;
  3404. for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
  3405. // The code after the try is the implicit successor.
  3406. Succ = TrySuccessor;
  3407. if (CS->hasEllipsis()) {
  3408. HasCatchAll = true;
  3409. }
  3410. Block = nullptr;
  3411. CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
  3412. if (!CatchBlock)
  3413. return nullptr;
  3414. // Add this block to the list of successors for the block with the try
  3415. // statement.
  3416. addSuccessor(NewTryTerminatedBlock, CatchBlock);
  3417. }
  3418. // FIXME: This needs updating when @finally support is added.
  3419. if (!HasCatchAll) {
  3420. if (PrevTryTerminatedBlock)
  3421. addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
  3422. else
  3423. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  3424. }
  3425. // The code after the try is the implicit successor.
  3426. Succ = TrySuccessor;
  3427. // Save the current "try" context.
  3428. SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
  3429. cfg->addTryDispatchBlock(TryTerminatedBlock);
  3430. assert(Terminator->getTryBody() && "try must contain a non-NULL body");
  3431. Block = nullptr;
  3432. return addStmt(Terminator->getTryBody());
  3433. }
  3434. CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
  3435. AddStmtChoice asc) {
  3436. findConstructionContextsForArguments(ME);
  3437. autoCreateBlock();
  3438. appendObjCMessage(Block, ME);
  3439. return VisitChildren(ME);
  3440. }
  3441. CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
  3442. // If we were in the middle of a block we stop processing that block.
  3443. if (badCFG)
  3444. return nullptr;
  3445. // Create the new block.
  3446. Block = createBlock(false);
  3447. if (TryTerminatedBlock)
  3448. // The current try statement is the only successor.
  3449. addSuccessor(Block, TryTerminatedBlock);
  3450. else
  3451. // otherwise the Exit block is the only successor.
  3452. addSuccessor(Block, &cfg->getExit());
  3453. // Add the statement to the block. This may create new blocks if S contains
  3454. // control-flow (short-circuit operations).
  3455. return VisitStmt(T, AddStmtChoice::AlwaysAdd);
  3456. }
  3457. CFGBlock *CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc) {
  3458. if (asc.alwaysAdd(*this, S)) {
  3459. autoCreateBlock();
  3460. appendStmt(Block, S);
  3461. }
  3462. // C++ [expr.typeid]p3:
  3463. // When typeid is applied to an expression other than an glvalue of a
  3464. // polymorphic class type [...] [the] expression is an unevaluated
  3465. // operand. [...]
  3466. // We add only potentially evaluated statements to the block to avoid
  3467. // CFG generation for unevaluated operands.
  3468. if (S && !S->isTypeDependent() && S->isPotentiallyEvaluated())
  3469. return VisitChildren(S);
  3470. // Return block without CFG for unevaluated operands.
  3471. return Block;
  3472. }
  3473. CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
  3474. CFGBlock *LoopSuccessor = nullptr;
  3475. addLoopExit(D);
  3476. // "do...while" is a control-flow statement. Thus we stop processing the
  3477. // current block.
  3478. if (Block) {
  3479. if (badCFG)
  3480. return nullptr;
  3481. LoopSuccessor = Block;
  3482. } else
  3483. LoopSuccessor = Succ;
  3484. // Because of short-circuit evaluation, the condition of the loop can span
  3485. // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
  3486. // evaluate the condition.
  3487. CFGBlock *ExitConditionBlock = createBlock(false);
  3488. CFGBlock *EntryConditionBlock = ExitConditionBlock;
  3489. // Set the terminator for the "exit" condition block.
  3490. ExitConditionBlock->setTerminator(D);
  3491. // Now add the actual condition to the condition block. Because the condition
  3492. // itself may contain control-flow, new blocks may be created.
  3493. if (Stmt *C = D->getCond()) {
  3494. Block = ExitConditionBlock;
  3495. EntryConditionBlock = addStmt(C);
  3496. if (Block) {
  3497. if (badCFG)
  3498. return nullptr;
  3499. }
  3500. }
  3501. // The condition block is the implicit successor for the loop body.
  3502. Succ = EntryConditionBlock;
  3503. // See if this is a known constant.
  3504. const TryResult &KnownVal = tryEvaluateBool(D->getCond());
  3505. // Process the loop body.
  3506. CFGBlock *BodyBlock = nullptr;
  3507. {
  3508. assert(D->getBody());
  3509. // Save the current values for Block, Succ, and continue and break targets
  3510. SaveAndRestore save_Block(Block), save_Succ(Succ);
  3511. SaveAndRestore save_continue(ContinueJumpTarget),
  3512. save_break(BreakJumpTarget);
  3513. // All continues within this loop should go to the condition block
  3514. ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
  3515. // All breaks should go to the code following the loop.
  3516. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3517. // NULL out Block to force lazy instantiation of blocks for the body.
  3518. Block = nullptr;
  3519. // If body is not a compound statement create implicit scope
  3520. // and add destructors.
  3521. if (!isa<CompoundStmt>(D->getBody()))
  3522. addLocalScopeAndDtors(D->getBody());
  3523. // Create the body. The returned block is the entry to the loop body.
  3524. BodyBlock = addStmt(D->getBody());
  3525. if (!BodyBlock)
  3526. BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
  3527. else if (Block) {
  3528. if (badCFG)
  3529. return nullptr;
  3530. }
  3531. // Add an intermediate block between the BodyBlock and the
  3532. // ExitConditionBlock to represent the "loop back" transition. Create an
  3533. // empty block to represent the transition block for looping back to the
  3534. // head of the loop.
  3535. // FIXME: Can we do this more efficiently without adding another block?
  3536. Block = nullptr;
  3537. Succ = BodyBlock;
  3538. CFGBlock *LoopBackBlock = createBlock();
  3539. LoopBackBlock->setLoopTarget(D);
  3540. if (!KnownVal.isFalse())
  3541. // Add the loop body entry as a successor to the condition.
  3542. addSuccessor(ExitConditionBlock, LoopBackBlock);
  3543. else
  3544. addSuccessor(ExitConditionBlock, nullptr);
  3545. }
  3546. // Link up the condition block with the code that follows the loop.
  3547. // (the false branch).
  3548. addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3549. // There can be no more statements in the body block(s) since we loop back to
  3550. // the body. NULL out Block to force lazy creation of another block.
  3551. Block = nullptr;
  3552. // Return the loop body, which is the dominating block for the loop.
  3553. Succ = BodyBlock;
  3554. return BodyBlock;
  3555. }
  3556. CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
  3557. // "continue" is a control-flow statement. Thus we stop processing the
  3558. // current block.
  3559. if (badCFG)
  3560. return nullptr;
  3561. // Now create a new block that ends with the continue statement.
  3562. Block = createBlock(false);
  3563. Block->setTerminator(C);
  3564. // If there is no target for the continue, then we are looking at an
  3565. // incomplete AST. This means the CFG cannot be constructed.
  3566. if (ContinueJumpTarget.block) {
  3567. addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
  3568. addSuccessor(Block, ContinueJumpTarget.block);
  3569. } else
  3570. badCFG = true;
  3571. return Block;
  3572. }
  3573. CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
  3574. AddStmtChoice asc) {
  3575. if (asc.alwaysAdd(*this, E)) {
  3576. autoCreateBlock();
  3577. appendStmt(Block, E);
  3578. }
  3579. // VLA types have expressions that must be evaluated.
  3580. // Evaluation is done only for `sizeof`.
  3581. if (E->getKind() != UETT_SizeOf)
  3582. return Block;
  3583. CFGBlock *lastBlock = Block;
  3584. if (E->isArgumentType()) {
  3585. for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
  3586. VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
  3587. lastBlock = addStmt(VA->getSizeExpr());
  3588. }
  3589. return lastBlock;
  3590. }
  3591. /// VisitStmtExpr - Utility method to handle (nested) statement
  3592. /// expressions (a GCC extension).
  3593. CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
  3594. if (asc.alwaysAdd(*this, SE)) {
  3595. autoCreateBlock();
  3596. appendStmt(Block, SE);
  3597. }
  3598. return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
  3599. }
  3600. CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
  3601. // "switch" is a control-flow statement. Thus we stop processing the current
  3602. // block.
  3603. CFGBlock *SwitchSuccessor = nullptr;
  3604. // Save local scope position because in case of condition variable ScopePos
  3605. // won't be restored when traversing AST.
  3606. SaveAndRestore save_scope_pos(ScopePos);
  3607. // Create local scope for C++17 switch init-stmt if one exists.
  3608. if (Stmt *Init = Terminator->getInit())
  3609. addLocalScopeForStmt(Init);
  3610. // Create local scope for possible condition variable.
  3611. // Store scope position. Add implicit destructor.
  3612. if (VarDecl *VD = Terminator->getConditionVariable())
  3613. addLocalScopeForVarDecl(VD);
  3614. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
  3615. if (Block) {
  3616. if (badCFG)
  3617. return nullptr;
  3618. SwitchSuccessor = Block;
  3619. } else SwitchSuccessor = Succ;
  3620. // Save the current "switch" context.
  3621. SaveAndRestore save_switch(SwitchTerminatedBlock),
  3622. save_default(DefaultCaseBlock);
  3623. SaveAndRestore save_break(BreakJumpTarget);
  3624. // Set the "default" case to be the block after the switch statement. If the
  3625. // switch statement contains a "default:", this value will be overwritten with
  3626. // the block for that code.
  3627. DefaultCaseBlock = SwitchSuccessor;
  3628. // Create a new block that will contain the switch statement.
  3629. SwitchTerminatedBlock = createBlock(false);
  3630. // Now process the switch body. The code after the switch is the implicit
  3631. // successor.
  3632. Succ = SwitchSuccessor;
  3633. BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
  3634. // When visiting the body, the case statements should automatically get linked
  3635. // up to the switch. We also don't keep a pointer to the body, since all
  3636. // control-flow from the switch goes to case/default statements.
  3637. assert(Terminator->getBody() && "switch must contain a non-NULL body");
  3638. Block = nullptr;
  3639. // For pruning unreachable case statements, save the current state
  3640. // for tracking the condition value.
  3641. SaveAndRestore save_switchExclusivelyCovered(switchExclusivelyCovered, false);
  3642. // Determine if the switch condition can be explicitly evaluated.
  3643. assert(Terminator->getCond() && "switch condition must be non-NULL");
  3644. Expr::EvalResult result;
  3645. bool b = tryEvaluate(Terminator->getCond(), result);
  3646. SaveAndRestore save_switchCond(switchCond, b ? &result : nullptr);
  3647. // If body is not a compound statement create implicit scope
  3648. // and add destructors.
  3649. if (!isa<CompoundStmt>(Terminator->getBody()))
  3650. addLocalScopeAndDtors(Terminator->getBody());
  3651. addStmt(Terminator->getBody());
  3652. if (Block) {
  3653. if (badCFG)
  3654. return nullptr;
  3655. }
  3656. // If we have no "default:" case, the default transition is to the code
  3657. // following the switch body. Moreover, take into account if all the
  3658. // cases of a switch are covered (e.g., switching on an enum value).
  3659. //
  3660. // Note: We add a successor to a switch that is considered covered yet has no
  3661. // case statements if the enumeration has no enumerators.
  3662. bool SwitchAlwaysHasSuccessor = false;
  3663. SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
  3664. SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
  3665. Terminator->getSwitchCaseList();
  3666. addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
  3667. !SwitchAlwaysHasSuccessor);
  3668. // Add the terminator and condition in the switch block.
  3669. SwitchTerminatedBlock->setTerminator(Terminator);
  3670. Block = SwitchTerminatedBlock;
  3671. CFGBlock *LastBlock = addStmt(Terminator->getCond());
  3672. // If the SwitchStmt contains a condition variable, add both the
  3673. // SwitchStmt and the condition variable initialization to the CFG.
  3674. if (VarDecl *VD = Terminator->getConditionVariable()) {
  3675. if (Expr *Init = VD->getInit()) {
  3676. autoCreateBlock();
  3677. appendStmt(Block, Terminator->getConditionVariableDeclStmt());
  3678. LastBlock = addStmt(Init);
  3679. maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
  3680. }
  3681. }
  3682. // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
  3683. if (Stmt *Init = Terminator->getInit()) {
  3684. autoCreateBlock();
  3685. LastBlock = addStmt(Init);
  3686. }
  3687. return LastBlock;
  3688. }
  3689. static bool shouldAddCase(bool &switchExclusivelyCovered,
  3690. const Expr::EvalResult *switchCond,
  3691. const CaseStmt *CS,
  3692. ASTContext &Ctx) {
  3693. if (!switchCond)
  3694. return true;
  3695. bool addCase = false;
  3696. if (!switchExclusivelyCovered) {
  3697. if (switchCond->Val.isInt()) {
  3698. // Evaluate the LHS of the case value.
  3699. const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
  3700. const llvm::APSInt &condInt = switchCond->Val.getInt();
  3701. if (condInt == lhsInt) {
  3702. addCase = true;
  3703. switchExclusivelyCovered = true;
  3704. }
  3705. else if (condInt > lhsInt) {
  3706. if (const Expr *RHS = CS->getRHS()) {
  3707. // Evaluate the RHS of the case value.
  3708. const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
  3709. if (V2 >= condInt) {
  3710. addCase = true;
  3711. switchExclusivelyCovered = true;
  3712. }
  3713. }
  3714. }
  3715. }
  3716. else
  3717. addCase = true;
  3718. }
  3719. return addCase;
  3720. }
  3721. CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
  3722. // CaseStmts are essentially labels, so they are the first statement in a
  3723. // block.
  3724. CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
  3725. if (Stmt *Sub = CS->getSubStmt()) {
  3726. // For deeply nested chains of CaseStmts, instead of doing a recursion
  3727. // (which can blow out the stack), manually unroll and create blocks
  3728. // along the way.
  3729. while (isa<CaseStmt>(Sub)) {
  3730. CFGBlock *currentBlock = createBlock(false);
  3731. currentBlock->setLabel(CS);
  3732. if (TopBlock)
  3733. addSuccessor(LastBlock, currentBlock);
  3734. else
  3735. TopBlock = currentBlock;
  3736. addSuccessor(SwitchTerminatedBlock,
  3737. shouldAddCase(switchExclusivelyCovered, switchCond,
  3738. CS, *Context)
  3739. ? currentBlock : nullptr);
  3740. LastBlock = currentBlock;
  3741. CS = cast<CaseStmt>(Sub);
  3742. Sub = CS->getSubStmt();
  3743. }
  3744. addStmt(Sub);
  3745. }
  3746. CFGBlock *CaseBlock = Block;
  3747. if (!CaseBlock)
  3748. CaseBlock = createBlock();
  3749. // Cases statements partition blocks, so this is the top of the basic block we
  3750. // were processing (the "case XXX:" is the label).
  3751. CaseBlock->setLabel(CS);
  3752. if (badCFG)
  3753. return nullptr;
  3754. // Add this block to the list of successors for the block with the switch
  3755. // statement.
  3756. assert(SwitchTerminatedBlock);
  3757. addSuccessor(SwitchTerminatedBlock, CaseBlock,
  3758. shouldAddCase(switchExclusivelyCovered, switchCond,
  3759. CS, *Context));
  3760. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  3761. Block = nullptr;
  3762. if (TopBlock) {
  3763. addSuccessor(LastBlock, CaseBlock);
  3764. Succ = TopBlock;
  3765. } else {
  3766. // This block is now the implicit successor of other blocks.
  3767. Succ = CaseBlock;
  3768. }
  3769. return Succ;
  3770. }
  3771. CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
  3772. if (Terminator->getSubStmt())
  3773. addStmt(Terminator->getSubStmt());
  3774. DefaultCaseBlock = Block;
  3775. if (!DefaultCaseBlock)
  3776. DefaultCaseBlock = createBlock();
  3777. // Default statements partition blocks, so this is the top of the basic block
  3778. // we were processing (the "default:" is the label).
  3779. DefaultCaseBlock->setLabel(Terminator);
  3780. if (badCFG)
  3781. return nullptr;
  3782. // Unlike case statements, we don't add the default block to the successors
  3783. // for the switch statement immediately. This is done when we finish
  3784. // processing the switch statement. This allows for the default case
  3785. // (including a fall-through to the code after the switch statement) to always
  3786. // be the last successor of a switch-terminated block.
  3787. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  3788. Block = nullptr;
  3789. // This block is now the implicit successor of other blocks.
  3790. Succ = DefaultCaseBlock;
  3791. return DefaultCaseBlock;
  3792. }
  3793. CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
  3794. // "try"/"catch" is a control-flow statement. Thus we stop processing the
  3795. // current block.
  3796. CFGBlock *TrySuccessor = nullptr;
  3797. if (Block) {
  3798. if (badCFG)
  3799. return nullptr;
  3800. TrySuccessor = Block;
  3801. } else
  3802. TrySuccessor = Succ;
  3803. CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
  3804. // Create a new block that will contain the try statement.
  3805. CFGBlock *NewTryTerminatedBlock = createBlock(false);
  3806. // Add the terminator in the try block.
  3807. NewTryTerminatedBlock->setTerminator(Terminator);
  3808. bool HasCatchAll = false;
  3809. for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) {
  3810. // The code after the try is the implicit successor.
  3811. Succ = TrySuccessor;
  3812. CXXCatchStmt *CS = Terminator->getHandler(I);
  3813. if (CS->getExceptionDecl() == nullptr) {
  3814. HasCatchAll = true;
  3815. }
  3816. Block = nullptr;
  3817. CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
  3818. if (!CatchBlock)
  3819. return nullptr;
  3820. // Add this block to the list of successors for the block with the try
  3821. // statement.
  3822. addSuccessor(NewTryTerminatedBlock, CatchBlock);
  3823. }
  3824. if (!HasCatchAll) {
  3825. if (PrevTryTerminatedBlock)
  3826. addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
  3827. else
  3828. addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
  3829. }
  3830. // The code after the try is the implicit successor.
  3831. Succ = TrySuccessor;
  3832. // Save the current "try" context.
  3833. SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
  3834. cfg->addTryDispatchBlock(TryTerminatedBlock);
  3835. assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
  3836. Block = nullptr;
  3837. return addStmt(Terminator->getTryBlock());
  3838. }
  3839. CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
  3840. // CXXCatchStmt are treated like labels, so they are the first statement in a
  3841. // block.
  3842. // Save local scope position because in case of exception variable ScopePos
  3843. // won't be restored when traversing AST.
  3844. SaveAndRestore save_scope_pos(ScopePos);
  3845. // Create local scope for possible exception variable.
  3846. // Store scope position. Add implicit destructor.
  3847. if (VarDecl *VD = CS->getExceptionDecl()) {
  3848. LocalScope::const_iterator BeginScopePos = ScopePos;
  3849. addLocalScopeForVarDecl(VD);
  3850. addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
  3851. }
  3852. if (CS->getHandlerBlock())
  3853. addStmt(CS->getHandlerBlock());
  3854. CFGBlock *CatchBlock = Block;
  3855. if (!CatchBlock)
  3856. CatchBlock = createBlock();
  3857. // CXXCatchStmt is more than just a label. They have semantic meaning
  3858. // as well, as they implicitly "initialize" the catch variable. Add
  3859. // it to the CFG as a CFGElement so that the control-flow of these
  3860. // semantics gets captured.
  3861. appendStmt(CatchBlock, CS);
  3862. // Also add the CXXCatchStmt as a label, to mirror handling of regular
  3863. // labels.
  3864. CatchBlock->setLabel(CS);
  3865. // Bail out if the CFG is bad.
  3866. if (badCFG)
  3867. return nullptr;
  3868. // We set Block to NULL to allow lazy creation of a new block (if necessary).
  3869. Block = nullptr;
  3870. return CatchBlock;
  3871. }
  3872. CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
  3873. // C++0x for-range statements are specified as [stmt.ranged]:
  3874. //
  3875. // {
  3876. // auto && __range = range-init;
  3877. // for ( auto __begin = begin-expr,
  3878. // __end = end-expr;
  3879. // __begin != __end;
  3880. // ++__begin ) {
  3881. // for-range-declaration = *__begin;
  3882. // statement
  3883. // }
  3884. // }
  3885. // Save local scope position before the addition of the implicit variables.
  3886. SaveAndRestore save_scope_pos(ScopePos);
  3887. // Create local scopes and destructors for range, begin and end variables.
  3888. if (Stmt *Range = S->getRangeStmt())
  3889. addLocalScopeForStmt(Range);
  3890. if (Stmt *Begin = S->getBeginStmt())
  3891. addLocalScopeForStmt(Begin);
  3892. if (Stmt *End = S->getEndStmt())
  3893. addLocalScopeForStmt(End);
  3894. addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
  3895. LocalScope::const_iterator ContinueScopePos = ScopePos;
  3896. // "for" is a control-flow statement. Thus we stop processing the current
  3897. // block.
  3898. CFGBlock *LoopSuccessor = nullptr;
  3899. if (Block) {
  3900. if (badCFG)
  3901. return nullptr;
  3902. LoopSuccessor = Block;
  3903. } else
  3904. LoopSuccessor = Succ;
  3905. // Save the current value for the break targets.
  3906. // All breaks should go to the code following the loop.
  3907. SaveAndRestore save_break(BreakJumpTarget);
  3908. BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
  3909. // The block for the __begin != __end expression.
  3910. CFGBlock *ConditionBlock = createBlock(false);
  3911. ConditionBlock->setTerminator(S);
  3912. // Now add the actual condition to the condition block.
  3913. if (Expr *C = S->getCond()) {
  3914. Block = ConditionBlock;
  3915. CFGBlock *BeginConditionBlock = addStmt(C);
  3916. if (badCFG)
  3917. return nullptr;
  3918. assert(BeginConditionBlock == ConditionBlock &&
  3919. "condition block in for-range was unexpectedly complex");
  3920. (void)BeginConditionBlock;
  3921. }
  3922. // The condition block is the implicit successor for the loop body as well as
  3923. // any code above the loop.
  3924. Succ = ConditionBlock;
  3925. // See if this is a known constant.
  3926. TryResult KnownVal(true);
  3927. if (S->getCond())
  3928. KnownVal = tryEvaluateBool(S->getCond());
  3929. // Now create the loop body.
  3930. {
  3931. assert(S->getBody());
  3932. // Save the current values for Block, Succ, and continue targets.
  3933. SaveAndRestore save_Block(Block), save_Succ(Succ);
  3934. SaveAndRestore save_continue(ContinueJumpTarget);
  3935. // Generate increment code in its own basic block. This is the target of
  3936. // continue statements.
  3937. Block = nullptr;
  3938. Succ = addStmt(S->getInc());
  3939. if (badCFG)
  3940. return nullptr;
  3941. ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
  3942. // The starting block for the loop increment is the block that should
  3943. // represent the 'loop target' for looping back to the start of the loop.
  3944. ContinueJumpTarget.block->setLoopTarget(S);
  3945. // Finish up the increment block and prepare to start the loop body.
  3946. assert(Block);
  3947. if (badCFG)
  3948. return nullptr;
  3949. Block = nullptr;
  3950. // Add implicit scope and dtors for loop variable.
  3951. addLocalScopeAndDtors(S->getLoopVarStmt());
  3952. // If body is not a compound statement create implicit scope
  3953. // and add destructors.
  3954. if (!isa<CompoundStmt>(S->getBody()))
  3955. addLocalScopeAndDtors(S->getBody());
  3956. // Populate a new block to contain the loop body and loop variable.
  3957. addStmt(S->getBody());
  3958. if (badCFG)
  3959. return nullptr;
  3960. CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
  3961. if (badCFG)
  3962. return nullptr;
  3963. // This new body block is a successor to our condition block.
  3964. addSuccessor(ConditionBlock,
  3965. KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
  3966. }
  3967. // Link up the condition block with the code that follows the loop (the
  3968. // false branch).
  3969. addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
  3970. // Add the initialization statements.
  3971. Block = createBlock();
  3972. addStmt(S->getBeginStmt());
  3973. addStmt(S->getEndStmt());
  3974. CFGBlock *Head = addStmt(S->getRangeStmt());
  3975. if (S->getInit())
  3976. Head = addStmt(S->getInit());
  3977. return Head;
  3978. }
  3979. CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
  3980. AddStmtChoice asc, bool ExternallyDestructed) {
  3981. if (BuildOpts.AddTemporaryDtors) {
  3982. // If adding implicit destructors visit the full expression for adding
  3983. // destructors of temporaries.
  3984. TempDtorContext Context;
  3985. VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
  3986. // Full expression has to be added as CFGStmt so it will be sequenced
  3987. // before destructors of it's temporaries.
  3988. asc = asc.withAlwaysAdd(true);
  3989. }
  3990. return Visit(E->getSubExpr(), asc);
  3991. }
  3992. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
  3993. AddStmtChoice asc) {
  3994. if (asc.alwaysAdd(*this, E)) {
  3995. autoCreateBlock();
  3996. appendStmt(Block, E);
  3997. findConstructionContexts(
  3998. ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
  3999. E->getSubExpr());
  4000. // We do not want to propagate the AlwaysAdd property.
  4001. asc = asc.withAlwaysAdd(false);
  4002. }
  4003. return Visit(E->getSubExpr(), asc);
  4004. }
  4005. CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
  4006. AddStmtChoice asc) {
  4007. // If the constructor takes objects as arguments by value, we need to properly
  4008. // construct these objects. Construction contexts we find here aren't for the
  4009. // constructor C, they're for its arguments only.
  4010. findConstructionContextsForArguments(C);
  4011. autoCreateBlock();
  4012. appendConstructor(Block, C);
  4013. return VisitChildren(C);
  4014. }
  4015. CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
  4016. AddStmtChoice asc) {
  4017. autoCreateBlock();
  4018. appendStmt(Block, NE);
  4019. findConstructionContexts(
  4020. ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
  4021. const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
  4022. if (NE->getInitializer())
  4023. Block = Visit(NE->getInitializer());
  4024. if (BuildOpts.AddCXXNewAllocator)
  4025. appendNewAllocator(Block, NE);
  4026. if (NE->isArray() && *NE->getArraySize())
  4027. Block = Visit(*NE->getArraySize());
  4028. for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
  4029. E = NE->placement_arg_end(); I != E; ++I)
  4030. Block = Visit(*I);
  4031. return Block;
  4032. }
  4033. CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
  4034. AddStmtChoice asc) {
  4035. autoCreateBlock();
  4036. appendStmt(Block, DE);
  4037. QualType DTy = DE->getDestroyedType();
  4038. if (!DTy.isNull()) {
  4039. DTy = DTy.getNonReferenceType();
  4040. CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
  4041. if (RD) {
  4042. if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
  4043. appendDeleteDtor(Block, RD, DE);
  4044. }
  4045. }
  4046. return VisitChildren(DE);
  4047. }
  4048. CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
  4049. AddStmtChoice asc) {
  4050. if (asc.alwaysAdd(*this, E)) {
  4051. autoCreateBlock();
  4052. appendStmt(Block, E);
  4053. // We do not want to propagate the AlwaysAdd property.
  4054. asc = asc.withAlwaysAdd(false);
  4055. }
  4056. return Visit(E->getSubExpr(), asc);
  4057. }
  4058. CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
  4059. AddStmtChoice asc) {
  4060. // If the constructor takes objects as arguments by value, we need to properly
  4061. // construct these objects. Construction contexts we find here aren't for the
  4062. // constructor C, they're for its arguments only.
  4063. findConstructionContextsForArguments(C);
  4064. autoCreateBlock();
  4065. appendConstructor(Block, C);
  4066. return VisitChildren(C);
  4067. }
  4068. CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
  4069. AddStmtChoice asc) {
  4070. if (asc.alwaysAdd(*this, E)) {
  4071. autoCreateBlock();
  4072. appendStmt(Block, E);
  4073. }
  4074. if (E->getCastKind() == CK_IntegralToBoolean)
  4075. tryEvaluateBool(E->getSubExpr()->IgnoreParens());
  4076. return Visit(E->getSubExpr(), AddStmtChoice());
  4077. }
  4078. CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
  4079. return Visit(E->getSubExpr(), AddStmtChoice());
  4080. }
  4081. CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  4082. // Lazily create the indirect-goto dispatch block if there isn't one already.
  4083. CFGBlock *IBlock = cfg->getIndirectGotoBlock();
  4084. if (!IBlock) {
  4085. IBlock = createBlock(false);
  4086. cfg->setIndirectGotoBlock(IBlock);
  4087. }
  4088. // IndirectGoto is a control-flow statement. Thus we stop processing the
  4089. // current block and create a new one.
  4090. if (badCFG)
  4091. return nullptr;
  4092. Block = createBlock(false);
  4093. Block->setTerminator(I);
  4094. addSuccessor(Block, IBlock);
  4095. return addStmt(I->getTarget());
  4096. }
  4097. CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
  4098. TempDtorContext &Context) {
  4099. assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
  4100. tryAgain:
  4101. if (!E) {
  4102. badCFG = true;
  4103. return nullptr;
  4104. }
  4105. switch (E->getStmtClass()) {
  4106. default:
  4107. return VisitChildrenForTemporaryDtors(E, false, Context);
  4108. case Stmt::InitListExprClass:
  4109. return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
  4110. case Stmt::BinaryOperatorClass:
  4111. return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
  4112. ExternallyDestructed,
  4113. Context);
  4114. case Stmt::CXXBindTemporaryExprClass:
  4115. return VisitCXXBindTemporaryExprForTemporaryDtors(
  4116. cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
  4117. case Stmt::BinaryConditionalOperatorClass:
  4118. case Stmt::ConditionalOperatorClass:
  4119. return VisitConditionalOperatorForTemporaryDtors(
  4120. cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
  4121. case Stmt::ImplicitCastExprClass:
  4122. // For implicit cast we want ExternallyDestructed to be passed further.
  4123. E = cast<CastExpr>(E)->getSubExpr();
  4124. goto tryAgain;
  4125. case Stmt::CXXFunctionalCastExprClass:
  4126. // For functional cast we want ExternallyDestructed to be passed further.
  4127. E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
  4128. goto tryAgain;
  4129. case Stmt::ConstantExprClass:
  4130. E = cast<ConstantExpr>(E)->getSubExpr();
  4131. goto tryAgain;
  4132. case Stmt::ParenExprClass:
  4133. E = cast<ParenExpr>(E)->getSubExpr();
  4134. goto tryAgain;
  4135. case Stmt::MaterializeTemporaryExprClass: {
  4136. const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
  4137. ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
  4138. SmallVector<const Expr *, 2> CommaLHSs;
  4139. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4140. // Find the expression whose lifetime needs to be extended.
  4141. E = const_cast<Expr *>(
  4142. cast<MaterializeTemporaryExpr>(E)
  4143. ->getSubExpr()
  4144. ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
  4145. // Visit the skipped comma operator left-hand sides for other temporaries.
  4146. for (const Expr *CommaLHS : CommaLHSs) {
  4147. VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
  4148. /*ExternallyDestructed=*/false, Context);
  4149. }
  4150. goto tryAgain;
  4151. }
  4152. case Stmt::BlockExprClass:
  4153. // Don't recurse into blocks; their subexpressions don't get evaluated
  4154. // here.
  4155. return Block;
  4156. case Stmt::LambdaExprClass: {
  4157. // For lambda expressions, only recurse into the capture initializers,
  4158. // and not the body.
  4159. auto *LE = cast<LambdaExpr>(E);
  4160. CFGBlock *B = Block;
  4161. for (Expr *Init : LE->capture_inits()) {
  4162. if (Init) {
  4163. if (CFGBlock *R = VisitForTemporaryDtors(
  4164. Init, /*ExternallyDestructed=*/true, Context))
  4165. B = R;
  4166. }
  4167. }
  4168. return B;
  4169. }
  4170. case Stmt::StmtExprClass:
  4171. // Don't recurse into statement expressions; any cleanups inside them
  4172. // will be wrapped in their own ExprWithCleanups.
  4173. return Block;
  4174. case Stmt::CXXDefaultArgExprClass:
  4175. E = cast<CXXDefaultArgExpr>(E)->getExpr();
  4176. goto tryAgain;
  4177. case Stmt::CXXDefaultInitExprClass:
  4178. E = cast<CXXDefaultInitExpr>(E)->getExpr();
  4179. goto tryAgain;
  4180. }
  4181. }
  4182. CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
  4183. bool ExternallyDestructed,
  4184. TempDtorContext &Context) {
  4185. if (isa<LambdaExpr>(E)) {
  4186. // Do not visit the children of lambdas; they have their own CFGs.
  4187. return Block;
  4188. }
  4189. // When visiting children for destructors we want to visit them in reverse
  4190. // order that they will appear in the CFG. Because the CFG is built
  4191. // bottom-up, this means we visit them in their natural order, which
  4192. // reverses them in the CFG.
  4193. CFGBlock *B = Block;
  4194. for (Stmt *Child : E->children())
  4195. if (Child)
  4196. if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
  4197. B = R;
  4198. return B;
  4199. }
  4200. CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
  4201. BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
  4202. if (E->isCommaOp()) {
  4203. // For the comma operator, the LHS expression is evaluated before the RHS
  4204. // expression, so prepend temporary destructors for the LHS first.
  4205. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  4206. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
  4207. return RHSBlock ? RHSBlock : LHSBlock;
  4208. }
  4209. if (E->isLogicalOp()) {
  4210. VisitForTemporaryDtors(E->getLHS(), false, Context);
  4211. TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
  4212. if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
  4213. RHSExecuted.negate();
  4214. // We do not know at CFG-construction time whether the right-hand-side was
  4215. // executed, thus we add a branch node that depends on the temporary
  4216. // constructor call.
  4217. TempDtorContext RHSContext(
  4218. bothKnownTrue(Context.KnownExecuted, RHSExecuted));
  4219. VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
  4220. InsertTempDtorDecisionBlock(RHSContext);
  4221. return Block;
  4222. }
  4223. if (E->isAssignmentOp()) {
  4224. // For assignment operators, the RHS expression is evaluated before the LHS
  4225. // expression, so prepend temporary destructors for the RHS first.
  4226. CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
  4227. CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
  4228. return LHSBlock ? LHSBlock : RHSBlock;
  4229. }
  4230. // Any other operator is visited normally.
  4231. return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
  4232. }
  4233. CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
  4234. CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
  4235. // First add destructors for temporaries in subexpression.
  4236. // Because VisitCXXBindTemporaryExpr calls setDestructed:
  4237. CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
  4238. if (!ExternallyDestructed) {
  4239. // If lifetime of temporary is not prolonged (by assigning to constant
  4240. // reference) add destructor for it.
  4241. const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
  4242. if (Dtor->getParent()->isAnyDestructorNoReturn()) {
  4243. // If the destructor is marked as a no-return destructor, we need to
  4244. // create a new block for the destructor which does not have as a
  4245. // successor anything built thus far. Control won't flow out of this
  4246. // block.
  4247. if (B) Succ = B;
  4248. Block = createNoReturnBlock();
  4249. } else if (Context.needsTempDtorBranch()) {
  4250. // If we need to introduce a branch, we add a new block that we will hook
  4251. // up to a decision block later.
  4252. if (B) Succ = B;
  4253. Block = createBlock();
  4254. } else {
  4255. autoCreateBlock();
  4256. }
  4257. if (Context.needsTempDtorBranch()) {
  4258. Context.setDecisionPoint(Succ, E);
  4259. }
  4260. appendTemporaryDtor(Block, E);
  4261. B = Block;
  4262. }
  4263. return B;
  4264. }
  4265. void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
  4266. CFGBlock *FalseSucc) {
  4267. if (!Context.TerminatorExpr) {
  4268. // If no temporary was found, we do not need to insert a decision point.
  4269. return;
  4270. }
  4271. assert(Context.TerminatorExpr);
  4272. CFGBlock *Decision = createBlock(false);
  4273. Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
  4274. CFGTerminator::TemporaryDtorsBranch));
  4275. addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
  4276. addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
  4277. !Context.KnownExecuted.isTrue());
  4278. Block = Decision;
  4279. }
  4280. CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
  4281. AbstractConditionalOperator *E, bool ExternallyDestructed,
  4282. TempDtorContext &Context) {
  4283. VisitForTemporaryDtors(E->getCond(), false, Context);
  4284. CFGBlock *ConditionBlock = Block;
  4285. CFGBlock *ConditionSucc = Succ;
  4286. TryResult ConditionVal = tryEvaluateBool(E->getCond());
  4287. TryResult NegatedVal = ConditionVal;
  4288. if (NegatedVal.isKnown()) NegatedVal.negate();
  4289. TempDtorContext TrueContext(
  4290. bothKnownTrue(Context.KnownExecuted, ConditionVal));
  4291. VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
  4292. CFGBlock *TrueBlock = Block;
  4293. Block = ConditionBlock;
  4294. Succ = ConditionSucc;
  4295. TempDtorContext FalseContext(
  4296. bothKnownTrue(Context.KnownExecuted, NegatedVal));
  4297. VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
  4298. if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
  4299. InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
  4300. } else if (TrueContext.TerminatorExpr) {
  4301. Block = TrueBlock;
  4302. InsertTempDtorDecisionBlock(TrueContext);
  4303. } else {
  4304. InsertTempDtorDecisionBlock(FalseContext);
  4305. }
  4306. return Block;
  4307. }
  4308. CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
  4309. AddStmtChoice asc) {
  4310. if (asc.alwaysAdd(*this, D)) {
  4311. autoCreateBlock();
  4312. appendStmt(Block, D);
  4313. }
  4314. // Iterate over all used expression in clauses.
  4315. CFGBlock *B = Block;
  4316. // Reverse the elements to process them in natural order. Iterators are not
  4317. // bidirectional, so we need to create temp vector.
  4318. SmallVector<Stmt *, 8> Used(
  4319. OMPExecutableDirective::used_clauses_children(D->clauses()));
  4320. for (Stmt *S : llvm::reverse(Used)) {
  4321. assert(S && "Expected non-null used-in-clause child.");
  4322. if (CFGBlock *R = Visit(S))
  4323. B = R;
  4324. }
  4325. // Visit associated structured block if any.
  4326. if (!D->isStandaloneDirective()) {
  4327. Stmt *S = D->getRawStmt();
  4328. if (!isa<CompoundStmt>(S))
  4329. addLocalScopeAndDtors(S);
  4330. if (CFGBlock *R = addStmt(S))
  4331. B = R;
  4332. }
  4333. return B;
  4334. }
  4335. /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
  4336. /// no successors or predecessors. If this is the first block created in the
  4337. /// CFG, it is automatically set to be the Entry and Exit of the CFG.
  4338. CFGBlock *CFG::createBlock() {
  4339. bool first_block = begin() == end();
  4340. // Create the block.
  4341. CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
  4342. new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
  4343. Blocks.push_back(Mem, BlkBVC);
  4344. // If this is the first block, set it as the Entry and Exit.
  4345. if (first_block)
  4346. Entry = Exit = &back();
  4347. // Return the block.
  4348. return &back();
  4349. }
  4350. /// buildCFG - Constructs a CFG from an AST.
  4351. std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
  4352. ASTContext *C, const BuildOptions &BO) {
  4353. CFGBuilder Builder(C, BO);
  4354. return Builder.buildCFG(D, Statement);
  4355. }
  4356. bool CFG::isLinear() const {
  4357. // Quick path: if we only have the ENTRY block, the EXIT block, and some code
  4358. // in between, then we have no room for control flow.
  4359. if (size() <= 3)
  4360. return true;
  4361. // Traverse the CFG until we find a branch.
  4362. // TODO: While this should still be very fast,
  4363. // maybe we should cache the answer.
  4364. llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
  4365. const CFGBlock *B = Entry;
  4366. while (B != Exit) {
  4367. auto IteratorAndFlag = Visited.insert(B);
  4368. if (!IteratorAndFlag.second) {
  4369. // We looped back to a block that we've already visited. Not linear.
  4370. return false;
  4371. }
  4372. // Iterate over reachable successors.
  4373. const CFGBlock *FirstReachableB = nullptr;
  4374. for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
  4375. if (!AB.isReachable())
  4376. continue;
  4377. if (FirstReachableB == nullptr) {
  4378. FirstReachableB = &*AB;
  4379. } else {
  4380. // We've encountered a branch. It's not a linear CFG.
  4381. return false;
  4382. }
  4383. }
  4384. if (!FirstReachableB) {
  4385. // We reached a dead end. EXIT is unreachable. This is linear enough.
  4386. return true;
  4387. }
  4388. // There's only one way to move forward. Proceed.
  4389. B = FirstReachableB;
  4390. }
  4391. // We reached EXIT and found no branches.
  4392. return true;
  4393. }
  4394. const CXXDestructorDecl *
  4395. CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
  4396. switch (getKind()) {
  4397. case CFGElement::Initializer:
  4398. case CFGElement::NewAllocator:
  4399. case CFGElement::LoopExit:
  4400. case CFGElement::LifetimeEnds:
  4401. case CFGElement::Statement:
  4402. case CFGElement::Constructor:
  4403. case CFGElement::CXXRecordTypedCall:
  4404. case CFGElement::ScopeBegin:
  4405. case CFGElement::ScopeEnd:
  4406. llvm_unreachable("getDestructorDecl should only be used with "
  4407. "ImplicitDtors");
  4408. case CFGElement::AutomaticObjectDtor: {
  4409. const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
  4410. QualType ty = var->getType();
  4411. // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
  4412. //
  4413. // Lifetime-extending constructs are handled here. This works for a single
  4414. // temporary in an initializer expression.
  4415. if (ty->isReferenceType()) {
  4416. if (const Expr *Init = var->getInit()) {
  4417. ty = getReferenceInitTemporaryType(Init);
  4418. }
  4419. }
  4420. while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
  4421. ty = arrayType->getElementType();
  4422. }
  4423. // The situation when the type of the lifetime-extending reference
  4424. // does not correspond to the type of the object is supposed
  4425. // to be handled by now. In particular, 'ty' is now the unwrapped
  4426. // record type.
  4427. const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
  4428. assert(classDecl);
  4429. return classDecl->getDestructor();
  4430. }
  4431. case CFGElement::DeleteDtor: {
  4432. const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
  4433. QualType DTy = DE->getDestroyedType();
  4434. DTy = DTy.getNonReferenceType();
  4435. const CXXRecordDecl *classDecl =
  4436. astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
  4437. return classDecl->getDestructor();
  4438. }
  4439. case CFGElement::TemporaryDtor: {
  4440. const CXXBindTemporaryExpr *bindExpr =
  4441. castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
  4442. const CXXTemporary *temp = bindExpr->getTemporary();
  4443. return temp->getDestructor();
  4444. }
  4445. case CFGElement::MemberDtor: {
  4446. const FieldDecl *field = castAs<CFGMemberDtor>().getFieldDecl();
  4447. QualType ty = field->getType();
  4448. while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
  4449. ty = arrayType->getElementType();
  4450. }
  4451. const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
  4452. assert(classDecl);
  4453. return classDecl->getDestructor();
  4454. }
  4455. case CFGElement::BaseDtor:
  4456. // Not yet supported.
  4457. return nullptr;
  4458. }
  4459. llvm_unreachable("getKind() returned bogus value");
  4460. }
  4461. //===----------------------------------------------------------------------===//
  4462. // CFGBlock operations.
  4463. //===----------------------------------------------------------------------===//
  4464. CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
  4465. : ReachableBlock(IsReachable ? B : nullptr),
  4466. UnreachableBlock(!IsReachable ? B : nullptr,
  4467. B && IsReachable ? AB_Normal : AB_Unreachable) {}
  4468. CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
  4469. : ReachableBlock(B),
  4470. UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
  4471. B == AlternateBlock ? AB_Alternate : AB_Normal) {}
  4472. void CFGBlock::addSuccessor(AdjacentBlock Succ,
  4473. BumpVectorContext &C) {
  4474. if (CFGBlock *B = Succ.getReachableBlock())
  4475. B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
  4476. if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
  4477. UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
  4478. Succs.push_back(Succ, C);
  4479. }
  4480. bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
  4481. const CFGBlock *From, const CFGBlock *To) {
  4482. if (F.IgnoreNullPredecessors && !From)
  4483. return true;
  4484. if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
  4485. // If the 'To' has no label or is labeled but the label isn't a
  4486. // CaseStmt then filter this edge.
  4487. if (const SwitchStmt *S =
  4488. dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
  4489. if (S->isAllEnumCasesCovered()) {
  4490. const Stmt *L = To->getLabel();
  4491. if (!L || !isa<CaseStmt>(L))
  4492. return true;
  4493. }
  4494. }
  4495. }
  4496. return false;
  4497. }
  4498. //===----------------------------------------------------------------------===//
  4499. // CFG pretty printing
  4500. //===----------------------------------------------------------------------===//
  4501. namespace {
  4502. class StmtPrinterHelper : public PrinterHelper {
  4503. using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
  4504. using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
  4505. StmtMapTy StmtMap;
  4506. DeclMapTy DeclMap;
  4507. signed currentBlock = 0;
  4508. unsigned currStmt = 0;
  4509. const LangOptions &LangOpts;
  4510. public:
  4511. StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
  4512. : LangOpts(LO) {
  4513. if (!cfg)
  4514. return;
  4515. for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
  4516. unsigned j = 1;
  4517. for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
  4518. BI != BEnd; ++BI, ++j ) {
  4519. if (std::optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
  4520. const Stmt *stmt= SE->getStmt();
  4521. std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
  4522. StmtMap[stmt] = P;
  4523. switch (stmt->getStmtClass()) {
  4524. case Stmt::DeclStmtClass:
  4525. DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
  4526. break;
  4527. case Stmt::IfStmtClass: {
  4528. const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
  4529. if (var)
  4530. DeclMap[var] = P;
  4531. break;
  4532. }
  4533. case Stmt::ForStmtClass: {
  4534. const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
  4535. if (var)
  4536. DeclMap[var] = P;
  4537. break;
  4538. }
  4539. case Stmt::WhileStmtClass: {
  4540. const VarDecl *var =
  4541. cast<WhileStmt>(stmt)->getConditionVariable();
  4542. if (var)
  4543. DeclMap[var] = P;
  4544. break;
  4545. }
  4546. case Stmt::SwitchStmtClass: {
  4547. const VarDecl *var =
  4548. cast<SwitchStmt>(stmt)->getConditionVariable();
  4549. if (var)
  4550. DeclMap[var] = P;
  4551. break;
  4552. }
  4553. case Stmt::CXXCatchStmtClass: {
  4554. const VarDecl *var =
  4555. cast<CXXCatchStmt>(stmt)->getExceptionDecl();
  4556. if (var)
  4557. DeclMap[var] = P;
  4558. break;
  4559. }
  4560. default:
  4561. break;
  4562. }
  4563. }
  4564. }
  4565. }
  4566. }
  4567. ~StmtPrinterHelper() override = default;
  4568. const LangOptions &getLangOpts() const { return LangOpts; }
  4569. void setBlockID(signed i) { currentBlock = i; }
  4570. void setStmtID(unsigned i) { currStmt = i; }
  4571. bool handledStmt(Stmt *S, raw_ostream &OS) override {
  4572. StmtMapTy::iterator I = StmtMap.find(S);
  4573. if (I == StmtMap.end())
  4574. return false;
  4575. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  4576. && I->second.second == currStmt) {
  4577. return false;
  4578. }
  4579. OS << "[B" << I->second.first << "." << I->second.second << "]";
  4580. return true;
  4581. }
  4582. bool handleDecl(const Decl *D, raw_ostream &OS) {
  4583. DeclMapTy::iterator I = DeclMap.find(D);
  4584. if (I == DeclMap.end())
  4585. return false;
  4586. if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
  4587. && I->second.second == currStmt) {
  4588. return false;
  4589. }
  4590. OS << "[B" << I->second.first << "." << I->second.second << "]";
  4591. return true;
  4592. }
  4593. };
  4594. class CFGBlockTerminatorPrint
  4595. : public StmtVisitor<CFGBlockTerminatorPrint,void> {
  4596. raw_ostream &OS;
  4597. StmtPrinterHelper* Helper;
  4598. PrintingPolicy Policy;
  4599. public:
  4600. CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
  4601. const PrintingPolicy &Policy)
  4602. : OS(os), Helper(helper), Policy(Policy) {
  4603. this->Policy.IncludeNewlines = false;
  4604. }
  4605. void VisitIfStmt(IfStmt *I) {
  4606. OS << "if ";
  4607. if (Stmt *C = I->getCond())
  4608. C->printPretty(OS, Helper, Policy);
  4609. }
  4610. // Default case.
  4611. void VisitStmt(Stmt *Terminator) {
  4612. Terminator->printPretty(OS, Helper, Policy);
  4613. }
  4614. void VisitDeclStmt(DeclStmt *DS) {
  4615. VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  4616. OS << "static init " << VD->getName();
  4617. }
  4618. void VisitForStmt(ForStmt *F) {
  4619. OS << "for (" ;
  4620. if (F->getInit())
  4621. OS << "...";
  4622. OS << "; ";
  4623. if (Stmt *C = F->getCond())
  4624. C->printPretty(OS, Helper, Policy);
  4625. OS << "; ";
  4626. if (F->getInc())
  4627. OS << "...";
  4628. OS << ")";
  4629. }
  4630. void VisitWhileStmt(WhileStmt *W) {
  4631. OS << "while " ;
  4632. if (Stmt *C = W->getCond())
  4633. C->printPretty(OS, Helper, Policy);
  4634. }
  4635. void VisitDoStmt(DoStmt *D) {
  4636. OS << "do ... while ";
  4637. if (Stmt *C = D->getCond())
  4638. C->printPretty(OS, Helper, Policy);
  4639. }
  4640. void VisitSwitchStmt(SwitchStmt *Terminator) {
  4641. OS << "switch ";
  4642. Terminator->getCond()->printPretty(OS, Helper, Policy);
  4643. }
  4644. void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; }
  4645. void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; }
  4646. void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; }
  4647. void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
  4648. if (Stmt *Cond = C->getCond())
  4649. Cond->printPretty(OS, Helper, Policy);
  4650. OS << " ? ... : ...";
  4651. }
  4652. void VisitChooseExpr(ChooseExpr *C) {
  4653. OS << "__builtin_choose_expr( ";
  4654. if (Stmt *Cond = C->getCond())
  4655. Cond->printPretty(OS, Helper, Policy);
  4656. OS << " )";
  4657. }
  4658. void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
  4659. OS << "goto *";
  4660. if (Stmt *T = I->getTarget())
  4661. T->printPretty(OS, Helper, Policy);
  4662. }
  4663. void VisitBinaryOperator(BinaryOperator* B) {
  4664. if (!B->isLogicalOp()) {
  4665. VisitExpr(B);
  4666. return;
  4667. }
  4668. if (B->getLHS())
  4669. B->getLHS()->printPretty(OS, Helper, Policy);
  4670. switch (B->getOpcode()) {
  4671. case BO_LOr:
  4672. OS << " || ...";
  4673. return;
  4674. case BO_LAnd:
  4675. OS << " && ...";
  4676. return;
  4677. default:
  4678. llvm_unreachable("Invalid logical operator.");
  4679. }
  4680. }
  4681. void VisitExpr(Expr *E) {
  4682. E->printPretty(OS, Helper, Policy);
  4683. }
  4684. public:
  4685. void print(CFGTerminator T) {
  4686. switch (T.getKind()) {
  4687. case CFGTerminator::StmtBranch:
  4688. Visit(T.getStmt());
  4689. break;
  4690. case CFGTerminator::TemporaryDtorsBranch:
  4691. OS << "(Temp Dtor) ";
  4692. Visit(T.getStmt());
  4693. break;
  4694. case CFGTerminator::VirtualBaseBranch:
  4695. OS << "(See if most derived ctor has already initialized vbases)";
  4696. break;
  4697. }
  4698. }
  4699. };
  4700. } // namespace
  4701. static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
  4702. const CXXCtorInitializer *I) {
  4703. if (I->isBaseInitializer())
  4704. OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
  4705. else if (I->isDelegatingInitializer())
  4706. OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
  4707. else
  4708. OS << I->getAnyMember()->getName();
  4709. OS << "(";
  4710. if (Expr *IE = I->getInit())
  4711. IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  4712. OS << ")";
  4713. if (I->isBaseInitializer())
  4714. OS << " (Base initializer)";
  4715. else if (I->isDelegatingInitializer())
  4716. OS << " (Delegating initializer)";
  4717. else
  4718. OS << " (Member initializer)";
  4719. }
  4720. static void print_construction_context(raw_ostream &OS,
  4721. StmtPrinterHelper &Helper,
  4722. const ConstructionContext *CC) {
  4723. SmallVector<const Stmt *, 3> Stmts;
  4724. switch (CC->getKind()) {
  4725. case ConstructionContext::SimpleConstructorInitializerKind: {
  4726. OS << ", ";
  4727. const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
  4728. print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
  4729. return;
  4730. }
  4731. case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
  4732. OS << ", ";
  4733. const auto *CICC =
  4734. cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
  4735. print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
  4736. Stmts.push_back(CICC->getCXXBindTemporaryExpr());
  4737. break;
  4738. }
  4739. case ConstructionContext::SimpleVariableKind: {
  4740. const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
  4741. Stmts.push_back(SDSCC->getDeclStmt());
  4742. break;
  4743. }
  4744. case ConstructionContext::CXX17ElidedCopyVariableKind: {
  4745. const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
  4746. Stmts.push_back(CDSCC->getDeclStmt());
  4747. Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
  4748. break;
  4749. }
  4750. case ConstructionContext::NewAllocatedObjectKind: {
  4751. const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
  4752. Stmts.push_back(NECC->getCXXNewExpr());
  4753. break;
  4754. }
  4755. case ConstructionContext::SimpleReturnedValueKind: {
  4756. const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
  4757. Stmts.push_back(RSCC->getReturnStmt());
  4758. break;
  4759. }
  4760. case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
  4761. const auto *RSCC =
  4762. cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
  4763. Stmts.push_back(RSCC->getReturnStmt());
  4764. Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
  4765. break;
  4766. }
  4767. case ConstructionContext::SimpleTemporaryObjectKind: {
  4768. const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
  4769. Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
  4770. Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
  4771. break;
  4772. }
  4773. case ConstructionContext::ElidedTemporaryObjectKind: {
  4774. const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
  4775. Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
  4776. Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
  4777. Stmts.push_back(TOCC->getConstructorAfterElision());
  4778. break;
  4779. }
  4780. case ConstructionContext::LambdaCaptureKind: {
  4781. const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
  4782. Helper.handledStmt(const_cast<LambdaExpr *>(LCC->getLambdaExpr()), OS);
  4783. OS << "+" << LCC->getIndex();
  4784. return;
  4785. }
  4786. case ConstructionContext::ArgumentKind: {
  4787. const auto *ACC = cast<ArgumentConstructionContext>(CC);
  4788. if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
  4789. OS << ", ";
  4790. Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
  4791. }
  4792. OS << ", ";
  4793. Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
  4794. OS << "+" << ACC->getIndex();
  4795. return;
  4796. }
  4797. }
  4798. for (auto I: Stmts)
  4799. if (I) {
  4800. OS << ", ";
  4801. Helper.handledStmt(const_cast<Stmt *>(I), OS);
  4802. }
  4803. }
  4804. static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
  4805. const CFGElement &E);
  4806. void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
  4807. StmtPrinterHelper Helper(nullptr, {});
  4808. print_elem(OS, Helper, *this);
  4809. }
  4810. static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
  4811. const CFGElement &E) {
  4812. switch (E.getKind()) {
  4813. case CFGElement::Kind::Statement:
  4814. case CFGElement::Kind::CXXRecordTypedCall:
  4815. case CFGElement::Kind::Constructor: {
  4816. CFGStmt CS = E.castAs<CFGStmt>();
  4817. const Stmt *S = CS.getStmt();
  4818. assert(S != nullptr && "Expecting non-null Stmt");
  4819. // special printing for statement-expressions.
  4820. if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
  4821. const CompoundStmt *Sub = SE->getSubStmt();
  4822. auto Children = Sub->children();
  4823. if (Children.begin() != Children.end()) {
  4824. OS << "({ ... ; ";
  4825. Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
  4826. OS << " })\n";
  4827. return;
  4828. }
  4829. }
  4830. // special printing for comma expressions.
  4831. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
  4832. if (B->getOpcode() == BO_Comma) {
  4833. OS << "... , ";
  4834. Helper.handledStmt(B->getRHS(),OS);
  4835. OS << '\n';
  4836. return;
  4837. }
  4838. }
  4839. S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  4840. if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
  4841. if (isa<CXXOperatorCallExpr>(S))
  4842. OS << " (OperatorCall)";
  4843. OS << " (CXXRecordTypedCall";
  4844. print_construction_context(OS, Helper, VTC->getConstructionContext());
  4845. OS << ")";
  4846. } else if (isa<CXXOperatorCallExpr>(S)) {
  4847. OS << " (OperatorCall)";
  4848. } else if (isa<CXXBindTemporaryExpr>(S)) {
  4849. OS << " (BindTemporary)";
  4850. } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
  4851. OS << " (CXXConstructExpr";
  4852. if (std::optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
  4853. print_construction_context(OS, Helper, CE->getConstructionContext());
  4854. }
  4855. OS << ", " << CCE->getType() << ")";
  4856. } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
  4857. OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName()
  4858. << ", " << CE->getType() << ")";
  4859. }
  4860. // Expressions need a newline.
  4861. if (isa<Expr>(S))
  4862. OS << '\n';
  4863. break;
  4864. }
  4865. case CFGElement::Kind::Initializer:
  4866. print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
  4867. OS << '\n';
  4868. break;
  4869. case CFGElement::Kind::AutomaticObjectDtor: {
  4870. CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
  4871. const VarDecl *VD = DE.getVarDecl();
  4872. Helper.handleDecl(VD, OS);
  4873. QualType T = VD->getType();
  4874. if (T->isReferenceType())
  4875. T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
  4876. OS << ".~";
  4877. T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  4878. OS << "() (Implicit destructor)\n";
  4879. break;
  4880. }
  4881. case CFGElement::Kind::LifetimeEnds:
  4882. Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
  4883. OS << " (Lifetime ends)\n";
  4884. break;
  4885. case CFGElement::Kind::LoopExit:
  4886. OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
  4887. break;
  4888. case CFGElement::Kind::ScopeBegin:
  4889. OS << "CFGScopeBegin(";
  4890. if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
  4891. OS << VD->getQualifiedNameAsString();
  4892. OS << ")\n";
  4893. break;
  4894. case CFGElement::Kind::ScopeEnd:
  4895. OS << "CFGScopeEnd(";
  4896. if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
  4897. OS << VD->getQualifiedNameAsString();
  4898. OS << ")\n";
  4899. break;
  4900. case CFGElement::Kind::NewAllocator:
  4901. OS << "CFGNewAllocator(";
  4902. if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
  4903. AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  4904. OS << ")\n";
  4905. break;
  4906. case CFGElement::Kind::DeleteDtor: {
  4907. CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
  4908. const CXXRecordDecl *RD = DE.getCXXRecordDecl();
  4909. if (!RD)
  4910. return;
  4911. CXXDeleteExpr *DelExpr =
  4912. const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
  4913. Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
  4914. OS << "->~" << RD->getName().str() << "()";
  4915. OS << " (Implicit destructor)\n";
  4916. break;
  4917. }
  4918. case CFGElement::Kind::BaseDtor: {
  4919. const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
  4920. OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
  4921. OS << " (Base object destructor)\n";
  4922. break;
  4923. }
  4924. case CFGElement::Kind::MemberDtor: {
  4925. const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
  4926. const Type *T = FD->getType()->getBaseElementTypeUnsafe();
  4927. OS << "this->" << FD->getName();
  4928. OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
  4929. OS << " (Member object destructor)\n";
  4930. break;
  4931. }
  4932. case CFGElement::Kind::TemporaryDtor: {
  4933. const CXXBindTemporaryExpr *BT =
  4934. E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
  4935. OS << "~";
  4936. BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
  4937. OS << "() (Temporary object destructor)\n";
  4938. break;
  4939. }
  4940. }
  4941. }
  4942. static void print_block(raw_ostream &OS, const CFG* cfg,
  4943. const CFGBlock &B,
  4944. StmtPrinterHelper &Helper, bool print_edges,
  4945. bool ShowColors) {
  4946. Helper.setBlockID(B.getBlockID());
  4947. // Print the header.
  4948. if (ShowColors)
  4949. OS.changeColor(raw_ostream::YELLOW, true);
  4950. OS << "\n [B" << B.getBlockID();
  4951. if (&B == &cfg->getEntry())
  4952. OS << " (ENTRY)]\n";
  4953. else if (&B == &cfg->getExit())
  4954. OS << " (EXIT)]\n";
  4955. else if (&B == cfg->getIndirectGotoBlock())
  4956. OS << " (INDIRECT GOTO DISPATCH)]\n";
  4957. else if (B.hasNoReturnElement())
  4958. OS << " (NORETURN)]\n";
  4959. else
  4960. OS << "]\n";
  4961. if (ShowColors)
  4962. OS.resetColor();
  4963. // Print the label of this block.
  4964. if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
  4965. if (print_edges)
  4966. OS << " ";
  4967. if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
  4968. OS << L->getName();
  4969. else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  4970. OS << "case ";
  4971. if (const Expr *LHS = C->getLHS())
  4972. LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  4973. if (const Expr *RHS = C->getRHS()) {
  4974. OS << " ... ";
  4975. RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
  4976. }
  4977. } else if (isa<DefaultStmt>(Label))
  4978. OS << "default";
  4979. else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
  4980. OS << "catch (";
  4981. if (const VarDecl *ED = CS->getExceptionDecl())
  4982. ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
  4983. else
  4984. OS << "...";
  4985. OS << ")";
  4986. } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) {
  4987. OS << "@catch (";
  4988. if (const VarDecl *PD = CS->getCatchParamDecl())
  4989. PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
  4990. else
  4991. OS << "...";
  4992. OS << ")";
  4993. } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
  4994. OS << "__except (";
  4995. ES->getFilterExpr()->printPretty(OS, &Helper,
  4996. PrintingPolicy(Helper.getLangOpts()), 0);
  4997. OS << ")";
  4998. } else
  4999. llvm_unreachable("Invalid label statement in CFGBlock.");
  5000. OS << ":\n";
  5001. }
  5002. // Iterate through the statements in the block and print them.
  5003. unsigned j = 1;
  5004. for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
  5005. I != E ; ++I, ++j ) {
  5006. // Print the statement # in the basic block and the statement itself.
  5007. if (print_edges)
  5008. OS << " ";
  5009. OS << llvm::format("%3d", j) << ": ";
  5010. Helper.setStmtID(j);
  5011. print_elem(OS, Helper, *I);
  5012. }
  5013. // Print the terminator of this block.
  5014. if (B.getTerminator().isValid()) {
  5015. if (ShowColors)
  5016. OS.changeColor(raw_ostream::GREEN);
  5017. OS << " T: ";
  5018. Helper.setBlockID(-1);
  5019. PrintingPolicy PP(Helper.getLangOpts());
  5020. CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
  5021. TPrinter.print(B.getTerminator());
  5022. OS << '\n';
  5023. if (ShowColors)
  5024. OS.resetColor();
  5025. }
  5026. if (print_edges) {
  5027. // Print the predecessors of this block.
  5028. if (!B.pred_empty()) {
  5029. const raw_ostream::Colors Color = raw_ostream::BLUE;
  5030. if (ShowColors)
  5031. OS.changeColor(Color);
  5032. OS << " Preds " ;
  5033. if (ShowColors)
  5034. OS.resetColor();
  5035. OS << '(' << B.pred_size() << "):";
  5036. unsigned i = 0;
  5037. if (ShowColors)
  5038. OS.changeColor(Color);
  5039. for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
  5040. I != E; ++I, ++i) {
  5041. if (i % 10 == 8)
  5042. OS << "\n ";
  5043. CFGBlock *B = *I;
  5044. bool Reachable = true;
  5045. if (!B) {
  5046. Reachable = false;
  5047. B = I->getPossiblyUnreachableBlock();
  5048. }
  5049. OS << " B" << B->getBlockID();
  5050. if (!Reachable)
  5051. OS << "(Unreachable)";
  5052. }
  5053. if (ShowColors)
  5054. OS.resetColor();
  5055. OS << '\n';
  5056. }
  5057. // Print the successors of this block.
  5058. if (!B.succ_empty()) {
  5059. const raw_ostream::Colors Color = raw_ostream::MAGENTA;
  5060. if (ShowColors)
  5061. OS.changeColor(Color);
  5062. OS << " Succs ";
  5063. if (ShowColors)
  5064. OS.resetColor();
  5065. OS << '(' << B.succ_size() << "):";
  5066. unsigned i = 0;
  5067. if (ShowColors)
  5068. OS.changeColor(Color);
  5069. for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
  5070. I != E; ++I, ++i) {
  5071. if (i % 10 == 8)
  5072. OS << "\n ";
  5073. CFGBlock *B = *I;
  5074. bool Reachable = true;
  5075. if (!B) {
  5076. Reachable = false;
  5077. B = I->getPossiblyUnreachableBlock();
  5078. }
  5079. if (B) {
  5080. OS << " B" << B->getBlockID();
  5081. if (!Reachable)
  5082. OS << "(Unreachable)";
  5083. }
  5084. else {
  5085. OS << " NULL";
  5086. }
  5087. }
  5088. if (ShowColors)
  5089. OS.resetColor();
  5090. OS << '\n';
  5091. }
  5092. }
  5093. }
  5094. /// dump - A simple pretty printer of a CFG that outputs to stderr.
  5095. void CFG::dump(const LangOptions &LO, bool ShowColors) const {
  5096. print(llvm::errs(), LO, ShowColors);
  5097. }
  5098. /// print - A simple pretty printer of a CFG that outputs to an ostream.
  5099. void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
  5100. StmtPrinterHelper Helper(this, LO);
  5101. // Print the entry block.
  5102. print_block(OS, this, getEntry(), Helper, true, ShowColors);
  5103. // Iterate through the CFGBlocks and print them one by one.
  5104. for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
  5105. // Skip the entry block, because we already printed it.
  5106. if (&(**I) == &getEntry() || &(**I) == &getExit())
  5107. continue;
  5108. print_block(OS, this, **I, Helper, true, ShowColors);
  5109. }
  5110. // Print the exit block.
  5111. print_block(OS, this, getExit(), Helper, true, ShowColors);
  5112. OS << '\n';
  5113. OS.flush();
  5114. }
  5115. size_t CFGBlock::getIndexInCFG() const {
  5116. return llvm::find(*getParent(), this) - getParent()->begin();
  5117. }
  5118. /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
  5119. void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
  5120. bool ShowColors) const {
  5121. print(llvm::errs(), cfg, LO, ShowColors);
  5122. }
  5123. LLVM_DUMP_METHOD void CFGBlock::dump() const {
  5124. dump(getParent(), LangOptions(), false);
  5125. }
  5126. /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
  5127. /// Generally this will only be called from CFG::print.
  5128. void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
  5129. const LangOptions &LO, bool ShowColors) const {
  5130. StmtPrinterHelper Helper(cfg, LO);
  5131. print_block(OS, cfg, *this, Helper, true, ShowColors);
  5132. OS << '\n';
  5133. }
  5134. /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
  5135. void CFGBlock::printTerminator(raw_ostream &OS,
  5136. const LangOptions &LO) const {
  5137. CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
  5138. TPrinter.print(getTerminator());
  5139. }
  5140. /// printTerminatorJson - Pretty-prints the terminator in JSON format.
  5141. void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
  5142. bool AddQuotes) const {
  5143. std::string Buf;
  5144. llvm::raw_string_ostream TempOut(Buf);
  5145. printTerminator(TempOut, LO);
  5146. Out << JsonFormat(TempOut.str(), AddQuotes);
  5147. }
  5148. // Returns true if by simply looking at the block, we can be sure that it
  5149. // results in a sink during analysis. This is useful to know when the analysis
  5150. // was interrupted, and we try to figure out if it would sink eventually.
  5151. // There may be many more reasons why a sink would appear during analysis
  5152. // (eg. checkers may generate sinks arbitrarily), but here we only consider
  5153. // sinks that would be obvious by looking at the CFG.
  5154. static bool isImmediateSinkBlock(const CFGBlock *Blk) {
  5155. if (Blk->hasNoReturnElement())
  5156. return true;
  5157. // FIXME: Throw-expressions are currently generating sinks during analysis:
  5158. // they're not supported yet, and also often used for actually terminating
  5159. // the program. So we should treat them as sinks in this analysis as well,
  5160. // at least for now, but once we have better support for exceptions,
  5161. // we'd need to carefully handle the case when the throw is being
  5162. // immediately caught.
  5163. if (llvm::any_of(*Blk, [](const CFGElement &Elm) {
  5164. if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
  5165. if (isa<CXXThrowExpr>(StmtElm->getStmt()))
  5166. return true;
  5167. return false;
  5168. }))
  5169. return true;
  5170. return false;
  5171. }
  5172. bool CFGBlock::isInevitablySinking() const {
  5173. const CFG &Cfg = *getParent();
  5174. const CFGBlock *StartBlk = this;
  5175. if (isImmediateSinkBlock(StartBlk))
  5176. return true;
  5177. llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
  5178. llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
  5179. DFSWorkList.push_back(StartBlk);
  5180. while (!DFSWorkList.empty()) {
  5181. const CFGBlock *Blk = DFSWorkList.back();
  5182. DFSWorkList.pop_back();
  5183. Visited.insert(Blk);
  5184. // If at least one path reaches the CFG exit, it means that control is
  5185. // returned to the caller. For now, say that we are not sure what
  5186. // happens next. If necessary, this can be improved to analyze
  5187. // the parent StackFrameContext's call site in a similar manner.
  5188. if (Blk == &Cfg.getExit())
  5189. return false;
  5190. for (const auto &Succ : Blk->succs()) {
  5191. if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
  5192. if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
  5193. // If the block has reachable child blocks that aren't no-return,
  5194. // add them to the worklist.
  5195. DFSWorkList.push_back(SuccBlk);
  5196. }
  5197. }
  5198. }
  5199. }
  5200. // Nothing reached the exit. It can only mean one thing: there's no return.
  5201. return true;
  5202. }
  5203. const Expr *CFGBlock::getLastCondition() const {
  5204. // If the terminator is a temporary dtor or a virtual base, etc, we can't
  5205. // retrieve a meaningful condition, bail out.
  5206. if (Terminator.getKind() != CFGTerminator::StmtBranch)
  5207. return nullptr;
  5208. // Also, if this method was called on a block that doesn't have 2 successors,
  5209. // this block doesn't have retrievable condition.
  5210. if (succ_size() < 2)
  5211. return nullptr;
  5212. // FIXME: Is there a better condition expression we can return in this case?
  5213. if (size() == 0)
  5214. return nullptr;
  5215. auto StmtElem = rbegin()->getAs<CFGStmt>();
  5216. if (!StmtElem)
  5217. return nullptr;
  5218. const Stmt *Cond = StmtElem->getStmt();
  5219. if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond))
  5220. return nullptr;
  5221. // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
  5222. // the cast<>.
  5223. return cast<Expr>(Cond)->IgnoreParens();
  5224. }
  5225. Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
  5226. Stmt *Terminator = getTerminatorStmt();
  5227. if (!Terminator)
  5228. return nullptr;
  5229. Expr *E = nullptr;
  5230. switch (Terminator->getStmtClass()) {
  5231. default:
  5232. break;
  5233. case Stmt::CXXForRangeStmtClass:
  5234. E = cast<CXXForRangeStmt>(Terminator)->getCond();
  5235. break;
  5236. case Stmt::ForStmtClass:
  5237. E = cast<ForStmt>(Terminator)->getCond();
  5238. break;
  5239. case Stmt::WhileStmtClass:
  5240. E = cast<WhileStmt>(Terminator)->getCond();
  5241. break;
  5242. case Stmt::DoStmtClass:
  5243. E = cast<DoStmt>(Terminator)->getCond();
  5244. break;
  5245. case Stmt::IfStmtClass:
  5246. E = cast<IfStmt>(Terminator)->getCond();
  5247. break;
  5248. case Stmt::ChooseExprClass:
  5249. E = cast<ChooseExpr>(Terminator)->getCond();
  5250. break;
  5251. case Stmt::IndirectGotoStmtClass:
  5252. E = cast<IndirectGotoStmt>(Terminator)->getTarget();
  5253. break;
  5254. case Stmt::SwitchStmtClass:
  5255. E = cast<SwitchStmt>(Terminator)->getCond();
  5256. break;
  5257. case Stmt::BinaryConditionalOperatorClass:
  5258. E = cast<BinaryConditionalOperator>(Terminator)->getCond();
  5259. break;
  5260. case Stmt::ConditionalOperatorClass:
  5261. E = cast<ConditionalOperator>(Terminator)->getCond();
  5262. break;
  5263. case Stmt::BinaryOperatorClass: // '&&' and '||'
  5264. E = cast<BinaryOperator>(Terminator)->getLHS();
  5265. break;
  5266. case Stmt::ObjCForCollectionStmtClass:
  5267. return Terminator;
  5268. }
  5269. if (!StripParens)
  5270. return E;
  5271. return E ? E->IgnoreParens() : nullptr;
  5272. }
  5273. //===----------------------------------------------------------------------===//
  5274. // CFG Graphviz Visualization
  5275. //===----------------------------------------------------------------------===//
  5276. static StmtPrinterHelper *GraphHelper;
  5277. void CFG::viewCFG(const LangOptions &LO) const {
  5278. StmtPrinterHelper H(this, LO);
  5279. GraphHelper = &H;
  5280. llvm::ViewGraph(this,"CFG");
  5281. GraphHelper = nullptr;
  5282. }
  5283. namespace llvm {
  5284. template<>
  5285. struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
  5286. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  5287. static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
  5288. std::string OutSStr;
  5289. llvm::raw_string_ostream Out(OutSStr);
  5290. print_block(Out,Graph, *Node, *GraphHelper, false, false);
  5291. std::string& OutStr = Out.str();
  5292. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  5293. // Process string output to make it nicer...
  5294. for (unsigned i = 0; i != OutStr.length(); ++i)
  5295. if (OutStr[i] == '\n') { // Left justify
  5296. OutStr[i] = '\\';
  5297. OutStr.insert(OutStr.begin()+i+1, 'l');
  5298. }
  5299. return OutStr;
  5300. }
  5301. };
  5302. } // namespace llvm