CFG.cpp 203 KB

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