Expr.h 241 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the Expr interface and subclasses.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_AST_EXPR_H
  18. #define LLVM_CLANG_AST_EXPR_H
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTVector.h"
  21. #include "clang/AST/ComputeDependence.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclAccessPair.h"
  24. #include "clang/AST/DependenceFlags.h"
  25. #include "clang/AST/OperationKinds.h"
  26. #include "clang/AST/Stmt.h"
  27. #include "clang/AST/TemplateBase.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Basic/CharInfo.h"
  30. #include "clang/Basic/LangOptions.h"
  31. #include "clang/Basic/SyncScope.h"
  32. #include "clang/Basic/TypeTraits.h"
  33. #include "llvm/ADT/APFloat.h"
  34. #include "llvm/ADT/APSInt.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include "llvm/ADT/StringRef.h"
  37. #include "llvm/ADT/iterator.h"
  38. #include "llvm/ADT/iterator_range.h"
  39. #include "llvm/Support/AtomicOrdering.h"
  40. #include "llvm/Support/Compiler.h"
  41. #include "llvm/Support/TrailingObjects.h"
  42. namespace clang {
  43. class APValue;
  44. class ASTContext;
  45. class BlockDecl;
  46. class CXXBaseSpecifier;
  47. class CXXMemberCallExpr;
  48. class CXXOperatorCallExpr;
  49. class CastExpr;
  50. class Decl;
  51. class IdentifierInfo;
  52. class MaterializeTemporaryExpr;
  53. class NamedDecl;
  54. class ObjCPropertyRefExpr;
  55. class OpaqueValueExpr;
  56. class ParmVarDecl;
  57. class StringLiteral;
  58. class TargetInfo;
  59. class ValueDecl;
  60. /// A simple array of base specifiers.
  61. typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
  62. /// An adjustment to be made to the temporary created when emitting a
  63. /// reference binding, which accesses a particular subobject of that temporary.
  64. struct SubobjectAdjustment {
  65. enum {
  66. DerivedToBaseAdjustment,
  67. FieldAdjustment,
  68. MemberPointerAdjustment
  69. } Kind;
  70. struct DTB {
  71. const CastExpr *BasePath;
  72. const CXXRecordDecl *DerivedClass;
  73. };
  74. struct P {
  75. const MemberPointerType *MPT;
  76. Expr *RHS;
  77. };
  78. union {
  79. struct DTB DerivedToBase;
  80. FieldDecl *Field;
  81. struct P Ptr;
  82. };
  83. SubobjectAdjustment(const CastExpr *BasePath,
  84. const CXXRecordDecl *DerivedClass)
  85. : Kind(DerivedToBaseAdjustment) {
  86. DerivedToBase.BasePath = BasePath;
  87. DerivedToBase.DerivedClass = DerivedClass;
  88. }
  89. SubobjectAdjustment(FieldDecl *Field)
  90. : Kind(FieldAdjustment) {
  91. this->Field = Field;
  92. }
  93. SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
  94. : Kind(MemberPointerAdjustment) {
  95. this->Ptr.MPT = MPT;
  96. this->Ptr.RHS = RHS;
  97. }
  98. };
  99. /// This represents one expression. Note that Expr's are subclasses of Stmt.
  100. /// This allows an expression to be transparently used any place a Stmt is
  101. /// required.
  102. class Expr : public ValueStmt {
  103. QualType TR;
  104. public:
  105. Expr() = delete;
  106. Expr(const Expr&) = delete;
  107. Expr(Expr &&) = delete;
  108. Expr &operator=(const Expr&) = delete;
  109. Expr &operator=(Expr&&) = delete;
  110. protected:
  111. Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
  112. : ValueStmt(SC) {
  113. ExprBits.Dependent = 0;
  114. ExprBits.ValueKind = VK;
  115. ExprBits.ObjectKind = OK;
  116. assert(ExprBits.ObjectKind == OK && "truncated kind");
  117. setType(T);
  118. }
  119. /// Construct an empty expression.
  120. explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
  121. /// Each concrete expr subclass is expected to compute its dependence and call
  122. /// this in the constructor.
  123. void setDependence(ExprDependence Deps) {
  124. ExprBits.Dependent = static_cast<unsigned>(Deps);
  125. }
  126. friend class ASTImporter; // Sets dependence dircetly.
  127. friend class ASTStmtReader; // Sets dependence dircetly.
  128. public:
  129. QualType getType() const { return TR; }
  130. void setType(QualType t) {
  131. // In C++, the type of an expression is always adjusted so that it
  132. // will not have reference type (C++ [expr]p6). Use
  133. // QualType::getNonReferenceType() to retrieve the non-reference
  134. // type. Additionally, inspect Expr::isLvalue to determine whether
  135. // an expression that is adjusted in this manner should be
  136. // considered an lvalue.
  137. assert((t.isNull() || !t->isReferenceType()) &&
  138. "Expressions can't have reference type");
  139. TR = t;
  140. }
  141. ExprDependence getDependence() const {
  142. return static_cast<ExprDependence>(ExprBits.Dependent);
  143. }
  144. /// Determines whether the value of this expression depends on
  145. /// - a template parameter (C++ [temp.dep.constexpr])
  146. /// - or an error, whose resolution is unknown
  147. ///
  148. /// For example, the array bound of "Chars" in the following example is
  149. /// value-dependent.
  150. /// @code
  151. /// template<int Size, char (&Chars)[Size]> struct meta_string;
  152. /// @endcode
  153. bool isValueDependent() const {
  154. return static_cast<bool>(getDependence() & ExprDependence::Value);
  155. }
  156. /// Determines whether the type of this expression depends on
  157. /// - a template paramter (C++ [temp.dep.expr], which means that its type
  158. /// could change from one template instantiation to the next)
  159. /// - or an error
  160. ///
  161. /// For example, the expressions "x" and "x + y" are type-dependent in
  162. /// the following code, but "y" is not type-dependent:
  163. /// @code
  164. /// template<typename T>
  165. /// void add(T x, int y) {
  166. /// x + y;
  167. /// }
  168. /// @endcode
  169. bool isTypeDependent() const {
  170. return static_cast<bool>(getDependence() & ExprDependence::Type);
  171. }
  172. /// Whether this expression is instantiation-dependent, meaning that
  173. /// it depends in some way on
  174. /// - a template parameter (even if neither its type nor (constant) value
  175. /// can change due to the template instantiation)
  176. /// - or an error
  177. ///
  178. /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
  179. /// instantiation-dependent (since it involves a template parameter \c T), but
  180. /// is neither type- nor value-dependent, since the type of the inner
  181. /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
  182. /// \c sizeof is known.
  183. ///
  184. /// \code
  185. /// template<typename T>
  186. /// void f(T x, T y) {
  187. /// sizeof(sizeof(T() + T());
  188. /// }
  189. /// \endcode
  190. ///
  191. /// \code
  192. /// void func(int) {
  193. /// func(); // the expression is instantiation-dependent, because it depends
  194. /// // on an error.
  195. /// }
  196. /// \endcode
  197. bool isInstantiationDependent() const {
  198. return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
  199. }
  200. /// Whether this expression contains an unexpanded parameter
  201. /// pack (for C++11 variadic templates).
  202. ///
  203. /// Given the following function template:
  204. ///
  205. /// \code
  206. /// template<typename F, typename ...Types>
  207. /// void forward(const F &f, Types &&...args) {
  208. /// f(static_cast<Types&&>(args)...);
  209. /// }
  210. /// \endcode
  211. ///
  212. /// The expressions \c args and \c static_cast<Types&&>(args) both
  213. /// contain parameter packs.
  214. bool containsUnexpandedParameterPack() const {
  215. return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
  216. }
  217. /// Whether this expression contains subexpressions which had errors, e.g. a
  218. /// TypoExpr.
  219. bool containsErrors() const {
  220. return static_cast<bool>(getDependence() & ExprDependence::Error);
  221. }
  222. /// getExprLoc - Return the preferred location for the arrow when diagnosing
  223. /// a problem with a generic expression.
  224. SourceLocation getExprLoc() const LLVM_READONLY;
  225. /// Determine whether an lvalue-to-rvalue conversion should implicitly be
  226. /// applied to this expression if it appears as a discarded-value expression
  227. /// in C++11 onwards. This applies to certain forms of volatile glvalues.
  228. bool isReadIfDiscardedInCPlusPlus11() const;
  229. /// isUnusedResultAWarning - Return true if this immediate expression should
  230. /// be warned about if the result is unused. If so, fill in expr, location,
  231. /// and ranges with expr to warn on and source locations/ranges appropriate
  232. /// for a warning.
  233. bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
  234. SourceRange &R1, SourceRange &R2,
  235. ASTContext &Ctx) const;
  236. /// isLValue - True if this expression is an "l-value" according to
  237. /// the rules of the current language. C and C++ give somewhat
  238. /// different rules for this concept, but in general, the result of
  239. /// an l-value expression identifies a specific object whereas the
  240. /// result of an r-value expression is a value detached from any
  241. /// specific storage.
  242. ///
  243. /// C++11 divides the concept of "r-value" into pure r-values
  244. /// ("pr-values") and so-called expiring values ("x-values"), which
  245. /// identify specific objects that can be safely cannibalized for
  246. /// their resources.
  247. bool isLValue() const { return getValueKind() == VK_LValue; }
  248. bool isPRValue() const { return getValueKind() == VK_PRValue; }
  249. bool isXValue() const { return getValueKind() == VK_XValue; }
  250. bool isGLValue() const { return getValueKind() != VK_PRValue; }
  251. enum LValueClassification {
  252. LV_Valid,
  253. LV_NotObjectType,
  254. LV_IncompleteVoidType,
  255. LV_DuplicateVectorComponents,
  256. LV_InvalidExpression,
  257. LV_InvalidMessageExpression,
  258. LV_MemberFunction,
  259. LV_SubObjCPropertySetting,
  260. LV_ClassTemporary,
  261. LV_ArrayTemporary
  262. };
  263. /// Reasons why an expression might not be an l-value.
  264. LValueClassification ClassifyLValue(ASTContext &Ctx) const;
  265. enum isModifiableLvalueResult {
  266. MLV_Valid,
  267. MLV_NotObjectType,
  268. MLV_IncompleteVoidType,
  269. MLV_DuplicateVectorComponents,
  270. MLV_InvalidExpression,
  271. MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
  272. MLV_IncompleteType,
  273. MLV_ConstQualified,
  274. MLV_ConstQualifiedField,
  275. MLV_ConstAddrSpace,
  276. MLV_ArrayType,
  277. MLV_NoSetterProperty,
  278. MLV_MemberFunction,
  279. MLV_SubObjCPropertySetting,
  280. MLV_InvalidMessageExpression,
  281. MLV_ClassTemporary,
  282. MLV_ArrayTemporary
  283. };
  284. /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
  285. /// does not have an incomplete type, does not have a const-qualified type,
  286. /// and if it is a structure or union, does not have any member (including,
  287. /// recursively, any member or element of all contained aggregates or unions)
  288. /// with a const-qualified type.
  289. ///
  290. /// \param Loc [in,out] - A source location which *may* be filled
  291. /// in with the location of the expression making this a
  292. /// non-modifiable lvalue, if specified.
  293. isModifiableLvalueResult
  294. isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
  295. /// The return type of classify(). Represents the C++11 expression
  296. /// taxonomy.
  297. class Classification {
  298. public:
  299. /// The various classification results. Most of these mean prvalue.
  300. enum Kinds {
  301. CL_LValue,
  302. CL_XValue,
  303. CL_Function, // Functions cannot be lvalues in C.
  304. CL_Void, // Void cannot be an lvalue in C.
  305. CL_AddressableVoid, // Void expression whose address can be taken in C.
  306. CL_DuplicateVectorComponents, // A vector shuffle with dupes.
  307. CL_MemberFunction, // An expression referring to a member function
  308. CL_SubObjCPropertySetting,
  309. CL_ClassTemporary, // A temporary of class type, or subobject thereof.
  310. CL_ArrayTemporary, // A temporary of array type.
  311. CL_ObjCMessageRValue, // ObjC message is an rvalue
  312. CL_PRValue // A prvalue for any other reason, of any other type
  313. };
  314. /// The results of modification testing.
  315. enum ModifiableType {
  316. CM_Untested, // testModifiable was false.
  317. CM_Modifiable,
  318. CM_RValue, // Not modifiable because it's an rvalue
  319. CM_Function, // Not modifiable because it's a function; C++ only
  320. CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
  321. CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
  322. CM_ConstQualified,
  323. CM_ConstQualifiedField,
  324. CM_ConstAddrSpace,
  325. CM_ArrayType,
  326. CM_IncompleteType
  327. };
  328. private:
  329. friend class Expr;
  330. unsigned short Kind;
  331. unsigned short Modifiable;
  332. explicit Classification(Kinds k, ModifiableType m)
  333. : Kind(k), Modifiable(m)
  334. {}
  335. public:
  336. Classification() {}
  337. Kinds getKind() const { return static_cast<Kinds>(Kind); }
  338. ModifiableType getModifiable() const {
  339. assert(Modifiable != CM_Untested && "Did not test for modifiability.");
  340. return static_cast<ModifiableType>(Modifiable);
  341. }
  342. bool isLValue() const { return Kind == CL_LValue; }
  343. bool isXValue() const { return Kind == CL_XValue; }
  344. bool isGLValue() const { return Kind <= CL_XValue; }
  345. bool isPRValue() const { return Kind >= CL_Function; }
  346. bool isRValue() const { return Kind >= CL_XValue; }
  347. bool isModifiable() const { return getModifiable() == CM_Modifiable; }
  348. /// Create a simple, modifiably lvalue
  349. static Classification makeSimpleLValue() {
  350. return Classification(CL_LValue, CM_Modifiable);
  351. }
  352. };
  353. /// Classify - Classify this expression according to the C++11
  354. /// expression taxonomy.
  355. ///
  356. /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
  357. /// old lvalue vs rvalue. This function determines the type of expression this
  358. /// is. There are three expression types:
  359. /// - lvalues are classical lvalues as in C++03.
  360. /// - prvalues are equivalent to rvalues in C++03.
  361. /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
  362. /// function returning an rvalue reference.
  363. /// lvalues and xvalues are collectively referred to as glvalues, while
  364. /// prvalues and xvalues together form rvalues.
  365. Classification Classify(ASTContext &Ctx) const {
  366. return ClassifyImpl(Ctx, nullptr);
  367. }
  368. /// ClassifyModifiable - Classify this expression according to the
  369. /// C++11 expression taxonomy, and see if it is valid on the left side
  370. /// of an assignment.
  371. ///
  372. /// This function extends classify in that it also tests whether the
  373. /// expression is modifiable (C99 6.3.2.1p1).
  374. /// \param Loc A source location that might be filled with a relevant location
  375. /// if the expression is not modifiable.
  376. Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
  377. return ClassifyImpl(Ctx, &Loc);
  378. }
  379. /// Returns the set of floating point options that apply to this expression.
  380. /// Only meaningful for operations on floating point values.
  381. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
  382. /// getValueKindForType - Given a formal return or parameter type,
  383. /// give its value kind.
  384. static ExprValueKind getValueKindForType(QualType T) {
  385. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  386. return (isa<LValueReferenceType>(RT)
  387. ? VK_LValue
  388. : (RT->getPointeeType()->isFunctionType()
  389. ? VK_LValue : VK_XValue));
  390. return VK_PRValue;
  391. }
  392. /// getValueKind - The value kind that this expression produces.
  393. ExprValueKind getValueKind() const {
  394. return static_cast<ExprValueKind>(ExprBits.ValueKind);
  395. }
  396. /// getObjectKind - The object kind that this expression produces.
  397. /// Object kinds are meaningful only for expressions that yield an
  398. /// l-value or x-value.
  399. ExprObjectKind getObjectKind() const {
  400. return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
  401. }
  402. bool isOrdinaryOrBitFieldObject() const {
  403. ExprObjectKind OK = getObjectKind();
  404. return (OK == OK_Ordinary || OK == OK_BitField);
  405. }
  406. /// setValueKind - Set the value kind produced by this expression.
  407. void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
  408. /// setObjectKind - Set the object kind produced by this expression.
  409. void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
  410. private:
  411. Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
  412. public:
  413. /// Returns true if this expression is a gl-value that
  414. /// potentially refers to a bit-field.
  415. ///
  416. /// In C++, whether a gl-value refers to a bitfield is essentially
  417. /// an aspect of the value-kind type system.
  418. bool refersToBitField() const { return getObjectKind() == OK_BitField; }
  419. /// If this expression refers to a bit-field, retrieve the
  420. /// declaration of that bit-field.
  421. ///
  422. /// Note that this returns a non-null pointer in subtly different
  423. /// places than refersToBitField returns true. In particular, this can
  424. /// return a non-null pointer even for r-values loaded from
  425. /// bit-fields, but it will return null for a conditional bit-field.
  426. FieldDecl *getSourceBitField();
  427. const FieldDecl *getSourceBitField() const {
  428. return const_cast<Expr*>(this)->getSourceBitField();
  429. }
  430. Decl *getReferencedDeclOfCallee();
  431. const Decl *getReferencedDeclOfCallee() const {
  432. return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
  433. }
  434. /// If this expression is an l-value for an Objective C
  435. /// property, find the underlying property reference expression.
  436. const ObjCPropertyRefExpr *getObjCProperty() const;
  437. /// Check if this expression is the ObjC 'self' implicit parameter.
  438. bool isObjCSelfExpr() const;
  439. /// Returns whether this expression refers to a vector element.
  440. bool refersToVectorElement() const;
  441. /// Returns whether this expression refers to a matrix element.
  442. bool refersToMatrixElement() const {
  443. return getObjectKind() == OK_MatrixComponent;
  444. }
  445. /// Returns whether this expression refers to a global register
  446. /// variable.
  447. bool refersToGlobalRegisterVar() const;
  448. /// Returns whether this expression has a placeholder type.
  449. bool hasPlaceholderType() const {
  450. return getType()->isPlaceholderType();
  451. }
  452. /// Returns whether this expression has a specific placeholder type.
  453. bool hasPlaceholderType(BuiltinType::Kind K) const {
  454. assert(BuiltinType::isPlaceholderTypeKind(K));
  455. if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
  456. return BT->getKind() == K;
  457. return false;
  458. }
  459. /// isKnownToHaveBooleanValue - Return true if this is an integer expression
  460. /// that is known to return 0 or 1. This happens for _Bool/bool expressions
  461. /// but also int expressions which are produced by things like comparisons in
  462. /// C.
  463. ///
  464. /// \param Semantic If true, only return true for expressions that are known
  465. /// to be semantically boolean, which might not be true even for expressions
  466. /// that are known to evaluate to 0/1. For instance, reading an unsigned
  467. /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
  468. /// semantically correspond to a bool.
  469. bool isKnownToHaveBooleanValue(bool Semantic = true) const;
  470. /// isIntegerConstantExpr - Return the value if this expression is a valid
  471. /// integer constant expression. If not a valid i-c-e, return None and fill
  472. /// in Loc (if specified) with the location of the invalid expression.
  473. ///
  474. /// Note: This does not perform the implicit conversions required by C++11
  475. /// [expr.const]p5.
  476. Optional<llvm::APSInt> getIntegerConstantExpr(const ASTContext &Ctx,
  477. SourceLocation *Loc = nullptr,
  478. bool isEvaluated = true) const;
  479. bool isIntegerConstantExpr(const ASTContext &Ctx,
  480. SourceLocation *Loc = nullptr) const;
  481. /// isCXX98IntegralConstantExpr - Return true if this expression is an
  482. /// integral constant expression in C++98. Can only be used in C++.
  483. bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
  484. /// isCXX11ConstantExpr - Return true if this expression is a constant
  485. /// expression in C++11. Can only be used in C++.
  486. ///
  487. /// Note: This does not perform the implicit conversions required by C++11
  488. /// [expr.const]p5.
  489. bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
  490. SourceLocation *Loc = nullptr) const;
  491. /// isPotentialConstantExpr - Return true if this function's definition
  492. /// might be usable in a constant expression in C++11, if it were marked
  493. /// constexpr. Return false if the function can never produce a constant
  494. /// expression, along with diagnostics describing why not.
  495. static bool isPotentialConstantExpr(const FunctionDecl *FD,
  496. SmallVectorImpl<
  497. PartialDiagnosticAt> &Diags);
  498. /// isPotentialConstantExprUnevaluted - Return true if this expression might
  499. /// be usable in a constant expression in C++11 in an unevaluated context, if
  500. /// it were in function FD marked constexpr. Return false if the function can
  501. /// never produce a constant expression, along with diagnostics describing
  502. /// why not.
  503. static bool isPotentialConstantExprUnevaluated(Expr *E,
  504. const FunctionDecl *FD,
  505. SmallVectorImpl<
  506. PartialDiagnosticAt> &Diags);
  507. /// isConstantInitializer - Returns true if this expression can be emitted to
  508. /// IR as a constant, and thus can be used as a constant initializer in C.
  509. /// If this expression is not constant and Culprit is non-null,
  510. /// it is used to store the address of first non constant expr.
  511. bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
  512. const Expr **Culprit = nullptr) const;
  513. /// If this expression is an unambiguous reference to a single declaration,
  514. /// in the style of __builtin_function_start, return that declaration. Note
  515. /// that this may return a non-static member function or field in C++ if this
  516. /// expression is a member pointer constant.
  517. const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
  518. /// EvalStatus is a struct with detailed info about an evaluation in progress.
  519. struct EvalStatus {
  520. /// Whether the evaluated expression has side effects.
  521. /// For example, (f() && 0) can be folded, but it still has side effects.
  522. bool HasSideEffects;
  523. /// Whether the evaluation hit undefined behavior.
  524. /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
  525. /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
  526. bool HasUndefinedBehavior;
  527. /// Diag - If this is non-null, it will be filled in with a stack of notes
  528. /// indicating why evaluation failed (or why it failed to produce a constant
  529. /// expression).
  530. /// If the expression is unfoldable, the notes will indicate why it's not
  531. /// foldable. If the expression is foldable, but not a constant expression,
  532. /// the notes will describes why it isn't a constant expression. If the
  533. /// expression *is* a constant expression, no notes will be produced.
  534. SmallVectorImpl<PartialDiagnosticAt> *Diag;
  535. EvalStatus()
  536. : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
  537. // hasSideEffects - Return true if the evaluated expression has
  538. // side effects.
  539. bool hasSideEffects() const {
  540. return HasSideEffects;
  541. }
  542. };
  543. /// EvalResult is a struct with detailed info about an evaluated expression.
  544. struct EvalResult : EvalStatus {
  545. /// Val - This is the value the expression can be folded to.
  546. APValue Val;
  547. // isGlobalLValue - Return true if the evaluated lvalue expression
  548. // is global.
  549. bool isGlobalLValue() const;
  550. };
  551. /// EvaluateAsRValue - Return true if this is a constant which we can fold to
  552. /// an rvalue using any crazy technique (that has nothing to do with language
  553. /// standards) that we want to, even if the expression has side-effects. If
  554. /// this function returns true, it returns the folded constant in Result. If
  555. /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
  556. /// applied.
  557. bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  558. bool InConstantContext = false) const;
  559. /// EvaluateAsBooleanCondition - Return true if this is a constant
  560. /// which we can fold and convert to a boolean condition using
  561. /// any crazy technique that we want to, even if the expression has
  562. /// side-effects.
  563. bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  564. bool InConstantContext = false) const;
  565. enum SideEffectsKind {
  566. SE_NoSideEffects, ///< Strictly evaluate the expression.
  567. SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
  568. ///< arbitrary unmodeled side effects.
  569. SE_AllowSideEffects ///< Allow any unmodeled side effect.
  570. };
  571. /// EvaluateAsInt - Return true if this is a constant which we can fold and
  572. /// convert to an integer, using any crazy technique that we want to.
  573. bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  574. SideEffectsKind AllowSideEffects = SE_NoSideEffects,
  575. bool InConstantContext = false) const;
  576. /// EvaluateAsFloat - Return true if this is a constant which we can fold and
  577. /// convert to a floating point value, using any crazy technique that we
  578. /// want to.
  579. bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
  580. SideEffectsKind AllowSideEffects = SE_NoSideEffects,
  581. bool InConstantContext = false) const;
  582. /// EvaluateAsFloat - Return true if this is a constant which we can fold and
  583. /// convert to a fixed point value.
  584. bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  585. SideEffectsKind AllowSideEffects = SE_NoSideEffects,
  586. bool InConstantContext = false) const;
  587. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  588. /// constant folded without side-effects, but discard the result.
  589. bool isEvaluatable(const ASTContext &Ctx,
  590. SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
  591. /// HasSideEffects - This routine returns true for all those expressions
  592. /// which have any effect other than producing a value. Example is a function
  593. /// call, volatile variable read, or throwing an exception. If
  594. /// IncludePossibleEffects is false, this call treats certain expressions with
  595. /// potential side effects (such as function call-like expressions,
  596. /// instantiation-dependent expressions, or invocations from a macro) as not
  597. /// having side effects.
  598. bool HasSideEffects(const ASTContext &Ctx,
  599. bool IncludePossibleEffects = true) const;
  600. /// Determine whether this expression involves a call to any function
  601. /// that is not trivial.
  602. bool hasNonTrivialCall(const ASTContext &Ctx) const;
  603. /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
  604. /// integer. This must be called on an expression that constant folds to an
  605. /// integer.
  606. llvm::APSInt EvaluateKnownConstInt(
  607. const ASTContext &Ctx,
  608. SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
  609. llvm::APSInt EvaluateKnownConstIntCheckOverflow(
  610. const ASTContext &Ctx,
  611. SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
  612. void EvaluateForOverflow(const ASTContext &Ctx) const;
  613. /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
  614. /// lvalue with link time known address, with no side-effects.
  615. bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  616. bool InConstantContext = false) const;
  617. /// EvaluateAsInitializer - Evaluate an expression as if it were the
  618. /// initializer of the given declaration. Returns true if the initializer
  619. /// can be folded to a constant, and produces any relevant notes. In C++11,
  620. /// notes will be produced if the expression is not a constant expression.
  621. bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
  622. const VarDecl *VD,
  623. SmallVectorImpl<PartialDiagnosticAt> &Notes,
  624. bool IsConstantInitializer) const;
  625. /// EvaluateWithSubstitution - Evaluate an expression as if from the context
  626. /// of a call to the given function with the given arguments, inside an
  627. /// unevaluated context. Returns true if the expression could be folded to a
  628. /// constant.
  629. bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  630. const FunctionDecl *Callee,
  631. ArrayRef<const Expr*> Args,
  632. const Expr *This = nullptr) const;
  633. enum class ConstantExprKind {
  634. /// An integer constant expression (an array bound, enumerator, case value,
  635. /// bit-field width, or similar) or similar.
  636. Normal,
  637. /// A non-class template argument. Such a value is only used for mangling,
  638. /// not for code generation, so can refer to dllimported functions.
  639. NonClassTemplateArgument,
  640. /// A class template argument. Such a value is used for code generation.
  641. ClassTemplateArgument,
  642. /// An immediate invocation. The destruction of the end result of this
  643. /// evaluation is not part of the evaluation, but all other temporaries
  644. /// are destroyed.
  645. ImmediateInvocation,
  646. };
  647. /// Evaluate an expression that is required to be a constant expression. Does
  648. /// not check the syntactic constraints for C and C++98 constant expressions.
  649. bool EvaluateAsConstantExpr(
  650. EvalResult &Result, const ASTContext &Ctx,
  651. ConstantExprKind Kind = ConstantExprKind::Normal) const;
  652. /// If the current Expr is a pointer, this will try to statically
  653. /// determine the number of bytes available where the pointer is pointing.
  654. /// Returns true if all of the above holds and we were able to figure out the
  655. /// size, false otherwise.
  656. ///
  657. /// \param Type - How to evaluate the size of the Expr, as defined by the
  658. /// "type" parameter of __builtin_object_size
  659. bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  660. unsigned Type) const;
  661. /// If the current Expr is a pointer, this will try to statically
  662. /// determine the strlen of the string pointed to.
  663. /// Returns true if all of the above holds and we were able to figure out the
  664. /// strlen, false otherwise.
  665. bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
  666. /// Enumeration used to describe the kind of Null pointer constant
  667. /// returned from \c isNullPointerConstant().
  668. enum NullPointerConstantKind {
  669. /// Expression is not a Null pointer constant.
  670. NPCK_NotNull = 0,
  671. /// Expression is a Null pointer constant built from a zero integer
  672. /// expression that is not a simple, possibly parenthesized, zero literal.
  673. /// C++ Core Issue 903 will classify these expressions as "not pointers"
  674. /// once it is adopted.
  675. /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  676. NPCK_ZeroExpression,
  677. /// Expression is a Null pointer constant built from a literal zero.
  678. NPCK_ZeroLiteral,
  679. /// Expression is a C++11 nullptr.
  680. NPCK_CXX11_nullptr,
  681. /// Expression is a GNU-style __null constant.
  682. NPCK_GNUNull
  683. };
  684. /// Enumeration used to describe how \c isNullPointerConstant()
  685. /// should cope with value-dependent expressions.
  686. enum NullPointerConstantValueDependence {
  687. /// Specifies that the expression should never be value-dependent.
  688. NPC_NeverValueDependent = 0,
  689. /// Specifies that a value-dependent expression of integral or
  690. /// dependent type should be considered a null pointer constant.
  691. NPC_ValueDependentIsNull,
  692. /// Specifies that a value-dependent expression should be considered
  693. /// to never be a null pointer constant.
  694. NPC_ValueDependentIsNotNull
  695. };
  696. /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
  697. /// a Null pointer constant. The return value can further distinguish the
  698. /// kind of NULL pointer constant that was detected.
  699. NullPointerConstantKind isNullPointerConstant(
  700. ASTContext &Ctx,
  701. NullPointerConstantValueDependence NPC) const;
  702. /// isOBJCGCCandidate - Return true if this expression may be used in a read/
  703. /// write barrier.
  704. bool isOBJCGCCandidate(ASTContext &Ctx) const;
  705. /// Returns true if this expression is a bound member function.
  706. bool isBoundMemberFunction(ASTContext &Ctx) const;
  707. /// Given an expression of bound-member type, find the type
  708. /// of the member. Returns null if this is an *overloaded* bound
  709. /// member expression.
  710. static QualType findBoundMemberType(const Expr *expr);
  711. /// Skip past any invisble AST nodes which might surround this
  712. /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
  713. /// but also injected CXXMemberExpr and CXXConstructExpr which represent
  714. /// implicit conversions.
  715. Expr *IgnoreUnlessSpelledInSource();
  716. const Expr *IgnoreUnlessSpelledInSource() const {
  717. return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
  718. }
  719. /// Skip past any implicit casts which might surround this expression until
  720. /// reaching a fixed point. Skips:
  721. /// * ImplicitCastExpr
  722. /// * FullExpr
  723. Expr *IgnoreImpCasts() LLVM_READONLY;
  724. const Expr *IgnoreImpCasts() const {
  725. return const_cast<Expr *>(this)->IgnoreImpCasts();
  726. }
  727. /// Skip past any casts which might surround this expression until reaching
  728. /// a fixed point. Skips:
  729. /// * CastExpr
  730. /// * FullExpr
  731. /// * MaterializeTemporaryExpr
  732. /// * SubstNonTypeTemplateParmExpr
  733. Expr *IgnoreCasts() LLVM_READONLY;
  734. const Expr *IgnoreCasts() const {
  735. return const_cast<Expr *>(this)->IgnoreCasts();
  736. }
  737. /// Skip past any implicit AST nodes which might surround this expression
  738. /// until reaching a fixed point. Skips:
  739. /// * What IgnoreImpCasts() skips
  740. /// * MaterializeTemporaryExpr
  741. /// * CXXBindTemporaryExpr
  742. Expr *IgnoreImplicit() LLVM_READONLY;
  743. const Expr *IgnoreImplicit() const {
  744. return const_cast<Expr *>(this)->IgnoreImplicit();
  745. }
  746. /// Skip past any implicit AST nodes which might surround this expression
  747. /// until reaching a fixed point. Same as IgnoreImplicit, except that it
  748. /// also skips over implicit calls to constructors and conversion functions.
  749. ///
  750. /// FIXME: Should IgnoreImplicit do this?
  751. Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
  752. const Expr *IgnoreImplicitAsWritten() const {
  753. return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
  754. }
  755. /// Skip past any parentheses which might surround this expression until
  756. /// reaching a fixed point. Skips:
  757. /// * ParenExpr
  758. /// * UnaryOperator if `UO_Extension`
  759. /// * GenericSelectionExpr if `!isResultDependent()`
  760. /// * ChooseExpr if `!isConditionDependent()`
  761. /// * ConstantExpr
  762. Expr *IgnoreParens() LLVM_READONLY;
  763. const Expr *IgnoreParens() const {
  764. return const_cast<Expr *>(this)->IgnoreParens();
  765. }
  766. /// Skip past any parentheses and implicit casts which might surround this
  767. /// expression until reaching a fixed point.
  768. /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
  769. /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
  770. /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
  771. /// * What IgnoreParens() skips
  772. /// * What IgnoreImpCasts() skips
  773. /// * MaterializeTemporaryExpr
  774. /// * SubstNonTypeTemplateParmExpr
  775. Expr *IgnoreParenImpCasts() LLVM_READONLY;
  776. const Expr *IgnoreParenImpCasts() const {
  777. return const_cast<Expr *>(this)->IgnoreParenImpCasts();
  778. }
  779. /// Skip past any parentheses and casts which might surround this expression
  780. /// until reaching a fixed point. Skips:
  781. /// * What IgnoreParens() skips
  782. /// * What IgnoreCasts() skips
  783. Expr *IgnoreParenCasts() LLVM_READONLY;
  784. const Expr *IgnoreParenCasts() const {
  785. return const_cast<Expr *>(this)->IgnoreParenCasts();
  786. }
  787. /// Skip conversion operators. If this Expr is a call to a conversion
  788. /// operator, return the argument.
  789. Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
  790. const Expr *IgnoreConversionOperatorSingleStep() const {
  791. return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
  792. }
  793. /// Skip past any parentheses and lvalue casts which might surround this
  794. /// expression until reaching a fixed point. Skips:
  795. /// * What IgnoreParens() skips
  796. /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
  797. /// casts are skipped
  798. /// FIXME: This is intended purely as a temporary workaround for code
  799. /// that hasn't yet been rewritten to do the right thing about those
  800. /// casts, and may disappear along with the last internal use.
  801. Expr *IgnoreParenLValueCasts() LLVM_READONLY;
  802. const Expr *IgnoreParenLValueCasts() const {
  803. return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
  804. }
  805. /// Skip past any parenthese and casts which do not change the value
  806. /// (including ptr->int casts of the same size) until reaching a fixed point.
  807. /// Skips:
  808. /// * What IgnoreParens() skips
  809. /// * CastExpr which do not change the value
  810. /// * SubstNonTypeTemplateParmExpr
  811. Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
  812. const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
  813. return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
  814. }
  815. /// Skip past any parentheses and derived-to-base casts until reaching a
  816. /// fixed point. Skips:
  817. /// * What IgnoreParens() skips
  818. /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
  819. /// CK_UncheckedDerivedToBase and CK_NoOp)
  820. Expr *IgnoreParenBaseCasts() LLVM_READONLY;
  821. const Expr *IgnoreParenBaseCasts() const {
  822. return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
  823. }
  824. /// Determine whether this expression is a default function argument.
  825. ///
  826. /// Default arguments are implicitly generated in the abstract syntax tree
  827. /// by semantic analysis for function calls, object constructions, etc. in
  828. /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
  829. /// this routine also looks through any implicit casts to determine whether
  830. /// the expression is a default argument.
  831. bool isDefaultArgument() const;
  832. /// Determine whether the result of this expression is a
  833. /// temporary object of the given class type.
  834. bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
  835. /// Whether this expression is an implicit reference to 'this' in C++.
  836. bool isImplicitCXXThis() const;
  837. static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
  838. /// For an expression of class type or pointer to class type,
  839. /// return the most derived class decl the expression is known to refer to.
  840. ///
  841. /// If this expression is a cast, this method looks through it to find the
  842. /// most derived decl that can be inferred from the expression.
  843. /// This is valid because derived-to-base conversions have undefined
  844. /// behavior if the object isn't dynamically of the derived type.
  845. const CXXRecordDecl *getBestDynamicClassType() const;
  846. /// Get the inner expression that determines the best dynamic class.
  847. /// If this is a prvalue, we guarantee that it is of the most-derived type
  848. /// for the object itself.
  849. const Expr *getBestDynamicClassTypeExpr() const;
  850. /// Walk outwards from an expression we want to bind a reference to and
  851. /// find the expression whose lifetime needs to be extended. Record
  852. /// the LHSs of comma expressions and adjustments needed along the path.
  853. const Expr *skipRValueSubobjectAdjustments(
  854. SmallVectorImpl<const Expr *> &CommaLHS,
  855. SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
  856. const Expr *skipRValueSubobjectAdjustments() const {
  857. SmallVector<const Expr *, 8> CommaLHSs;
  858. SmallVector<SubobjectAdjustment, 8> Adjustments;
  859. return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  860. }
  861. /// Checks that the two Expr's will refer to the same value as a comparison
  862. /// operand. The caller must ensure that the values referenced by the Expr's
  863. /// are not modified between E1 and E2 or the result my be invalid.
  864. static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
  865. static bool classof(const Stmt *T) {
  866. return T->getStmtClass() >= firstExprConstant &&
  867. T->getStmtClass() <= lastExprConstant;
  868. }
  869. };
  870. // PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
  871. // Expr. Verify that we got it right.
  872. static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
  873. llvm::detail::ConstantLog2<alignof(Expr)>::value,
  874. "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
  875. using ConstantExprKind = Expr::ConstantExprKind;
  876. //===----------------------------------------------------------------------===//
  877. // Wrapper Expressions.
  878. //===----------------------------------------------------------------------===//
  879. /// FullExpr - Represents a "full-expression" node.
  880. class FullExpr : public Expr {
  881. protected:
  882. Stmt *SubExpr;
  883. FullExpr(StmtClass SC, Expr *subexpr)
  884. : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
  885. subexpr->getObjectKind()),
  886. SubExpr(subexpr) {
  887. setDependence(computeDependence(this));
  888. }
  889. FullExpr(StmtClass SC, EmptyShell Empty)
  890. : Expr(SC, Empty) {}
  891. public:
  892. const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
  893. Expr *getSubExpr() { return cast<Expr>(SubExpr); }
  894. /// As with any mutator of the AST, be very careful when modifying an
  895. /// existing AST to preserve its invariants.
  896. void setSubExpr(Expr *E) { SubExpr = E; }
  897. static bool classof(const Stmt *T) {
  898. return T->getStmtClass() >= firstFullExprConstant &&
  899. T->getStmtClass() <= lastFullExprConstant;
  900. }
  901. };
  902. /// ConstantExpr - An expression that occurs in a constant context and
  903. /// optionally the result of evaluating the expression.
  904. class ConstantExpr final
  905. : public FullExpr,
  906. private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
  907. static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
  908. "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
  909. "for tail-allocated storage");
  910. friend TrailingObjects;
  911. friend class ASTStmtReader;
  912. friend class ASTStmtWriter;
  913. public:
  914. /// Describes the kind of result that can be tail-allocated.
  915. enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
  916. private:
  917. size_t numTrailingObjects(OverloadToken<APValue>) const {
  918. return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
  919. }
  920. size_t numTrailingObjects(OverloadToken<uint64_t>) const {
  921. return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
  922. }
  923. uint64_t &Int64Result() {
  924. assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
  925. "invalid accessor");
  926. return *getTrailingObjects<uint64_t>();
  927. }
  928. const uint64_t &Int64Result() const {
  929. return const_cast<ConstantExpr *>(this)->Int64Result();
  930. }
  931. APValue &APValueResult() {
  932. assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
  933. "invalid accessor");
  934. return *getTrailingObjects<APValue>();
  935. }
  936. APValue &APValueResult() const {
  937. return const_cast<ConstantExpr *>(this)->APValueResult();
  938. }
  939. ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
  940. bool IsImmediateInvocation);
  941. ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind);
  942. public:
  943. static ConstantExpr *Create(const ASTContext &Context, Expr *E,
  944. const APValue &Result);
  945. static ConstantExpr *Create(const ASTContext &Context, Expr *E,
  946. ResultStorageKind Storage = RSK_None,
  947. bool IsImmediateInvocation = false);
  948. static ConstantExpr *CreateEmpty(const ASTContext &Context,
  949. ResultStorageKind StorageKind);
  950. static ResultStorageKind getStorageKind(const APValue &Value);
  951. static ResultStorageKind getStorageKind(const Type *T,
  952. const ASTContext &Context);
  953. SourceLocation getBeginLoc() const LLVM_READONLY {
  954. return SubExpr->getBeginLoc();
  955. }
  956. SourceLocation getEndLoc() const LLVM_READONLY {
  957. return SubExpr->getEndLoc();
  958. }
  959. static bool classof(const Stmt *T) {
  960. return T->getStmtClass() == ConstantExprClass;
  961. }
  962. void SetResult(APValue Value, const ASTContext &Context) {
  963. MoveIntoResult(Value, Context);
  964. }
  965. void MoveIntoResult(APValue &Value, const ASTContext &Context);
  966. APValue::ValueKind getResultAPValueKind() const {
  967. return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
  968. }
  969. ResultStorageKind getResultStorageKind() const {
  970. return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
  971. }
  972. bool isImmediateInvocation() const {
  973. return ConstantExprBits.IsImmediateInvocation;
  974. }
  975. bool hasAPValueResult() const {
  976. return ConstantExprBits.APValueKind != APValue::None;
  977. }
  978. APValue getAPValueResult() const;
  979. APValue &getResultAsAPValue() const { return APValueResult(); }
  980. llvm::APSInt getResultAsAPSInt() const;
  981. // Iterators
  982. child_range children() { return child_range(&SubExpr, &SubExpr+1); }
  983. const_child_range children() const {
  984. return const_child_range(&SubExpr, &SubExpr + 1);
  985. }
  986. };
  987. //===----------------------------------------------------------------------===//
  988. // Primary Expressions.
  989. //===----------------------------------------------------------------------===//
  990. /// OpaqueValueExpr - An expression referring to an opaque object of a
  991. /// fixed type and value class. These don't correspond to concrete
  992. /// syntax; instead they're used to express operations (usually copy
  993. /// operations) on values whose source is generally obvious from
  994. /// context.
  995. class OpaqueValueExpr : public Expr {
  996. friend class ASTStmtReader;
  997. Expr *SourceExpr;
  998. public:
  999. OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
  1000. ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
  1001. : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
  1002. setIsUnique(false);
  1003. OpaqueValueExprBits.Loc = Loc;
  1004. setDependence(computeDependence(this));
  1005. }
  1006. /// Given an expression which invokes a copy constructor --- i.e. a
  1007. /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
  1008. /// find the OpaqueValueExpr that's the source of the construction.
  1009. static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
  1010. explicit OpaqueValueExpr(EmptyShell Empty)
  1011. : Expr(OpaqueValueExprClass, Empty) {}
  1012. /// Retrieve the location of this expression.
  1013. SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
  1014. SourceLocation getBeginLoc() const LLVM_READONLY {
  1015. return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
  1016. }
  1017. SourceLocation getEndLoc() const LLVM_READONLY {
  1018. return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
  1019. }
  1020. SourceLocation getExprLoc() const LLVM_READONLY {
  1021. return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
  1022. }
  1023. child_range children() {
  1024. return child_range(child_iterator(), child_iterator());
  1025. }
  1026. const_child_range children() const {
  1027. return const_child_range(const_child_iterator(), const_child_iterator());
  1028. }
  1029. /// The source expression of an opaque value expression is the
  1030. /// expression which originally generated the value. This is
  1031. /// provided as a convenience for analyses that don't wish to
  1032. /// precisely model the execution behavior of the program.
  1033. ///
  1034. /// The source expression is typically set when building the
  1035. /// expression which binds the opaque value expression in the first
  1036. /// place.
  1037. Expr *getSourceExpr() const { return SourceExpr; }
  1038. void setIsUnique(bool V) {
  1039. assert((!V || SourceExpr) &&
  1040. "unique OVEs are expected to have source expressions");
  1041. OpaqueValueExprBits.IsUnique = V;
  1042. }
  1043. bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
  1044. static bool classof(const Stmt *T) {
  1045. return T->getStmtClass() == OpaqueValueExprClass;
  1046. }
  1047. };
  1048. /// A reference to a declared variable, function, enum, etc.
  1049. /// [C99 6.5.1p2]
  1050. ///
  1051. /// This encodes all the information about how a declaration is referenced
  1052. /// within an expression.
  1053. ///
  1054. /// There are several optional constructs attached to DeclRefExprs only when
  1055. /// they apply in order to conserve memory. These are laid out past the end of
  1056. /// the object, and flags in the DeclRefExprBitfield track whether they exist:
  1057. ///
  1058. /// DeclRefExprBits.HasQualifier:
  1059. /// Specifies when this declaration reference expression has a C++
  1060. /// nested-name-specifier.
  1061. /// DeclRefExprBits.HasFoundDecl:
  1062. /// Specifies when this declaration reference expression has a record of
  1063. /// a NamedDecl (different from the referenced ValueDecl) which was found
  1064. /// during name lookup and/or overload resolution.
  1065. /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
  1066. /// Specifies when this declaration reference expression has an explicit
  1067. /// C++ template keyword and/or template argument list.
  1068. /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
  1069. /// Specifies when this declaration reference expression (validly)
  1070. /// refers to an enclosed local or a captured variable.
  1071. class DeclRefExpr final
  1072. : public Expr,
  1073. private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
  1074. NamedDecl *, ASTTemplateKWAndArgsInfo,
  1075. TemplateArgumentLoc> {
  1076. friend class ASTStmtReader;
  1077. friend class ASTStmtWriter;
  1078. friend TrailingObjects;
  1079. /// The declaration that we are referencing.
  1080. ValueDecl *D;
  1081. /// Provides source/type location info for the declaration name
  1082. /// embedded in D.
  1083. DeclarationNameLoc DNLoc;
  1084. size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
  1085. return hasQualifier();
  1086. }
  1087. size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
  1088. return hasFoundDecl();
  1089. }
  1090. size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
  1091. return hasTemplateKWAndArgsInfo();
  1092. }
  1093. /// Test whether there is a distinct FoundDecl attached to the end of
  1094. /// this DRE.
  1095. bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
  1096. DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
  1097. SourceLocation TemplateKWLoc, ValueDecl *D,
  1098. bool RefersToEnlosingVariableOrCapture,
  1099. const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
  1100. const TemplateArgumentListInfo *TemplateArgs, QualType T,
  1101. ExprValueKind VK, NonOdrUseReason NOUR);
  1102. /// Construct an empty declaration reference expression.
  1103. explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
  1104. public:
  1105. DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
  1106. bool RefersToEnclosingVariableOrCapture, QualType T,
  1107. ExprValueKind VK, SourceLocation L,
  1108. const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
  1109. NonOdrUseReason NOUR = NOUR_None);
  1110. static DeclRefExpr *
  1111. Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
  1112. SourceLocation TemplateKWLoc, ValueDecl *D,
  1113. bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
  1114. QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
  1115. const TemplateArgumentListInfo *TemplateArgs = nullptr,
  1116. NonOdrUseReason NOUR = NOUR_None);
  1117. static DeclRefExpr *
  1118. Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
  1119. SourceLocation TemplateKWLoc, ValueDecl *D,
  1120. bool RefersToEnclosingVariableOrCapture,
  1121. const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
  1122. NamedDecl *FoundD = nullptr,
  1123. const TemplateArgumentListInfo *TemplateArgs = nullptr,
  1124. NonOdrUseReason NOUR = NOUR_None);
  1125. /// Construct an empty declaration reference expression.
  1126. static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
  1127. bool HasFoundDecl,
  1128. bool HasTemplateKWAndArgsInfo,
  1129. unsigned NumTemplateArgs);
  1130. ValueDecl *getDecl() { return D; }
  1131. const ValueDecl *getDecl() const { return D; }
  1132. void setDecl(ValueDecl *NewD);
  1133. DeclarationNameInfo getNameInfo() const {
  1134. return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
  1135. }
  1136. SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
  1137. void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
  1138. SourceLocation getBeginLoc() const LLVM_READONLY;
  1139. SourceLocation getEndLoc() const LLVM_READONLY;
  1140. /// Determine whether this declaration reference was preceded by a
  1141. /// C++ nested-name-specifier, e.g., \c N::foo.
  1142. bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
  1143. /// If the name was qualified, retrieves the nested-name-specifier
  1144. /// that precedes the name, with source-location information.
  1145. NestedNameSpecifierLoc getQualifierLoc() const {
  1146. if (!hasQualifier())
  1147. return NestedNameSpecifierLoc();
  1148. return *getTrailingObjects<NestedNameSpecifierLoc>();
  1149. }
  1150. /// If the name was qualified, retrieves the nested-name-specifier
  1151. /// that precedes the name. Otherwise, returns NULL.
  1152. NestedNameSpecifier *getQualifier() const {
  1153. return getQualifierLoc().getNestedNameSpecifier();
  1154. }
  1155. /// Get the NamedDecl through which this reference occurred.
  1156. ///
  1157. /// This Decl may be different from the ValueDecl actually referred to in the
  1158. /// presence of using declarations, etc. It always returns non-NULL, and may
  1159. /// simple return the ValueDecl when appropriate.
  1160. NamedDecl *getFoundDecl() {
  1161. return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
  1162. }
  1163. /// Get the NamedDecl through which this reference occurred.
  1164. /// See non-const variant.
  1165. const NamedDecl *getFoundDecl() const {
  1166. return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
  1167. }
  1168. bool hasTemplateKWAndArgsInfo() const {
  1169. return DeclRefExprBits.HasTemplateKWAndArgsInfo;
  1170. }
  1171. /// Retrieve the location of the template keyword preceding
  1172. /// this name, if any.
  1173. SourceLocation getTemplateKeywordLoc() const {
  1174. if (!hasTemplateKWAndArgsInfo())
  1175. return SourceLocation();
  1176. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
  1177. }
  1178. /// Retrieve the location of the left angle bracket starting the
  1179. /// explicit template argument list following the name, if any.
  1180. SourceLocation getLAngleLoc() const {
  1181. if (!hasTemplateKWAndArgsInfo())
  1182. return SourceLocation();
  1183. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
  1184. }
  1185. /// Retrieve the location of the right angle bracket ending the
  1186. /// explicit template argument list following the name, if any.
  1187. SourceLocation getRAngleLoc() const {
  1188. if (!hasTemplateKWAndArgsInfo())
  1189. return SourceLocation();
  1190. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
  1191. }
  1192. /// Determines whether the name in this declaration reference
  1193. /// was preceded by the template keyword.
  1194. bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
  1195. /// Determines whether this declaration reference was followed by an
  1196. /// explicit template argument list.
  1197. bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
  1198. /// Copies the template arguments (if present) into the given
  1199. /// structure.
  1200. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
  1201. if (hasExplicitTemplateArgs())
  1202. getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
  1203. getTrailingObjects<TemplateArgumentLoc>(), List);
  1204. }
  1205. /// Retrieve the template arguments provided as part of this
  1206. /// template-id.
  1207. const TemplateArgumentLoc *getTemplateArgs() const {
  1208. if (!hasExplicitTemplateArgs())
  1209. return nullptr;
  1210. return getTrailingObjects<TemplateArgumentLoc>();
  1211. }
  1212. /// Retrieve the number of template arguments provided as part of this
  1213. /// template-id.
  1214. unsigned getNumTemplateArgs() const {
  1215. if (!hasExplicitTemplateArgs())
  1216. return 0;
  1217. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
  1218. }
  1219. ArrayRef<TemplateArgumentLoc> template_arguments() const {
  1220. return {getTemplateArgs(), getNumTemplateArgs()};
  1221. }
  1222. /// Returns true if this expression refers to a function that
  1223. /// was resolved from an overloaded set having size greater than 1.
  1224. bool hadMultipleCandidates() const {
  1225. return DeclRefExprBits.HadMultipleCandidates;
  1226. }
  1227. /// Sets the flag telling whether this expression refers to
  1228. /// a function that was resolved from an overloaded set having size
  1229. /// greater than 1.
  1230. void setHadMultipleCandidates(bool V = true) {
  1231. DeclRefExprBits.HadMultipleCandidates = V;
  1232. }
  1233. /// Is this expression a non-odr-use reference, and if so, why?
  1234. NonOdrUseReason isNonOdrUse() const {
  1235. return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
  1236. }
  1237. /// Does this DeclRefExpr refer to an enclosing local or a captured
  1238. /// variable?
  1239. bool refersToEnclosingVariableOrCapture() const {
  1240. return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
  1241. }
  1242. static bool classof(const Stmt *T) {
  1243. return T->getStmtClass() == DeclRefExprClass;
  1244. }
  1245. // Iterators
  1246. child_range children() {
  1247. return child_range(child_iterator(), child_iterator());
  1248. }
  1249. const_child_range children() const {
  1250. return const_child_range(const_child_iterator(), const_child_iterator());
  1251. }
  1252. };
  1253. /// Used by IntegerLiteral/FloatingLiteral to store the numeric without
  1254. /// leaking memory.
  1255. ///
  1256. /// For large floats/integers, APFloat/APInt will allocate memory from the heap
  1257. /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
  1258. /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
  1259. /// the APFloat/APInt values will never get freed. APNumericStorage uses
  1260. /// ASTContext's allocator for memory allocation.
  1261. class APNumericStorage {
  1262. union {
  1263. uint64_t VAL; ///< Used to store the <= 64 bits integer value.
  1264. uint64_t *pVal; ///< Used to store the >64 bits integer value.
  1265. };
  1266. unsigned BitWidth;
  1267. bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
  1268. APNumericStorage(const APNumericStorage &) = delete;
  1269. void operator=(const APNumericStorage &) = delete;
  1270. protected:
  1271. APNumericStorage() : VAL(0), BitWidth(0) { }
  1272. llvm::APInt getIntValue() const {
  1273. unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
  1274. if (NumWords > 1)
  1275. return llvm::APInt(BitWidth, NumWords, pVal);
  1276. else
  1277. return llvm::APInt(BitWidth, VAL);
  1278. }
  1279. void setIntValue(const ASTContext &C, const llvm::APInt &Val);
  1280. };
  1281. class APIntStorage : private APNumericStorage {
  1282. public:
  1283. llvm::APInt getValue() const { return getIntValue(); }
  1284. void setValue(const ASTContext &C, const llvm::APInt &Val) {
  1285. setIntValue(C, Val);
  1286. }
  1287. };
  1288. class APFloatStorage : private APNumericStorage {
  1289. public:
  1290. llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
  1291. return llvm::APFloat(Semantics, getIntValue());
  1292. }
  1293. void setValue(const ASTContext &C, const llvm::APFloat &Val) {
  1294. setIntValue(C, Val.bitcastToAPInt());
  1295. }
  1296. };
  1297. class IntegerLiteral : public Expr, public APIntStorage {
  1298. SourceLocation Loc;
  1299. /// Construct an empty integer literal.
  1300. explicit IntegerLiteral(EmptyShell Empty)
  1301. : Expr(IntegerLiteralClass, Empty) { }
  1302. public:
  1303. // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
  1304. // or UnsignedLongLongTy
  1305. IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
  1306. SourceLocation l);
  1307. /// Returns a new integer literal with value 'V' and type 'type'.
  1308. /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
  1309. /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
  1310. /// \param V - the value that the returned integer literal contains.
  1311. static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
  1312. QualType type, SourceLocation l);
  1313. /// Returns a new empty integer literal.
  1314. static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
  1315. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1316. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1317. /// Retrieve the location of the literal.
  1318. SourceLocation getLocation() const { return Loc; }
  1319. void setLocation(SourceLocation Location) { Loc = Location; }
  1320. static bool classof(const Stmt *T) {
  1321. return T->getStmtClass() == IntegerLiteralClass;
  1322. }
  1323. // Iterators
  1324. child_range children() {
  1325. return child_range(child_iterator(), child_iterator());
  1326. }
  1327. const_child_range children() const {
  1328. return const_child_range(const_child_iterator(), const_child_iterator());
  1329. }
  1330. };
  1331. class FixedPointLiteral : public Expr, public APIntStorage {
  1332. SourceLocation Loc;
  1333. unsigned Scale;
  1334. /// \brief Construct an empty fixed-point literal.
  1335. explicit FixedPointLiteral(EmptyShell Empty)
  1336. : Expr(FixedPointLiteralClass, Empty) {}
  1337. public:
  1338. FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
  1339. SourceLocation l, unsigned Scale);
  1340. // Store the int as is without any bit shifting.
  1341. static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
  1342. const llvm::APInt &V,
  1343. QualType type, SourceLocation l,
  1344. unsigned Scale);
  1345. /// Returns an empty fixed-point literal.
  1346. static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
  1347. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1348. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1349. /// \brief Retrieve the location of the literal.
  1350. SourceLocation getLocation() const { return Loc; }
  1351. void setLocation(SourceLocation Location) { Loc = Location; }
  1352. unsigned getScale() const { return Scale; }
  1353. void setScale(unsigned S) { Scale = S; }
  1354. static bool classof(const Stmt *T) {
  1355. return T->getStmtClass() == FixedPointLiteralClass;
  1356. }
  1357. std::string getValueAsString(unsigned Radix) const;
  1358. // Iterators
  1359. child_range children() {
  1360. return child_range(child_iterator(), child_iterator());
  1361. }
  1362. const_child_range children() const {
  1363. return const_child_range(const_child_iterator(), const_child_iterator());
  1364. }
  1365. };
  1366. class CharacterLiteral : public Expr {
  1367. public:
  1368. enum CharacterKind {
  1369. Ascii,
  1370. Wide,
  1371. UTF8,
  1372. UTF16,
  1373. UTF32
  1374. };
  1375. private:
  1376. unsigned Value;
  1377. SourceLocation Loc;
  1378. public:
  1379. // type should be IntTy
  1380. CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
  1381. SourceLocation l)
  1382. : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
  1383. Value(value), Loc(l) {
  1384. CharacterLiteralBits.Kind = kind;
  1385. setDependence(ExprDependence::None);
  1386. }
  1387. /// Construct an empty character literal.
  1388. CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
  1389. SourceLocation getLocation() const { return Loc; }
  1390. CharacterKind getKind() const {
  1391. return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
  1392. }
  1393. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1394. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1395. unsigned getValue() const { return Value; }
  1396. void setLocation(SourceLocation Location) { Loc = Location; }
  1397. void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
  1398. void setValue(unsigned Val) { Value = Val; }
  1399. static bool classof(const Stmt *T) {
  1400. return T->getStmtClass() == CharacterLiteralClass;
  1401. }
  1402. static void print(unsigned val, CharacterKind Kind, raw_ostream &OS);
  1403. // Iterators
  1404. child_range children() {
  1405. return child_range(child_iterator(), child_iterator());
  1406. }
  1407. const_child_range children() const {
  1408. return const_child_range(const_child_iterator(), const_child_iterator());
  1409. }
  1410. };
  1411. class FloatingLiteral : public Expr, private APFloatStorage {
  1412. SourceLocation Loc;
  1413. FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
  1414. QualType Type, SourceLocation L);
  1415. /// Construct an empty floating-point literal.
  1416. explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
  1417. public:
  1418. static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
  1419. bool isexact, QualType Type, SourceLocation L);
  1420. static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
  1421. llvm::APFloat getValue() const {
  1422. return APFloatStorage::getValue(getSemantics());
  1423. }
  1424. void setValue(const ASTContext &C, const llvm::APFloat &Val) {
  1425. assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
  1426. APFloatStorage::setValue(C, Val);
  1427. }
  1428. /// Get a raw enumeration value representing the floating-point semantics of
  1429. /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
  1430. llvm::APFloatBase::Semantics getRawSemantics() const {
  1431. return static_cast<llvm::APFloatBase::Semantics>(
  1432. FloatingLiteralBits.Semantics);
  1433. }
  1434. /// Set the raw enumeration value representing the floating-point semantics of
  1435. /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
  1436. void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
  1437. FloatingLiteralBits.Semantics = Sem;
  1438. }
  1439. /// Return the APFloat semantics this literal uses.
  1440. const llvm::fltSemantics &getSemantics() const {
  1441. return llvm::APFloatBase::EnumToSemantics(
  1442. static_cast<llvm::APFloatBase::Semantics>(
  1443. FloatingLiteralBits.Semantics));
  1444. }
  1445. /// Set the APFloat semantics this literal uses.
  1446. void setSemantics(const llvm::fltSemantics &Sem) {
  1447. FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
  1448. }
  1449. bool isExact() const { return FloatingLiteralBits.IsExact; }
  1450. void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
  1451. /// getValueAsApproximateDouble - This returns the value as an inaccurate
  1452. /// double. Note that this may cause loss of precision, but is useful for
  1453. /// debugging dumps, etc.
  1454. double getValueAsApproximateDouble() const;
  1455. SourceLocation getLocation() const { return Loc; }
  1456. void setLocation(SourceLocation L) { Loc = L; }
  1457. SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
  1458. SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
  1459. static bool classof(const Stmt *T) {
  1460. return T->getStmtClass() == FloatingLiteralClass;
  1461. }
  1462. // Iterators
  1463. child_range children() {
  1464. return child_range(child_iterator(), child_iterator());
  1465. }
  1466. const_child_range children() const {
  1467. return const_child_range(const_child_iterator(), const_child_iterator());
  1468. }
  1469. };
  1470. /// ImaginaryLiteral - We support imaginary integer and floating point literals,
  1471. /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
  1472. /// IntegerLiteral classes. Instances of this class always have a Complex type
  1473. /// whose element type matches the subexpression.
  1474. ///
  1475. class ImaginaryLiteral : public Expr {
  1476. Stmt *Val;
  1477. public:
  1478. ImaginaryLiteral(Expr *val, QualType Ty)
  1479. : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
  1480. setDependence(ExprDependence::None);
  1481. }
  1482. /// Build an empty imaginary literal.
  1483. explicit ImaginaryLiteral(EmptyShell Empty)
  1484. : Expr(ImaginaryLiteralClass, Empty) { }
  1485. const Expr *getSubExpr() const { return cast<Expr>(Val); }
  1486. Expr *getSubExpr() { return cast<Expr>(Val); }
  1487. void setSubExpr(Expr *E) { Val = E; }
  1488. SourceLocation getBeginLoc() const LLVM_READONLY {
  1489. return Val->getBeginLoc();
  1490. }
  1491. SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
  1492. static bool classof(const Stmt *T) {
  1493. return T->getStmtClass() == ImaginaryLiteralClass;
  1494. }
  1495. // Iterators
  1496. child_range children() { return child_range(&Val, &Val+1); }
  1497. const_child_range children() const {
  1498. return const_child_range(&Val, &Val + 1);
  1499. }
  1500. };
  1501. /// StringLiteral - This represents a string literal expression, e.g. "foo"
  1502. /// or L"bar" (wide strings). The actual string data can be obtained with
  1503. /// getBytes() and is NOT null-terminated. The length of the string data is
  1504. /// determined by calling getByteLength().
  1505. ///
  1506. /// The C type for a string is always a ConstantArrayType. In C++, the char
  1507. /// type is const qualified, in C it is not.
  1508. ///
  1509. /// Note that strings in C can be formed by concatenation of multiple string
  1510. /// literal pptokens in translation phase #6. This keeps track of the locations
  1511. /// of each of these pieces.
  1512. ///
  1513. /// Strings in C can also be truncated and extended by assigning into arrays,
  1514. /// e.g. with constructs like:
  1515. /// char X[2] = "foobar";
  1516. /// In this case, getByteLength() will return 6, but the string literal will
  1517. /// have type "char[2]".
  1518. class StringLiteral final
  1519. : public Expr,
  1520. private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
  1521. char> {
  1522. friend class ASTStmtReader;
  1523. friend TrailingObjects;
  1524. /// StringLiteral is followed by several trailing objects. They are in order:
  1525. ///
  1526. /// * A single unsigned storing the length in characters of this string. The
  1527. /// length in bytes is this length times the width of a single character.
  1528. /// Always present and stored as a trailing objects because storing it in
  1529. /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
  1530. /// due to alignment requirements. If you add some data to StringLiteral,
  1531. /// consider moving it inside StringLiteral.
  1532. ///
  1533. /// * An array of getNumConcatenated() SourceLocation, one for each of the
  1534. /// token this string is made of.
  1535. ///
  1536. /// * An array of getByteLength() char used to store the string data.
  1537. public:
  1538. enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
  1539. private:
  1540. unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
  1541. unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
  1542. return getNumConcatenated();
  1543. }
  1544. unsigned numTrailingObjects(OverloadToken<char>) const {
  1545. return getByteLength();
  1546. }
  1547. char *getStrDataAsChar() { return getTrailingObjects<char>(); }
  1548. const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
  1549. const uint16_t *getStrDataAsUInt16() const {
  1550. return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
  1551. }
  1552. const uint32_t *getStrDataAsUInt32() const {
  1553. return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
  1554. }
  1555. /// Build a string literal.
  1556. StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
  1557. bool Pascal, QualType Ty, const SourceLocation *Loc,
  1558. unsigned NumConcatenated);
  1559. /// Build an empty string literal.
  1560. StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
  1561. unsigned CharByteWidth);
  1562. /// Map a target and string kind to the appropriate character width.
  1563. static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
  1564. /// Set one of the string literal token.
  1565. void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
  1566. assert(TokNum < getNumConcatenated() && "Invalid tok number");
  1567. getTrailingObjects<SourceLocation>()[TokNum] = L;
  1568. }
  1569. public:
  1570. /// This is the "fully general" constructor that allows representation of
  1571. /// strings formed from multiple concatenated tokens.
  1572. static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
  1573. StringKind Kind, bool Pascal, QualType Ty,
  1574. const SourceLocation *Loc,
  1575. unsigned NumConcatenated);
  1576. /// Simple constructor for string literals made from one token.
  1577. static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
  1578. StringKind Kind, bool Pascal, QualType Ty,
  1579. SourceLocation Loc) {
  1580. return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
  1581. }
  1582. /// Construct an empty string literal.
  1583. static StringLiteral *CreateEmpty(const ASTContext &Ctx,
  1584. unsigned NumConcatenated, unsigned Length,
  1585. unsigned CharByteWidth);
  1586. StringRef getString() const {
  1587. assert(getCharByteWidth() == 1 &&
  1588. "This function is used in places that assume strings use char");
  1589. return StringRef(getStrDataAsChar(), getByteLength());
  1590. }
  1591. /// Allow access to clients that need the byte representation, such as
  1592. /// ASTWriterStmt::VisitStringLiteral().
  1593. StringRef getBytes() const {
  1594. // FIXME: StringRef may not be the right type to use as a result for this.
  1595. return StringRef(getStrDataAsChar(), getByteLength());
  1596. }
  1597. void outputString(raw_ostream &OS) const;
  1598. uint32_t getCodeUnit(size_t i) const {
  1599. assert(i < getLength() && "out of bounds access");
  1600. switch (getCharByteWidth()) {
  1601. case 1:
  1602. return static_cast<unsigned char>(getStrDataAsChar()[i]);
  1603. case 2:
  1604. return getStrDataAsUInt16()[i];
  1605. case 4:
  1606. return getStrDataAsUInt32()[i];
  1607. }
  1608. llvm_unreachable("Unsupported character width!");
  1609. }
  1610. unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
  1611. unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
  1612. unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
  1613. StringKind getKind() const {
  1614. return static_cast<StringKind>(StringLiteralBits.Kind);
  1615. }
  1616. bool isAscii() const { return getKind() == Ascii; }
  1617. bool isWide() const { return getKind() == Wide; }
  1618. bool isUTF8() const { return getKind() == UTF8; }
  1619. bool isUTF16() const { return getKind() == UTF16; }
  1620. bool isUTF32() const { return getKind() == UTF32; }
  1621. bool isPascal() const { return StringLiteralBits.IsPascal; }
  1622. bool containsNonAscii() const {
  1623. for (auto c : getString())
  1624. if (!isASCII(c))
  1625. return true;
  1626. return false;
  1627. }
  1628. bool containsNonAsciiOrNull() const {
  1629. for (auto c : getString())
  1630. if (!isASCII(c) || !c)
  1631. return true;
  1632. return false;
  1633. }
  1634. /// getNumConcatenated - Get the number of string literal tokens that were
  1635. /// concatenated in translation phase #6 to form this string literal.
  1636. unsigned getNumConcatenated() const {
  1637. return StringLiteralBits.NumConcatenated;
  1638. }
  1639. /// Get one of the string literal token.
  1640. SourceLocation getStrTokenLoc(unsigned TokNum) const {
  1641. assert(TokNum < getNumConcatenated() && "Invalid tok number");
  1642. return getTrailingObjects<SourceLocation>()[TokNum];
  1643. }
  1644. /// getLocationOfByte - Return a source location that points to the specified
  1645. /// byte of this string literal.
  1646. ///
  1647. /// Strings are amazingly complex. They can be formed from multiple tokens
  1648. /// and can have escape sequences in them in addition to the usual trigraph
  1649. /// and escaped newline business. This routine handles this complexity.
  1650. ///
  1651. SourceLocation
  1652. getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
  1653. const LangOptions &Features, const TargetInfo &Target,
  1654. unsigned *StartToken = nullptr,
  1655. unsigned *StartTokenByteOffset = nullptr) const;
  1656. typedef const SourceLocation *tokloc_iterator;
  1657. tokloc_iterator tokloc_begin() const {
  1658. return getTrailingObjects<SourceLocation>();
  1659. }
  1660. tokloc_iterator tokloc_end() const {
  1661. return getTrailingObjects<SourceLocation>() + getNumConcatenated();
  1662. }
  1663. SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
  1664. SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
  1665. static bool classof(const Stmt *T) {
  1666. return T->getStmtClass() == StringLiteralClass;
  1667. }
  1668. // Iterators
  1669. child_range children() {
  1670. return child_range(child_iterator(), child_iterator());
  1671. }
  1672. const_child_range children() const {
  1673. return const_child_range(const_child_iterator(), const_child_iterator());
  1674. }
  1675. };
  1676. /// [C99 6.4.2.2] - A predefined identifier such as __func__.
  1677. class PredefinedExpr final
  1678. : public Expr,
  1679. private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
  1680. friend class ASTStmtReader;
  1681. friend TrailingObjects;
  1682. // PredefinedExpr is optionally followed by a single trailing
  1683. // "Stmt *" for the predefined identifier. It is present if and only if
  1684. // hasFunctionName() is true and is always a "StringLiteral *".
  1685. public:
  1686. enum IdentKind {
  1687. Func,
  1688. Function,
  1689. LFunction, // Same as Function, but as wide string.
  1690. FuncDName,
  1691. FuncSig,
  1692. LFuncSig, // Same as FuncSig, but as as wide string
  1693. PrettyFunction,
  1694. /// The same as PrettyFunction, except that the
  1695. /// 'virtual' keyword is omitted for virtual member functions.
  1696. PrettyFunctionNoVirtual
  1697. };
  1698. private:
  1699. PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
  1700. StringLiteral *SL);
  1701. explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
  1702. /// True if this PredefinedExpr has storage for a function name.
  1703. bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
  1704. void setFunctionName(StringLiteral *SL) {
  1705. assert(hasFunctionName() &&
  1706. "This PredefinedExpr has no storage for a function name!");
  1707. *getTrailingObjects<Stmt *>() = SL;
  1708. }
  1709. public:
  1710. /// Create a PredefinedExpr.
  1711. static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
  1712. QualType FNTy, IdentKind IK, StringLiteral *SL);
  1713. /// Create an empty PredefinedExpr.
  1714. static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
  1715. bool HasFunctionName);
  1716. IdentKind getIdentKind() const {
  1717. return static_cast<IdentKind>(PredefinedExprBits.Kind);
  1718. }
  1719. SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
  1720. void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
  1721. StringLiteral *getFunctionName() {
  1722. return hasFunctionName()
  1723. ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
  1724. : nullptr;
  1725. }
  1726. const StringLiteral *getFunctionName() const {
  1727. return hasFunctionName()
  1728. ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
  1729. : nullptr;
  1730. }
  1731. static StringRef getIdentKindName(IdentKind IK);
  1732. StringRef getIdentKindName() const {
  1733. return getIdentKindName(getIdentKind());
  1734. }
  1735. static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
  1736. SourceLocation getBeginLoc() const { return getLocation(); }
  1737. SourceLocation getEndLoc() const { return getLocation(); }
  1738. static bool classof(const Stmt *T) {
  1739. return T->getStmtClass() == PredefinedExprClass;
  1740. }
  1741. // Iterators
  1742. child_range children() {
  1743. return child_range(getTrailingObjects<Stmt *>(),
  1744. getTrailingObjects<Stmt *>() + hasFunctionName());
  1745. }
  1746. const_child_range children() const {
  1747. return const_child_range(getTrailingObjects<Stmt *>(),
  1748. getTrailingObjects<Stmt *>() + hasFunctionName());
  1749. }
  1750. };
  1751. // This represents a use of the __builtin_sycl_unique_stable_name, which takes a
  1752. // type-id, and at CodeGen time emits a unique string representation of the
  1753. // type in a way that permits us to properly encode information about the SYCL
  1754. // kernels.
  1755. class SYCLUniqueStableNameExpr final : public Expr {
  1756. friend class ASTStmtReader;
  1757. SourceLocation OpLoc, LParen, RParen;
  1758. TypeSourceInfo *TypeInfo;
  1759. SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
  1760. SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
  1761. SourceLocation RParen, QualType ResultTy,
  1762. TypeSourceInfo *TSI);
  1763. void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
  1764. void setLocation(SourceLocation L) { OpLoc = L; }
  1765. void setLParenLocation(SourceLocation L) { LParen = L; }
  1766. void setRParenLocation(SourceLocation L) { RParen = L; }
  1767. public:
  1768. TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
  1769. const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
  1770. static SYCLUniqueStableNameExpr *
  1771. Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
  1772. SourceLocation RParen, TypeSourceInfo *TSI);
  1773. static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
  1774. SourceLocation getBeginLoc() const { return getLocation(); }
  1775. SourceLocation getEndLoc() const { return RParen; }
  1776. SourceLocation getLocation() const { return OpLoc; }
  1777. SourceLocation getLParenLocation() const { return LParen; }
  1778. SourceLocation getRParenLocation() const { return RParen; }
  1779. static bool classof(const Stmt *T) {
  1780. return T->getStmtClass() == SYCLUniqueStableNameExprClass;
  1781. }
  1782. // Iterators
  1783. child_range children() {
  1784. return child_range(child_iterator(), child_iterator());
  1785. }
  1786. const_child_range children() const {
  1787. return const_child_range(const_child_iterator(), const_child_iterator());
  1788. }
  1789. // Convenience function to generate the name of the currently stored type.
  1790. std::string ComputeName(ASTContext &Context) const;
  1791. // Get the generated name of the type. Note that this only works after all
  1792. // kernels have been instantiated.
  1793. static std::string ComputeName(ASTContext &Context, QualType Ty);
  1794. };
  1795. /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
  1796. /// AST node is only formed if full location information is requested.
  1797. class ParenExpr : public Expr {
  1798. SourceLocation L, R;
  1799. Stmt *Val;
  1800. public:
  1801. ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
  1802. : Expr(ParenExprClass, val->getType(), val->getValueKind(),
  1803. val->getObjectKind()),
  1804. L(l), R(r), Val(val) {
  1805. setDependence(computeDependence(this));
  1806. }
  1807. /// Construct an empty parenthesized expression.
  1808. explicit ParenExpr(EmptyShell Empty)
  1809. : Expr(ParenExprClass, Empty) { }
  1810. const Expr *getSubExpr() const { return cast<Expr>(Val); }
  1811. Expr *getSubExpr() { return cast<Expr>(Val); }
  1812. void setSubExpr(Expr *E) { Val = E; }
  1813. SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
  1814. SourceLocation getEndLoc() const LLVM_READONLY { return R; }
  1815. /// Get the location of the left parentheses '('.
  1816. SourceLocation getLParen() const { return L; }
  1817. void setLParen(SourceLocation Loc) { L = Loc; }
  1818. /// Get the location of the right parentheses ')'.
  1819. SourceLocation getRParen() const { return R; }
  1820. void setRParen(SourceLocation Loc) { R = Loc; }
  1821. static bool classof(const Stmt *T) {
  1822. return T->getStmtClass() == ParenExprClass;
  1823. }
  1824. // Iterators
  1825. child_range children() { return child_range(&Val, &Val+1); }
  1826. const_child_range children() const {
  1827. return const_child_range(&Val, &Val + 1);
  1828. }
  1829. };
  1830. /// UnaryOperator - This represents the unary-expression's (except sizeof and
  1831. /// alignof), the postinc/postdec operators from postfix-expression, and various
  1832. /// extensions.
  1833. ///
  1834. /// Notes on various nodes:
  1835. ///
  1836. /// Real/Imag - These return the real/imag part of a complex operand. If
  1837. /// applied to a non-complex value, the former returns its operand and the
  1838. /// later returns zero in the type of the operand.
  1839. ///
  1840. class UnaryOperator final
  1841. : public Expr,
  1842. private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
  1843. Stmt *Val;
  1844. size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
  1845. return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
  1846. }
  1847. FPOptionsOverride &getTrailingFPFeatures() {
  1848. assert(UnaryOperatorBits.HasFPFeatures);
  1849. return *getTrailingObjects<FPOptionsOverride>();
  1850. }
  1851. const FPOptionsOverride &getTrailingFPFeatures() const {
  1852. assert(UnaryOperatorBits.HasFPFeatures);
  1853. return *getTrailingObjects<FPOptionsOverride>();
  1854. }
  1855. public:
  1856. typedef UnaryOperatorKind Opcode;
  1857. protected:
  1858. UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
  1859. ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
  1860. bool CanOverflow, FPOptionsOverride FPFeatures);
  1861. /// Build an empty unary operator.
  1862. explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
  1863. : Expr(UnaryOperatorClass, Empty) {
  1864. UnaryOperatorBits.Opc = UO_AddrOf;
  1865. UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
  1866. }
  1867. public:
  1868. static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
  1869. static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
  1870. QualType type, ExprValueKind VK,
  1871. ExprObjectKind OK, SourceLocation l,
  1872. bool CanOverflow, FPOptionsOverride FPFeatures);
  1873. Opcode getOpcode() const {
  1874. return static_cast<Opcode>(UnaryOperatorBits.Opc);
  1875. }
  1876. void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
  1877. Expr *getSubExpr() const { return cast<Expr>(Val); }
  1878. void setSubExpr(Expr *E) { Val = E; }
  1879. /// getOperatorLoc - Return the location of the operator.
  1880. SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
  1881. void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
  1882. /// Returns true if the unary operator can cause an overflow. For instance,
  1883. /// signed int i = INT_MAX; i++;
  1884. /// signed char c = CHAR_MAX; c++;
  1885. /// Due to integer promotions, c++ is promoted to an int before the postfix
  1886. /// increment, and the result is an int that cannot overflow. However, i++
  1887. /// can overflow.
  1888. bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
  1889. void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
  1890. // Get the FP contractability status of this operator. Only meaningful for
  1891. // operations on floating point types.
  1892. bool isFPContractableWithinStatement(const LangOptions &LO) const {
  1893. return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
  1894. }
  1895. // Get the FENV_ACCESS status of this operator. Only meaningful for
  1896. // operations on floating point types.
  1897. bool isFEnvAccessOn(const LangOptions &LO) const {
  1898. return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
  1899. }
  1900. /// isPostfix - Return true if this is a postfix operation, like x++.
  1901. static bool isPostfix(Opcode Op) {
  1902. return Op == UO_PostInc || Op == UO_PostDec;
  1903. }
  1904. /// isPrefix - Return true if this is a prefix operation, like --x.
  1905. static bool isPrefix(Opcode Op) {
  1906. return Op == UO_PreInc || Op == UO_PreDec;
  1907. }
  1908. bool isPrefix() const { return isPrefix(getOpcode()); }
  1909. bool isPostfix() const { return isPostfix(getOpcode()); }
  1910. static bool isIncrementOp(Opcode Op) {
  1911. return Op == UO_PreInc || Op == UO_PostInc;
  1912. }
  1913. bool isIncrementOp() const {
  1914. return isIncrementOp(getOpcode());
  1915. }
  1916. static bool isDecrementOp(Opcode Op) {
  1917. return Op == UO_PreDec || Op == UO_PostDec;
  1918. }
  1919. bool isDecrementOp() const {
  1920. return isDecrementOp(getOpcode());
  1921. }
  1922. static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
  1923. bool isIncrementDecrementOp() const {
  1924. return isIncrementDecrementOp(getOpcode());
  1925. }
  1926. static bool isArithmeticOp(Opcode Op) {
  1927. return Op >= UO_Plus && Op <= UO_LNot;
  1928. }
  1929. bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
  1930. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  1931. /// corresponds to, e.g. "sizeof" or "[pre]++"
  1932. static StringRef getOpcodeStr(Opcode Op);
  1933. /// Retrieve the unary opcode that corresponds to the given
  1934. /// overloaded operator.
  1935. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
  1936. /// Retrieve the overloaded operator kind that corresponds to
  1937. /// the given unary opcode.
  1938. static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
  1939. SourceLocation getBeginLoc() const LLVM_READONLY {
  1940. return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
  1941. }
  1942. SourceLocation getEndLoc() const LLVM_READONLY {
  1943. return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
  1944. }
  1945. SourceLocation getExprLoc() const { return getOperatorLoc(); }
  1946. static bool classof(const Stmt *T) {
  1947. return T->getStmtClass() == UnaryOperatorClass;
  1948. }
  1949. // Iterators
  1950. child_range children() { return child_range(&Val, &Val+1); }
  1951. const_child_range children() const {
  1952. return const_child_range(&Val, &Val + 1);
  1953. }
  1954. /// Is FPFeatures in Trailing Storage?
  1955. bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
  1956. /// Get FPFeatures from trailing storage.
  1957. FPOptionsOverride getStoredFPFeatures() const {
  1958. return getTrailingFPFeatures();
  1959. }
  1960. protected:
  1961. /// Set FPFeatures in trailing storage, used only by Serialization
  1962. void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
  1963. public:
  1964. // Get the FP features status of this operator. Only meaningful for
  1965. // operations on floating point types.
  1966. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  1967. if (UnaryOperatorBits.HasFPFeatures)
  1968. return getStoredFPFeatures().applyOverrides(LO);
  1969. return FPOptions::defaultWithoutTrailingStorage(LO);
  1970. }
  1971. FPOptionsOverride getFPOptionsOverride() const {
  1972. if (UnaryOperatorBits.HasFPFeatures)
  1973. return getStoredFPFeatures();
  1974. return FPOptionsOverride();
  1975. }
  1976. friend TrailingObjects;
  1977. friend class ASTReader;
  1978. friend class ASTStmtReader;
  1979. friend class ASTStmtWriter;
  1980. };
  1981. /// Helper class for OffsetOfExpr.
  1982. // __builtin_offsetof(type, identifier(.identifier|[expr])*)
  1983. class OffsetOfNode {
  1984. public:
  1985. /// The kind of offsetof node we have.
  1986. enum Kind {
  1987. /// An index into an array.
  1988. Array = 0x00,
  1989. /// A field.
  1990. Field = 0x01,
  1991. /// A field in a dependent type, known only by its name.
  1992. Identifier = 0x02,
  1993. /// An implicit indirection through a C++ base class, when the
  1994. /// field found is in a base class.
  1995. Base = 0x03
  1996. };
  1997. private:
  1998. enum { MaskBits = 2, Mask = 0x03 };
  1999. /// The source range that covers this part of the designator.
  2000. SourceRange Range;
  2001. /// The data describing the designator, which comes in three
  2002. /// different forms, depending on the lower two bits.
  2003. /// - An unsigned index into the array of Expr*'s stored after this node
  2004. /// in memory, for [constant-expression] designators.
  2005. /// - A FieldDecl*, for references to a known field.
  2006. /// - An IdentifierInfo*, for references to a field with a given name
  2007. /// when the class type is dependent.
  2008. /// - A CXXBaseSpecifier*, for references that look at a field in a
  2009. /// base class.
  2010. uintptr_t Data;
  2011. public:
  2012. /// Create an offsetof node that refers to an array element.
  2013. OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
  2014. SourceLocation RBracketLoc)
  2015. : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
  2016. /// Create an offsetof node that refers to a field.
  2017. OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
  2018. : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
  2019. Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
  2020. /// Create an offsetof node that refers to an identifier.
  2021. OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
  2022. SourceLocation NameLoc)
  2023. : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
  2024. Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
  2025. /// Create an offsetof node that refers into a C++ base class.
  2026. explicit OffsetOfNode(const CXXBaseSpecifier *Base)
  2027. : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
  2028. /// Determine what kind of offsetof node this is.
  2029. Kind getKind() const { return static_cast<Kind>(Data & Mask); }
  2030. /// For an array element node, returns the index into the array
  2031. /// of expressions.
  2032. unsigned getArrayExprIndex() const {
  2033. assert(getKind() == Array);
  2034. return Data >> 2;
  2035. }
  2036. /// For a field offsetof node, returns the field.
  2037. FieldDecl *getField() const {
  2038. assert(getKind() == Field);
  2039. return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
  2040. }
  2041. /// For a field or identifier offsetof node, returns the name of
  2042. /// the field.
  2043. IdentifierInfo *getFieldName() const;
  2044. /// For a base class node, returns the base specifier.
  2045. CXXBaseSpecifier *getBase() const {
  2046. assert(getKind() == Base);
  2047. return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
  2048. }
  2049. /// Retrieve the source range that covers this offsetof node.
  2050. ///
  2051. /// For an array element node, the source range contains the locations of
  2052. /// the square brackets. For a field or identifier node, the source range
  2053. /// contains the location of the period (if there is one) and the
  2054. /// identifier.
  2055. SourceRange getSourceRange() const LLVM_READONLY { return Range; }
  2056. SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
  2057. SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
  2058. };
  2059. /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
  2060. /// offsetof(record-type, member-designator). For example, given:
  2061. /// @code
  2062. /// struct S {
  2063. /// float f;
  2064. /// double d;
  2065. /// };
  2066. /// struct T {
  2067. /// int i;
  2068. /// struct S s[10];
  2069. /// };
  2070. /// @endcode
  2071. /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
  2072. class OffsetOfExpr final
  2073. : public Expr,
  2074. private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
  2075. SourceLocation OperatorLoc, RParenLoc;
  2076. // Base type;
  2077. TypeSourceInfo *TSInfo;
  2078. // Number of sub-components (i.e. instances of OffsetOfNode).
  2079. unsigned NumComps;
  2080. // Number of sub-expressions (i.e. array subscript expressions).
  2081. unsigned NumExprs;
  2082. size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
  2083. return NumComps;
  2084. }
  2085. OffsetOfExpr(const ASTContext &C, QualType type,
  2086. SourceLocation OperatorLoc, TypeSourceInfo *tsi,
  2087. ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
  2088. SourceLocation RParenLoc);
  2089. explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
  2090. : Expr(OffsetOfExprClass, EmptyShell()),
  2091. TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
  2092. public:
  2093. static OffsetOfExpr *Create(const ASTContext &C, QualType type,
  2094. SourceLocation OperatorLoc, TypeSourceInfo *tsi,
  2095. ArrayRef<OffsetOfNode> comps,
  2096. ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
  2097. static OffsetOfExpr *CreateEmpty(const ASTContext &C,
  2098. unsigned NumComps, unsigned NumExprs);
  2099. /// getOperatorLoc - Return the location of the operator.
  2100. SourceLocation getOperatorLoc() const { return OperatorLoc; }
  2101. void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
  2102. /// Return the location of the right parentheses.
  2103. SourceLocation getRParenLoc() const { return RParenLoc; }
  2104. void setRParenLoc(SourceLocation R) { RParenLoc = R; }
  2105. TypeSourceInfo *getTypeSourceInfo() const {
  2106. return TSInfo;
  2107. }
  2108. void setTypeSourceInfo(TypeSourceInfo *tsi) {
  2109. TSInfo = tsi;
  2110. }
  2111. const OffsetOfNode &getComponent(unsigned Idx) const {
  2112. assert(Idx < NumComps && "Subscript out of range");
  2113. return getTrailingObjects<OffsetOfNode>()[Idx];
  2114. }
  2115. void setComponent(unsigned Idx, OffsetOfNode ON) {
  2116. assert(Idx < NumComps && "Subscript out of range");
  2117. getTrailingObjects<OffsetOfNode>()[Idx] = ON;
  2118. }
  2119. unsigned getNumComponents() const {
  2120. return NumComps;
  2121. }
  2122. Expr* getIndexExpr(unsigned Idx) {
  2123. assert(Idx < NumExprs && "Subscript out of range");
  2124. return getTrailingObjects<Expr *>()[Idx];
  2125. }
  2126. const Expr *getIndexExpr(unsigned Idx) const {
  2127. assert(Idx < NumExprs && "Subscript out of range");
  2128. return getTrailingObjects<Expr *>()[Idx];
  2129. }
  2130. void setIndexExpr(unsigned Idx, Expr* E) {
  2131. assert(Idx < NumComps && "Subscript out of range");
  2132. getTrailingObjects<Expr *>()[Idx] = E;
  2133. }
  2134. unsigned getNumExpressions() const {
  2135. return NumExprs;
  2136. }
  2137. SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
  2138. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  2139. static bool classof(const Stmt *T) {
  2140. return T->getStmtClass() == OffsetOfExprClass;
  2141. }
  2142. // Iterators
  2143. child_range children() {
  2144. Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
  2145. return child_range(begin, begin + NumExprs);
  2146. }
  2147. const_child_range children() const {
  2148. Stmt *const *begin =
  2149. reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
  2150. return const_child_range(begin, begin + NumExprs);
  2151. }
  2152. friend TrailingObjects;
  2153. };
  2154. /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
  2155. /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
  2156. /// vec_step (OpenCL 1.1 6.11.12).
  2157. class UnaryExprOrTypeTraitExpr : public Expr {
  2158. union {
  2159. TypeSourceInfo *Ty;
  2160. Stmt *Ex;
  2161. } Argument;
  2162. SourceLocation OpLoc, RParenLoc;
  2163. public:
  2164. UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
  2165. QualType resultType, SourceLocation op,
  2166. SourceLocation rp)
  2167. : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
  2168. OK_Ordinary),
  2169. OpLoc(op), RParenLoc(rp) {
  2170. assert(ExprKind <= UETT_Last && "invalid enum value!");
  2171. UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
  2172. assert(static_cast<unsigned>(ExprKind) ==
  2173. UnaryExprOrTypeTraitExprBits.Kind &&
  2174. "UnaryExprOrTypeTraitExprBits.Kind overflow!");
  2175. UnaryExprOrTypeTraitExprBits.IsType = true;
  2176. Argument.Ty = TInfo;
  2177. setDependence(computeDependence(this));
  2178. }
  2179. UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
  2180. QualType resultType, SourceLocation op,
  2181. SourceLocation rp);
  2182. /// Construct an empty sizeof/alignof expression.
  2183. explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
  2184. : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
  2185. UnaryExprOrTypeTrait getKind() const {
  2186. return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
  2187. }
  2188. void setKind(UnaryExprOrTypeTrait K) {
  2189. assert(K <= UETT_Last && "invalid enum value!");
  2190. UnaryExprOrTypeTraitExprBits.Kind = K;
  2191. assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
  2192. "UnaryExprOrTypeTraitExprBits.Kind overflow!");
  2193. }
  2194. bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
  2195. QualType getArgumentType() const {
  2196. return getArgumentTypeInfo()->getType();
  2197. }
  2198. TypeSourceInfo *getArgumentTypeInfo() const {
  2199. assert(isArgumentType() && "calling getArgumentType() when arg is expr");
  2200. return Argument.Ty;
  2201. }
  2202. Expr *getArgumentExpr() {
  2203. assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
  2204. return static_cast<Expr*>(Argument.Ex);
  2205. }
  2206. const Expr *getArgumentExpr() const {
  2207. return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
  2208. }
  2209. void setArgument(Expr *E) {
  2210. Argument.Ex = E;
  2211. UnaryExprOrTypeTraitExprBits.IsType = false;
  2212. }
  2213. void setArgument(TypeSourceInfo *TInfo) {
  2214. Argument.Ty = TInfo;
  2215. UnaryExprOrTypeTraitExprBits.IsType = true;
  2216. }
  2217. /// Gets the argument type, or the type of the argument expression, whichever
  2218. /// is appropriate.
  2219. QualType getTypeOfArgument() const {
  2220. return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
  2221. }
  2222. SourceLocation getOperatorLoc() const { return OpLoc; }
  2223. void setOperatorLoc(SourceLocation L) { OpLoc = L; }
  2224. SourceLocation getRParenLoc() const { return RParenLoc; }
  2225. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  2226. SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
  2227. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  2228. static bool classof(const Stmt *T) {
  2229. return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
  2230. }
  2231. // Iterators
  2232. child_range children();
  2233. const_child_range children() const;
  2234. };
  2235. //===----------------------------------------------------------------------===//
  2236. // Postfix Operators.
  2237. //===----------------------------------------------------------------------===//
  2238. /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
  2239. class ArraySubscriptExpr : public Expr {
  2240. enum { LHS, RHS, END_EXPR };
  2241. Stmt *SubExprs[END_EXPR];
  2242. bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
  2243. public:
  2244. ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
  2245. ExprObjectKind OK, SourceLocation rbracketloc)
  2246. : Expr(ArraySubscriptExprClass, t, VK, OK) {
  2247. SubExprs[LHS] = lhs;
  2248. SubExprs[RHS] = rhs;
  2249. ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
  2250. setDependence(computeDependence(this));
  2251. }
  2252. /// Create an empty array subscript expression.
  2253. explicit ArraySubscriptExpr(EmptyShell Shell)
  2254. : Expr(ArraySubscriptExprClass, Shell) { }
  2255. /// An array access can be written A[4] or 4[A] (both are equivalent).
  2256. /// - getBase() and getIdx() always present the normalized view: A[4].
  2257. /// In this case getBase() returns "A" and getIdx() returns "4".
  2258. /// - getLHS() and getRHS() present the syntactic view. e.g. for
  2259. /// 4[A] getLHS() returns "4".
  2260. /// Note: Because vector element access is also written A[4] we must
  2261. /// predicate the format conversion in getBase and getIdx only on the
  2262. /// the type of the RHS, as it is possible for the LHS to be a vector of
  2263. /// integer type
  2264. Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
  2265. const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  2266. void setLHS(Expr *E) { SubExprs[LHS] = E; }
  2267. Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
  2268. const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  2269. void setRHS(Expr *E) { SubExprs[RHS] = E; }
  2270. Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
  2271. const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
  2272. Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
  2273. const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
  2274. SourceLocation getBeginLoc() const LLVM_READONLY {
  2275. return getLHS()->getBeginLoc();
  2276. }
  2277. SourceLocation getEndLoc() const { return getRBracketLoc(); }
  2278. SourceLocation getRBracketLoc() const {
  2279. return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
  2280. }
  2281. void setRBracketLoc(SourceLocation L) {
  2282. ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
  2283. }
  2284. SourceLocation getExprLoc() const LLVM_READONLY {
  2285. return getBase()->getExprLoc();
  2286. }
  2287. static bool classof(const Stmt *T) {
  2288. return T->getStmtClass() == ArraySubscriptExprClass;
  2289. }
  2290. // Iterators
  2291. child_range children() {
  2292. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  2293. }
  2294. const_child_range children() const {
  2295. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  2296. }
  2297. };
  2298. /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
  2299. /// extension.
  2300. /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
  2301. /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
  2302. /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
  2303. /// exist during the initial construction of the AST.
  2304. class MatrixSubscriptExpr : public Expr {
  2305. enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
  2306. Stmt *SubExprs[END_EXPR];
  2307. public:
  2308. MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
  2309. SourceLocation RBracketLoc)
  2310. : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
  2311. OK_MatrixComponent) {
  2312. SubExprs[BASE] = Base;
  2313. SubExprs[ROW_IDX] = RowIdx;
  2314. SubExprs[COLUMN_IDX] = ColumnIdx;
  2315. ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
  2316. setDependence(computeDependence(this));
  2317. }
  2318. /// Create an empty matrix subscript expression.
  2319. explicit MatrixSubscriptExpr(EmptyShell Shell)
  2320. : Expr(MatrixSubscriptExprClass, Shell) {}
  2321. bool isIncomplete() const {
  2322. bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
  2323. assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
  2324. "expressions without column index must be marked as incomplete");
  2325. return IsIncomplete;
  2326. }
  2327. Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
  2328. const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
  2329. void setBase(Expr *E) { SubExprs[BASE] = E; }
  2330. Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
  2331. const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
  2332. void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
  2333. Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
  2334. const Expr *getColumnIdx() const {
  2335. assert(!isIncomplete() &&
  2336. "cannot get the column index of an incomplete expression");
  2337. return cast<Expr>(SubExprs[COLUMN_IDX]);
  2338. }
  2339. void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
  2340. SourceLocation getBeginLoc() const LLVM_READONLY {
  2341. return getBase()->getBeginLoc();
  2342. }
  2343. SourceLocation getEndLoc() const { return getRBracketLoc(); }
  2344. SourceLocation getExprLoc() const LLVM_READONLY {
  2345. return getBase()->getExprLoc();
  2346. }
  2347. SourceLocation getRBracketLoc() const {
  2348. return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
  2349. }
  2350. void setRBracketLoc(SourceLocation L) {
  2351. ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
  2352. }
  2353. static bool classof(const Stmt *T) {
  2354. return T->getStmtClass() == MatrixSubscriptExprClass;
  2355. }
  2356. // Iterators
  2357. child_range children() {
  2358. return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  2359. }
  2360. const_child_range children() const {
  2361. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  2362. }
  2363. };
  2364. /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
  2365. /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
  2366. /// while its subclasses may represent alternative syntax that (semantically)
  2367. /// results in a function call. For example, CXXOperatorCallExpr is
  2368. /// a subclass for overloaded operator calls that use operator syntax, e.g.,
  2369. /// "str1 + str2" to resolve to a function call.
  2370. class CallExpr : public Expr {
  2371. enum { FN = 0, PREARGS_START = 1 };
  2372. /// The number of arguments in the call expression.
  2373. unsigned NumArgs;
  2374. /// The location of the right parenthese. This has a different meaning for
  2375. /// the derived classes of CallExpr.
  2376. SourceLocation RParenLoc;
  2377. // CallExpr store some data in trailing objects. However since CallExpr
  2378. // is used a base of other expression classes we cannot use
  2379. // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
  2380. // and casts.
  2381. //
  2382. // The trailing objects are in order:
  2383. //
  2384. // * A single "Stmt *" for the callee expression.
  2385. //
  2386. // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
  2387. //
  2388. // * An array of getNumArgs() "Stmt *" for the argument expressions.
  2389. //
  2390. // * An optional of type FPOptionsOverride.
  2391. //
  2392. // Note that we store the offset in bytes from the this pointer to the start
  2393. // of the trailing objects. It would be perfectly possible to compute it
  2394. // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
  2395. // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
  2396. // compute this once and then load the offset from the bit-fields of Stmt,
  2397. // instead of re-computing the offset each time the trailing objects are
  2398. // accessed.
  2399. /// Return a pointer to the start of the trailing array of "Stmt *".
  2400. Stmt **getTrailingStmts() {
  2401. return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
  2402. CallExprBits.OffsetToTrailingObjects);
  2403. }
  2404. Stmt *const *getTrailingStmts() const {
  2405. return const_cast<CallExpr *>(this)->getTrailingStmts();
  2406. }
  2407. /// Map a statement class to the appropriate offset in bytes from the
  2408. /// this pointer to the trailing objects.
  2409. static unsigned offsetToTrailingObjects(StmtClass SC);
  2410. unsigned getSizeOfTrailingStmts() const {
  2411. return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
  2412. }
  2413. size_t getOffsetOfTrailingFPFeatures() const {
  2414. assert(hasStoredFPFeatures());
  2415. return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
  2416. }
  2417. public:
  2418. enum class ADLCallKind : bool { NotADL, UsesADL };
  2419. static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
  2420. static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
  2421. protected:
  2422. /// Build a call expression, assuming that appropriate storage has been
  2423. /// allocated for the trailing objects.
  2424. CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
  2425. ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
  2426. SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
  2427. unsigned MinNumArgs, ADLCallKind UsesADL);
  2428. /// Build an empty call expression, for deserialization.
  2429. CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
  2430. bool hasFPFeatures, EmptyShell Empty);
  2431. /// Return the size in bytes needed for the trailing objects.
  2432. /// Used by the derived classes to allocate the right amount of storage.
  2433. static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
  2434. bool HasFPFeatures) {
  2435. return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
  2436. HasFPFeatures * sizeof(FPOptionsOverride);
  2437. }
  2438. Stmt *getPreArg(unsigned I) {
  2439. assert(I < getNumPreArgs() && "Prearg access out of range!");
  2440. return getTrailingStmts()[PREARGS_START + I];
  2441. }
  2442. const Stmt *getPreArg(unsigned I) const {
  2443. assert(I < getNumPreArgs() && "Prearg access out of range!");
  2444. return getTrailingStmts()[PREARGS_START + I];
  2445. }
  2446. void setPreArg(unsigned I, Stmt *PreArg) {
  2447. assert(I < getNumPreArgs() && "Prearg access out of range!");
  2448. getTrailingStmts()[PREARGS_START + I] = PreArg;
  2449. }
  2450. unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
  2451. /// Return a pointer to the trailing FPOptions
  2452. FPOptionsOverride *getTrailingFPFeatures() {
  2453. assert(hasStoredFPFeatures());
  2454. return reinterpret_cast<FPOptionsOverride *>(
  2455. reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
  2456. getSizeOfTrailingStmts());
  2457. }
  2458. const FPOptionsOverride *getTrailingFPFeatures() const {
  2459. assert(hasStoredFPFeatures());
  2460. return reinterpret_cast<const FPOptionsOverride *>(
  2461. reinterpret_cast<const char *>(this) +
  2462. CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
  2463. }
  2464. public:
  2465. /// Create a call expression.
  2466. /// \param Fn The callee expression,
  2467. /// \param Args The argument array,
  2468. /// \param Ty The type of the call expression (which is *not* the return
  2469. /// type in general),
  2470. /// \param VK The value kind of the call expression (lvalue, rvalue, ...),
  2471. /// \param RParenLoc The location of the right parenthesis in the call
  2472. /// expression.
  2473. /// \param FPFeatures Floating-point features associated with the call,
  2474. /// \param MinNumArgs Specifies the minimum number of arguments. The actual
  2475. /// number of arguments will be the greater of Args.size()
  2476. /// and MinNumArgs. This is used in a few places to allocate
  2477. /// enough storage for the default arguments.
  2478. /// \param UsesADL Specifies whether the callee was found through
  2479. /// argument-dependent lookup.
  2480. ///
  2481. /// Note that you can use CreateTemporary if you need a temporary call
  2482. /// expression on the stack.
  2483. static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
  2484. ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
  2485. SourceLocation RParenLoc,
  2486. FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
  2487. ADLCallKind UsesADL = NotADL);
  2488. /// Create a temporary call expression with no arguments in the memory
  2489. /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
  2490. /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
  2491. ///
  2492. /// \code{.cpp}
  2493. /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
  2494. /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
  2495. /// \endcode
  2496. static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
  2497. ExprValueKind VK, SourceLocation RParenLoc,
  2498. ADLCallKind UsesADL = NotADL);
  2499. /// Create an empty call expression, for deserialization.
  2500. static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
  2501. bool HasFPFeatures, EmptyShell Empty);
  2502. Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
  2503. const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
  2504. void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
  2505. ADLCallKind getADLCallKind() const {
  2506. return static_cast<ADLCallKind>(CallExprBits.UsesADL);
  2507. }
  2508. void setADLCallKind(ADLCallKind V = UsesADL) {
  2509. CallExprBits.UsesADL = static_cast<bool>(V);
  2510. }
  2511. bool usesADL() const { return getADLCallKind() == UsesADL; }
  2512. bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
  2513. Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
  2514. const Decl *getCalleeDecl() const {
  2515. return getCallee()->getReferencedDeclOfCallee();
  2516. }
  2517. /// If the callee is a FunctionDecl, return it. Otherwise return null.
  2518. FunctionDecl *getDirectCallee() {
  2519. return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
  2520. }
  2521. const FunctionDecl *getDirectCallee() const {
  2522. return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
  2523. }
  2524. /// getNumArgs - Return the number of actual arguments to this call.
  2525. unsigned getNumArgs() const { return NumArgs; }
  2526. /// Retrieve the call arguments.
  2527. Expr **getArgs() {
  2528. return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
  2529. getNumPreArgs());
  2530. }
  2531. const Expr *const *getArgs() const {
  2532. return reinterpret_cast<const Expr *const *>(
  2533. getTrailingStmts() + PREARGS_START + getNumPreArgs());
  2534. }
  2535. /// getArg - Return the specified argument.
  2536. Expr *getArg(unsigned Arg) {
  2537. assert(Arg < getNumArgs() && "Arg access out of range!");
  2538. return getArgs()[Arg];
  2539. }
  2540. const Expr *getArg(unsigned Arg) const {
  2541. assert(Arg < getNumArgs() && "Arg access out of range!");
  2542. return getArgs()[Arg];
  2543. }
  2544. /// setArg - Set the specified argument.
  2545. /// ! the dependence bits might be stale after calling this setter, it is
  2546. /// *caller*'s responsibility to recompute them by calling
  2547. /// computeDependence().
  2548. void setArg(unsigned Arg, Expr *ArgExpr) {
  2549. assert(Arg < getNumArgs() && "Arg access out of range!");
  2550. getArgs()[Arg] = ArgExpr;
  2551. }
  2552. /// Compute and set dependence bits.
  2553. void computeDependence() {
  2554. setDependence(clang::computeDependence(
  2555. this, llvm::makeArrayRef(
  2556. reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
  2557. getNumPreArgs())));
  2558. }
  2559. /// Reduce the number of arguments in this call expression. This is used for
  2560. /// example during error recovery to drop extra arguments. There is no way
  2561. /// to perform the opposite because: 1.) We don't track how much storage
  2562. /// we have for the argument array 2.) This would potentially require growing
  2563. /// the argument array, something we cannot support since the arguments are
  2564. /// stored in a trailing array.
  2565. void shrinkNumArgs(unsigned NewNumArgs) {
  2566. assert((NewNumArgs <= getNumArgs()) &&
  2567. "shrinkNumArgs cannot increase the number of arguments!");
  2568. NumArgs = NewNumArgs;
  2569. }
  2570. /// Bluntly set a new number of arguments without doing any checks whatsoever.
  2571. /// Only used during construction of a CallExpr in a few places in Sema.
  2572. /// FIXME: Find a way to remove it.
  2573. void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
  2574. typedef ExprIterator arg_iterator;
  2575. typedef ConstExprIterator const_arg_iterator;
  2576. typedef llvm::iterator_range<arg_iterator> arg_range;
  2577. typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
  2578. arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
  2579. const_arg_range arguments() const {
  2580. return const_arg_range(arg_begin(), arg_end());
  2581. }
  2582. arg_iterator arg_begin() {
  2583. return getTrailingStmts() + PREARGS_START + getNumPreArgs();
  2584. }
  2585. arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
  2586. const_arg_iterator arg_begin() const {
  2587. return getTrailingStmts() + PREARGS_START + getNumPreArgs();
  2588. }
  2589. const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
  2590. /// This method provides fast access to all the subexpressions of
  2591. /// a CallExpr without going through the slower virtual child_iterator
  2592. /// interface. This provides efficient reverse iteration of the
  2593. /// subexpressions. This is currently used for CFG construction.
  2594. ArrayRef<Stmt *> getRawSubExprs() {
  2595. return llvm::makeArrayRef(getTrailingStmts(),
  2596. PREARGS_START + getNumPreArgs() + getNumArgs());
  2597. }
  2598. /// getNumCommas - Return the number of commas that must have been present in
  2599. /// this function call.
  2600. unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
  2601. /// Get FPOptionsOverride from trailing storage.
  2602. FPOptionsOverride getStoredFPFeatures() const {
  2603. assert(hasStoredFPFeatures());
  2604. return *getTrailingFPFeatures();
  2605. }
  2606. /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
  2607. void setStoredFPFeatures(FPOptionsOverride F) {
  2608. assert(hasStoredFPFeatures());
  2609. *getTrailingFPFeatures() = F;
  2610. }
  2611. // Get the FP features status of this operator. Only meaningful for
  2612. // operations on floating point types.
  2613. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  2614. if (hasStoredFPFeatures())
  2615. return getStoredFPFeatures().applyOverrides(LO);
  2616. return FPOptions::defaultWithoutTrailingStorage(LO);
  2617. }
  2618. FPOptionsOverride getFPFeatures() const {
  2619. if (hasStoredFPFeatures())
  2620. return getStoredFPFeatures();
  2621. return FPOptionsOverride();
  2622. }
  2623. /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
  2624. /// of the callee. If not, return 0.
  2625. unsigned getBuiltinCallee() const;
  2626. /// Returns \c true if this is a call to a builtin which does not
  2627. /// evaluate side-effects within its arguments.
  2628. bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
  2629. /// getCallReturnType - Get the return type of the call expr. This is not
  2630. /// always the type of the expr itself, if the return type is a reference
  2631. /// type.
  2632. QualType getCallReturnType(const ASTContext &Ctx) const;
  2633. /// Returns the WarnUnusedResultAttr that is either declared on the called
  2634. /// function, or its return type declaration.
  2635. const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
  2636. /// Returns true if this call expression should warn on unused results.
  2637. bool hasUnusedResultAttr(const ASTContext &Ctx) const {
  2638. return getUnusedResultAttr(Ctx) != nullptr;
  2639. }
  2640. SourceLocation getRParenLoc() const { return RParenLoc; }
  2641. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  2642. SourceLocation getBeginLoc() const LLVM_READONLY;
  2643. SourceLocation getEndLoc() const LLVM_READONLY;
  2644. /// Return true if this is a call to __assume() or __builtin_assume() with
  2645. /// a non-value-dependent constant parameter evaluating as false.
  2646. bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
  2647. /// Used by Sema to implement MSVC-compatible delayed name lookup.
  2648. /// (Usually Exprs themselves should set dependence).
  2649. void markDependentForPostponedNameLookup() {
  2650. setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
  2651. }
  2652. bool isCallToStdMove() const {
  2653. const FunctionDecl *FD = getDirectCallee();
  2654. return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
  2655. FD->getIdentifier() && FD->getIdentifier()->isStr("move");
  2656. }
  2657. static bool classof(const Stmt *T) {
  2658. return T->getStmtClass() >= firstCallExprConstant &&
  2659. T->getStmtClass() <= lastCallExprConstant;
  2660. }
  2661. // Iterators
  2662. child_range children() {
  2663. return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
  2664. getNumPreArgs() + getNumArgs());
  2665. }
  2666. const_child_range children() const {
  2667. return const_child_range(getTrailingStmts(),
  2668. getTrailingStmts() + PREARGS_START +
  2669. getNumPreArgs() + getNumArgs());
  2670. }
  2671. };
  2672. /// Extra data stored in some MemberExpr objects.
  2673. struct MemberExprNameQualifier {
  2674. /// The nested-name-specifier that qualifies the name, including
  2675. /// source-location information.
  2676. NestedNameSpecifierLoc QualifierLoc;
  2677. /// The DeclAccessPair through which the MemberDecl was found due to
  2678. /// name qualifiers.
  2679. DeclAccessPair FoundDecl;
  2680. };
  2681. /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
  2682. ///
  2683. class MemberExpr final
  2684. : public Expr,
  2685. private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
  2686. ASTTemplateKWAndArgsInfo,
  2687. TemplateArgumentLoc> {
  2688. friend class ASTReader;
  2689. friend class ASTStmtReader;
  2690. friend class ASTStmtWriter;
  2691. friend TrailingObjects;
  2692. /// Base - the expression for the base pointer or structure references. In
  2693. /// X.F, this is "X".
  2694. Stmt *Base;
  2695. /// MemberDecl - This is the decl being referenced by the field/member name.
  2696. /// In X.F, this is the decl referenced by F.
  2697. ValueDecl *MemberDecl;
  2698. /// MemberDNLoc - Provides source/type location info for the
  2699. /// declaration name embedded in MemberDecl.
  2700. DeclarationNameLoc MemberDNLoc;
  2701. /// MemberLoc - This is the location of the member name.
  2702. SourceLocation MemberLoc;
  2703. size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
  2704. return hasQualifierOrFoundDecl();
  2705. }
  2706. size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
  2707. return hasTemplateKWAndArgsInfo();
  2708. }
  2709. bool hasQualifierOrFoundDecl() const {
  2710. return MemberExprBits.HasQualifierOrFoundDecl;
  2711. }
  2712. bool hasTemplateKWAndArgsInfo() const {
  2713. return MemberExprBits.HasTemplateKWAndArgsInfo;
  2714. }
  2715. MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
  2716. ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
  2717. QualType T, ExprValueKind VK, ExprObjectKind OK,
  2718. NonOdrUseReason NOUR);
  2719. MemberExpr(EmptyShell Empty)
  2720. : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
  2721. public:
  2722. static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
  2723. SourceLocation OperatorLoc,
  2724. NestedNameSpecifierLoc QualifierLoc,
  2725. SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
  2726. DeclAccessPair FoundDecl,
  2727. DeclarationNameInfo MemberNameInfo,
  2728. const TemplateArgumentListInfo *TemplateArgs,
  2729. QualType T, ExprValueKind VK, ExprObjectKind OK,
  2730. NonOdrUseReason NOUR);
  2731. /// Create an implicit MemberExpr, with no location, qualifier, template
  2732. /// arguments, and so on. Suitable only for non-static member access.
  2733. static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
  2734. bool IsArrow, ValueDecl *MemberDecl,
  2735. QualType T, ExprValueKind VK,
  2736. ExprObjectKind OK) {
  2737. return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
  2738. SourceLocation(), MemberDecl,
  2739. DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
  2740. DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
  2741. }
  2742. static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
  2743. bool HasFoundDecl,
  2744. bool HasTemplateKWAndArgsInfo,
  2745. unsigned NumTemplateArgs);
  2746. void setBase(Expr *E) { Base = E; }
  2747. Expr *getBase() const { return cast<Expr>(Base); }
  2748. /// Retrieve the member declaration to which this expression refers.
  2749. ///
  2750. /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
  2751. /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
  2752. ValueDecl *getMemberDecl() const { return MemberDecl; }
  2753. void setMemberDecl(ValueDecl *D);
  2754. /// Retrieves the declaration found by lookup.
  2755. DeclAccessPair getFoundDecl() const {
  2756. if (!hasQualifierOrFoundDecl())
  2757. return DeclAccessPair::make(getMemberDecl(),
  2758. getMemberDecl()->getAccess());
  2759. return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
  2760. }
  2761. /// Determines whether this member expression actually had
  2762. /// a C++ nested-name-specifier prior to the name of the member, e.g.,
  2763. /// x->Base::foo.
  2764. bool hasQualifier() const { return getQualifier() != nullptr; }
  2765. /// If the member name was qualified, retrieves the
  2766. /// nested-name-specifier that precedes the member name, with source-location
  2767. /// information.
  2768. NestedNameSpecifierLoc getQualifierLoc() const {
  2769. if (!hasQualifierOrFoundDecl())
  2770. return NestedNameSpecifierLoc();
  2771. return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
  2772. }
  2773. /// If the member name was qualified, retrieves the
  2774. /// nested-name-specifier that precedes the member name. Otherwise, returns
  2775. /// NULL.
  2776. NestedNameSpecifier *getQualifier() const {
  2777. return getQualifierLoc().getNestedNameSpecifier();
  2778. }
  2779. /// Retrieve the location of the template keyword preceding
  2780. /// the member name, if any.
  2781. SourceLocation getTemplateKeywordLoc() const {
  2782. if (!hasTemplateKWAndArgsInfo())
  2783. return SourceLocation();
  2784. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
  2785. }
  2786. /// Retrieve the location of the left angle bracket starting the
  2787. /// explicit template argument list following the member name, if any.
  2788. SourceLocation getLAngleLoc() const {
  2789. if (!hasTemplateKWAndArgsInfo())
  2790. return SourceLocation();
  2791. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
  2792. }
  2793. /// Retrieve the location of the right angle bracket ending the
  2794. /// explicit template argument list following the member name, if any.
  2795. SourceLocation getRAngleLoc() const {
  2796. if (!hasTemplateKWAndArgsInfo())
  2797. return SourceLocation();
  2798. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
  2799. }
  2800. /// Determines whether the member name was preceded by the template keyword.
  2801. bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
  2802. /// Determines whether the member name was followed by an
  2803. /// explicit template argument list.
  2804. bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
  2805. /// Copies the template arguments (if present) into the given
  2806. /// structure.
  2807. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
  2808. if (hasExplicitTemplateArgs())
  2809. getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
  2810. getTrailingObjects<TemplateArgumentLoc>(), List);
  2811. }
  2812. /// Retrieve the template arguments provided as part of this
  2813. /// template-id.
  2814. const TemplateArgumentLoc *getTemplateArgs() const {
  2815. if (!hasExplicitTemplateArgs())
  2816. return nullptr;
  2817. return getTrailingObjects<TemplateArgumentLoc>();
  2818. }
  2819. /// Retrieve the number of template arguments provided as part of this
  2820. /// template-id.
  2821. unsigned getNumTemplateArgs() const {
  2822. if (!hasExplicitTemplateArgs())
  2823. return 0;
  2824. return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
  2825. }
  2826. ArrayRef<TemplateArgumentLoc> template_arguments() const {
  2827. return {getTemplateArgs(), getNumTemplateArgs()};
  2828. }
  2829. /// Retrieve the member declaration name info.
  2830. DeclarationNameInfo getMemberNameInfo() const {
  2831. return DeclarationNameInfo(MemberDecl->getDeclName(),
  2832. MemberLoc, MemberDNLoc);
  2833. }
  2834. SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
  2835. bool isArrow() const { return MemberExprBits.IsArrow; }
  2836. void setArrow(bool A) { MemberExprBits.IsArrow = A; }
  2837. /// getMemberLoc - Return the location of the "member", in X->F, it is the
  2838. /// location of 'F'.
  2839. SourceLocation getMemberLoc() const { return MemberLoc; }
  2840. void setMemberLoc(SourceLocation L) { MemberLoc = L; }
  2841. SourceLocation getBeginLoc() const LLVM_READONLY;
  2842. SourceLocation getEndLoc() const LLVM_READONLY;
  2843. SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
  2844. /// Determine whether the base of this explicit is implicit.
  2845. bool isImplicitAccess() const {
  2846. return getBase() && getBase()->isImplicitCXXThis();
  2847. }
  2848. /// Returns true if this member expression refers to a method that
  2849. /// was resolved from an overloaded set having size greater than 1.
  2850. bool hadMultipleCandidates() const {
  2851. return MemberExprBits.HadMultipleCandidates;
  2852. }
  2853. /// Sets the flag telling whether this expression refers to
  2854. /// a method that was resolved from an overloaded set having size
  2855. /// greater than 1.
  2856. void setHadMultipleCandidates(bool V = true) {
  2857. MemberExprBits.HadMultipleCandidates = V;
  2858. }
  2859. /// Returns true if virtual dispatch is performed.
  2860. /// If the member access is fully qualified, (i.e. X::f()), virtual
  2861. /// dispatching is not performed. In -fapple-kext mode qualified
  2862. /// calls to virtual method will still go through the vtable.
  2863. bool performsVirtualDispatch(const LangOptions &LO) const {
  2864. return LO.AppleKext || !hasQualifier();
  2865. }
  2866. /// Is this expression a non-odr-use reference, and if so, why?
  2867. /// This is only meaningful if the named member is a static member.
  2868. NonOdrUseReason isNonOdrUse() const {
  2869. return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
  2870. }
  2871. static bool classof(const Stmt *T) {
  2872. return T->getStmtClass() == MemberExprClass;
  2873. }
  2874. // Iterators
  2875. child_range children() { return child_range(&Base, &Base+1); }
  2876. const_child_range children() const {
  2877. return const_child_range(&Base, &Base + 1);
  2878. }
  2879. };
  2880. /// CompoundLiteralExpr - [C99 6.5.2.5]
  2881. ///
  2882. class CompoundLiteralExpr : public Expr {
  2883. /// LParenLoc - If non-null, this is the location of the left paren in a
  2884. /// compound literal like "(int){4}". This can be null if this is a
  2885. /// synthesized compound expression.
  2886. SourceLocation LParenLoc;
  2887. /// The type as written. This can be an incomplete array type, in
  2888. /// which case the actual expression type will be different.
  2889. /// The int part of the pair stores whether this expr is file scope.
  2890. llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
  2891. Stmt *Init;
  2892. public:
  2893. CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
  2894. QualType T, ExprValueKind VK, Expr *init, bool fileScope)
  2895. : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
  2896. LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
  2897. setDependence(computeDependence(this));
  2898. }
  2899. /// Construct an empty compound literal.
  2900. explicit CompoundLiteralExpr(EmptyShell Empty)
  2901. : Expr(CompoundLiteralExprClass, Empty) { }
  2902. const Expr *getInitializer() const { return cast<Expr>(Init); }
  2903. Expr *getInitializer() { return cast<Expr>(Init); }
  2904. void setInitializer(Expr *E) { Init = E; }
  2905. bool isFileScope() const { return TInfoAndScope.getInt(); }
  2906. void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
  2907. SourceLocation getLParenLoc() const { return LParenLoc; }
  2908. void setLParenLoc(SourceLocation L) { LParenLoc = L; }
  2909. TypeSourceInfo *getTypeSourceInfo() const {
  2910. return TInfoAndScope.getPointer();
  2911. }
  2912. void setTypeSourceInfo(TypeSourceInfo *tinfo) {
  2913. TInfoAndScope.setPointer(tinfo);
  2914. }
  2915. SourceLocation getBeginLoc() const LLVM_READONLY {
  2916. // FIXME: Init should never be null.
  2917. if (!Init)
  2918. return SourceLocation();
  2919. if (LParenLoc.isInvalid())
  2920. return Init->getBeginLoc();
  2921. return LParenLoc;
  2922. }
  2923. SourceLocation getEndLoc() const LLVM_READONLY {
  2924. // FIXME: Init should never be null.
  2925. if (!Init)
  2926. return SourceLocation();
  2927. return Init->getEndLoc();
  2928. }
  2929. static bool classof(const Stmt *T) {
  2930. return T->getStmtClass() == CompoundLiteralExprClass;
  2931. }
  2932. // Iterators
  2933. child_range children() { return child_range(&Init, &Init+1); }
  2934. const_child_range children() const {
  2935. return const_child_range(&Init, &Init + 1);
  2936. }
  2937. };
  2938. /// CastExpr - Base class for type casts, including both implicit
  2939. /// casts (ImplicitCastExpr) and explicit casts that have some
  2940. /// representation in the source code (ExplicitCastExpr's derived
  2941. /// classes).
  2942. class CastExpr : public Expr {
  2943. Stmt *Op;
  2944. bool CastConsistency() const;
  2945. const CXXBaseSpecifier * const *path_buffer() const {
  2946. return const_cast<CastExpr*>(this)->path_buffer();
  2947. }
  2948. CXXBaseSpecifier **path_buffer();
  2949. friend class ASTStmtReader;
  2950. protected:
  2951. CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
  2952. Expr *op, unsigned BasePathSize, bool HasFPFeatures)
  2953. : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
  2954. CastExprBits.Kind = kind;
  2955. CastExprBits.PartOfExplicitCast = false;
  2956. CastExprBits.BasePathSize = BasePathSize;
  2957. assert((CastExprBits.BasePathSize == BasePathSize) &&
  2958. "BasePathSize overflow!");
  2959. setDependence(computeDependence(this));
  2960. assert(CastConsistency());
  2961. CastExprBits.HasFPFeatures = HasFPFeatures;
  2962. }
  2963. /// Construct an empty cast.
  2964. CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
  2965. bool HasFPFeatures)
  2966. : Expr(SC, Empty) {
  2967. CastExprBits.PartOfExplicitCast = false;
  2968. CastExprBits.BasePathSize = BasePathSize;
  2969. CastExprBits.HasFPFeatures = HasFPFeatures;
  2970. assert((CastExprBits.BasePathSize == BasePathSize) &&
  2971. "BasePathSize overflow!");
  2972. }
  2973. /// Return a pointer to the trailing FPOptions.
  2974. /// \pre hasStoredFPFeatures() == true
  2975. FPOptionsOverride *getTrailingFPFeatures();
  2976. const FPOptionsOverride *getTrailingFPFeatures() const {
  2977. return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
  2978. }
  2979. public:
  2980. CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
  2981. void setCastKind(CastKind K) { CastExprBits.Kind = K; }
  2982. static const char *getCastKindName(CastKind CK);
  2983. const char *getCastKindName() const { return getCastKindName(getCastKind()); }
  2984. Expr *getSubExpr() { return cast<Expr>(Op); }
  2985. const Expr *getSubExpr() const { return cast<Expr>(Op); }
  2986. void setSubExpr(Expr *E) { Op = E; }
  2987. /// Retrieve the cast subexpression as it was written in the source
  2988. /// code, looking through any implicit casts or other intermediate nodes
  2989. /// introduced by semantic analysis.
  2990. Expr *getSubExprAsWritten();
  2991. const Expr *getSubExprAsWritten() const {
  2992. return const_cast<CastExpr *>(this)->getSubExprAsWritten();
  2993. }
  2994. /// If this cast applies a user-defined conversion, retrieve the conversion
  2995. /// function that it invokes.
  2996. NamedDecl *getConversionFunction() const;
  2997. typedef CXXBaseSpecifier **path_iterator;
  2998. typedef const CXXBaseSpecifier *const *path_const_iterator;
  2999. bool path_empty() const { return path_size() == 0; }
  3000. unsigned path_size() const { return CastExprBits.BasePathSize; }
  3001. path_iterator path_begin() { return path_buffer(); }
  3002. path_iterator path_end() { return path_buffer() + path_size(); }
  3003. path_const_iterator path_begin() const { return path_buffer(); }
  3004. path_const_iterator path_end() const { return path_buffer() + path_size(); }
  3005. llvm::iterator_range<path_iterator> path() {
  3006. return llvm::make_range(path_begin(), path_end());
  3007. }
  3008. llvm::iterator_range<path_const_iterator> path() const {
  3009. return llvm::make_range(path_begin(), path_end());
  3010. }
  3011. const FieldDecl *getTargetUnionField() const {
  3012. assert(getCastKind() == CK_ToUnion);
  3013. return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
  3014. }
  3015. bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
  3016. /// Get FPOptionsOverride from trailing storage.
  3017. FPOptionsOverride getStoredFPFeatures() const {
  3018. assert(hasStoredFPFeatures());
  3019. return *getTrailingFPFeatures();
  3020. }
  3021. // Get the FP features status of this operation. Only meaningful for
  3022. // operations on floating point types.
  3023. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  3024. if (hasStoredFPFeatures())
  3025. return getStoredFPFeatures().applyOverrides(LO);
  3026. return FPOptions::defaultWithoutTrailingStorage(LO);
  3027. }
  3028. FPOptionsOverride getFPFeatures() const {
  3029. if (hasStoredFPFeatures())
  3030. return getStoredFPFeatures();
  3031. return FPOptionsOverride();
  3032. }
  3033. static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
  3034. QualType opType);
  3035. static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
  3036. QualType opType);
  3037. static bool classof(const Stmt *T) {
  3038. return T->getStmtClass() >= firstCastExprConstant &&
  3039. T->getStmtClass() <= lastCastExprConstant;
  3040. }
  3041. // Iterators
  3042. child_range children() { return child_range(&Op, &Op+1); }
  3043. const_child_range children() const { return const_child_range(&Op, &Op + 1); }
  3044. };
  3045. /// ImplicitCastExpr - Allows us to explicitly represent implicit type
  3046. /// conversions, which have no direct representation in the original
  3047. /// source code. For example: converting T[]->T*, void f()->void
  3048. /// (*f)(), float->double, short->int, etc.
  3049. ///
  3050. /// In C, implicit casts always produce rvalues. However, in C++, an
  3051. /// implicit cast whose result is being bound to a reference will be
  3052. /// an lvalue or xvalue. For example:
  3053. ///
  3054. /// @code
  3055. /// class Base { };
  3056. /// class Derived : public Base { };
  3057. /// Derived &&ref();
  3058. /// void f(Derived d) {
  3059. /// Base& b = d; // initializer is an ImplicitCastExpr
  3060. /// // to an lvalue of type Base
  3061. /// Base&& r = ref(); // initializer is an ImplicitCastExpr
  3062. /// // to an xvalue of type Base
  3063. /// }
  3064. /// @endcode
  3065. class ImplicitCastExpr final
  3066. : public CastExpr,
  3067. private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
  3068. FPOptionsOverride> {
  3069. ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
  3070. unsigned BasePathLength, FPOptionsOverride FPO,
  3071. ExprValueKind VK)
  3072. : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
  3073. FPO.requiresTrailingStorage()) {
  3074. if (hasStoredFPFeatures())
  3075. *getTrailingFPFeatures() = FPO;
  3076. }
  3077. /// Construct an empty implicit cast.
  3078. explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
  3079. bool HasFPFeatures)
  3080. : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
  3081. unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
  3082. return path_size();
  3083. }
  3084. public:
  3085. enum OnStack_t { OnStack };
  3086. ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
  3087. ExprValueKind VK, FPOptionsOverride FPO)
  3088. : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
  3089. FPO.requiresTrailingStorage()) {
  3090. if (hasStoredFPFeatures())
  3091. *getTrailingFPFeatures() = FPO;
  3092. }
  3093. bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
  3094. void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
  3095. CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
  3096. }
  3097. static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
  3098. CastKind Kind, Expr *Operand,
  3099. const CXXCastPath *BasePath,
  3100. ExprValueKind Cat, FPOptionsOverride FPO);
  3101. static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
  3102. unsigned PathSize, bool HasFPFeatures);
  3103. SourceLocation getBeginLoc() const LLVM_READONLY {
  3104. return getSubExpr()->getBeginLoc();
  3105. }
  3106. SourceLocation getEndLoc() const LLVM_READONLY {
  3107. return getSubExpr()->getEndLoc();
  3108. }
  3109. static bool classof(const Stmt *T) {
  3110. return T->getStmtClass() == ImplicitCastExprClass;
  3111. }
  3112. friend TrailingObjects;
  3113. friend class CastExpr;
  3114. };
  3115. /// ExplicitCastExpr - An explicit cast written in the source
  3116. /// code.
  3117. ///
  3118. /// This class is effectively an abstract class, because it provides
  3119. /// the basic representation of an explicitly-written cast without
  3120. /// specifying which kind of cast (C cast, functional cast, static
  3121. /// cast, etc.) was written; specific derived classes represent the
  3122. /// particular style of cast and its location information.
  3123. ///
  3124. /// Unlike implicit casts, explicit cast nodes have two different
  3125. /// types: the type that was written into the source code, and the
  3126. /// actual type of the expression as determined by semantic
  3127. /// analysis. These types may differ slightly. For example, in C++ one
  3128. /// can cast to a reference type, which indicates that the resulting
  3129. /// expression will be an lvalue or xvalue. The reference type, however,
  3130. /// will not be used as the type of the expression.
  3131. class ExplicitCastExpr : public CastExpr {
  3132. /// TInfo - Source type info for the (written) type
  3133. /// this expression is casting to.
  3134. TypeSourceInfo *TInfo;
  3135. protected:
  3136. ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
  3137. CastKind kind, Expr *op, unsigned PathSize,
  3138. bool HasFPFeatures, TypeSourceInfo *writtenTy)
  3139. : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
  3140. TInfo(writtenTy) {}
  3141. /// Construct an empty explicit cast.
  3142. ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
  3143. bool HasFPFeatures)
  3144. : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
  3145. public:
  3146. /// getTypeInfoAsWritten - Returns the type source info for the type
  3147. /// that this expression is casting to.
  3148. TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
  3149. void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
  3150. /// getTypeAsWritten - Returns the type that this expression is
  3151. /// casting to, as written in the source code.
  3152. QualType getTypeAsWritten() const { return TInfo->getType(); }
  3153. static bool classof(const Stmt *T) {
  3154. return T->getStmtClass() >= firstExplicitCastExprConstant &&
  3155. T->getStmtClass() <= lastExplicitCastExprConstant;
  3156. }
  3157. };
  3158. /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
  3159. /// cast in C++ (C++ [expr.cast]), which uses the syntax
  3160. /// (Type)expr. For example: @c (int)f.
  3161. class CStyleCastExpr final
  3162. : public ExplicitCastExpr,
  3163. private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
  3164. FPOptionsOverride> {
  3165. SourceLocation LPLoc; // the location of the left paren
  3166. SourceLocation RPLoc; // the location of the right paren
  3167. CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
  3168. unsigned PathSize, FPOptionsOverride FPO,
  3169. TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
  3170. : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
  3171. FPO.requiresTrailingStorage(), writtenTy),
  3172. LPLoc(l), RPLoc(r) {
  3173. if (hasStoredFPFeatures())
  3174. *getTrailingFPFeatures() = FPO;
  3175. }
  3176. /// Construct an empty C-style explicit cast.
  3177. explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
  3178. bool HasFPFeatures)
  3179. : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
  3180. unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
  3181. return path_size();
  3182. }
  3183. public:
  3184. static CStyleCastExpr *
  3185. Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
  3186. Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
  3187. TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
  3188. static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
  3189. unsigned PathSize, bool HasFPFeatures);
  3190. SourceLocation getLParenLoc() const { return LPLoc; }
  3191. void setLParenLoc(SourceLocation L) { LPLoc = L; }
  3192. SourceLocation getRParenLoc() const { return RPLoc; }
  3193. void setRParenLoc(SourceLocation L) { RPLoc = L; }
  3194. SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
  3195. SourceLocation getEndLoc() const LLVM_READONLY {
  3196. return getSubExpr()->getEndLoc();
  3197. }
  3198. static bool classof(const Stmt *T) {
  3199. return T->getStmtClass() == CStyleCastExprClass;
  3200. }
  3201. friend TrailingObjects;
  3202. friend class CastExpr;
  3203. };
  3204. /// A builtin binary operation expression such as "x + y" or "x <= y".
  3205. ///
  3206. /// This expression node kind describes a builtin binary operation,
  3207. /// such as "x + y" for integer values "x" and "y". The operands will
  3208. /// already have been converted to appropriate types (e.g., by
  3209. /// performing promotions or conversions).
  3210. ///
  3211. /// In C++, where operators may be overloaded, a different kind of
  3212. /// expression node (CXXOperatorCallExpr) is used to express the
  3213. /// invocation of an overloaded operator with operator syntax. Within
  3214. /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
  3215. /// used to store an expression "x + y" depends on the subexpressions
  3216. /// for x and y. If neither x or y is type-dependent, and the "+"
  3217. /// operator resolves to a built-in operation, BinaryOperator will be
  3218. /// used to express the computation (x and y may still be
  3219. /// value-dependent). If either x or y is type-dependent, or if the
  3220. /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
  3221. /// be used to express the computation.
  3222. class BinaryOperator : public Expr {
  3223. enum { LHS, RHS, END_EXPR };
  3224. Stmt *SubExprs[END_EXPR];
  3225. public:
  3226. typedef BinaryOperatorKind Opcode;
  3227. protected:
  3228. size_t offsetOfTrailingStorage() const;
  3229. /// Return a pointer to the trailing FPOptions
  3230. FPOptionsOverride *getTrailingFPFeatures() {
  3231. assert(BinaryOperatorBits.HasFPFeatures);
  3232. return reinterpret_cast<FPOptionsOverride *>(
  3233. reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
  3234. }
  3235. const FPOptionsOverride *getTrailingFPFeatures() const {
  3236. assert(BinaryOperatorBits.HasFPFeatures);
  3237. return reinterpret_cast<const FPOptionsOverride *>(
  3238. reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
  3239. }
  3240. /// Build a binary operator, assuming that appropriate storage has been
  3241. /// allocated for the trailing objects when needed.
  3242. BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
  3243. QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
  3244. SourceLocation opLoc, FPOptionsOverride FPFeatures);
  3245. /// Construct an empty binary operator.
  3246. explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
  3247. BinaryOperatorBits.Opc = BO_Comma;
  3248. }
  3249. public:
  3250. static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
  3251. static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
  3252. Opcode opc, QualType ResTy, ExprValueKind VK,
  3253. ExprObjectKind OK, SourceLocation opLoc,
  3254. FPOptionsOverride FPFeatures);
  3255. SourceLocation getExprLoc() const { return getOperatorLoc(); }
  3256. SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
  3257. void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
  3258. Opcode getOpcode() const {
  3259. return static_cast<Opcode>(BinaryOperatorBits.Opc);
  3260. }
  3261. void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
  3262. Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  3263. void setLHS(Expr *E) { SubExprs[LHS] = E; }
  3264. Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  3265. void setRHS(Expr *E) { SubExprs[RHS] = E; }
  3266. SourceLocation getBeginLoc() const LLVM_READONLY {
  3267. return getLHS()->getBeginLoc();
  3268. }
  3269. SourceLocation getEndLoc() const LLVM_READONLY {
  3270. return getRHS()->getEndLoc();
  3271. }
  3272. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  3273. /// corresponds to, e.g. "<<=".
  3274. static StringRef getOpcodeStr(Opcode Op);
  3275. StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
  3276. /// Retrieve the binary opcode that corresponds to the given
  3277. /// overloaded operator.
  3278. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
  3279. /// Retrieve the overloaded operator kind that corresponds to
  3280. /// the given binary opcode.
  3281. static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
  3282. /// predicates to categorize the respective opcodes.
  3283. static bool isPtrMemOp(Opcode Opc) {
  3284. return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
  3285. }
  3286. bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
  3287. static bool isMultiplicativeOp(Opcode Opc) {
  3288. return Opc >= BO_Mul && Opc <= BO_Rem;
  3289. }
  3290. bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
  3291. static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
  3292. bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
  3293. static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
  3294. bool isShiftOp() const { return isShiftOp(getOpcode()); }
  3295. static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
  3296. bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
  3297. static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
  3298. bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
  3299. static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
  3300. bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
  3301. static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
  3302. bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
  3303. static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
  3304. bool isCommaOp() const { return isCommaOp(getOpcode()); }
  3305. static Opcode negateComparisonOp(Opcode Opc) {
  3306. switch (Opc) {
  3307. default:
  3308. llvm_unreachable("Not a comparison operator.");
  3309. case BO_LT: return BO_GE;
  3310. case BO_GT: return BO_LE;
  3311. case BO_LE: return BO_GT;
  3312. case BO_GE: return BO_LT;
  3313. case BO_EQ: return BO_NE;
  3314. case BO_NE: return BO_EQ;
  3315. }
  3316. }
  3317. static Opcode reverseComparisonOp(Opcode Opc) {
  3318. switch (Opc) {
  3319. default:
  3320. llvm_unreachable("Not a comparison operator.");
  3321. case BO_LT: return BO_GT;
  3322. case BO_GT: return BO_LT;
  3323. case BO_LE: return BO_GE;
  3324. case BO_GE: return BO_LE;
  3325. case BO_EQ:
  3326. case BO_NE:
  3327. return Opc;
  3328. }
  3329. }
  3330. static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
  3331. bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
  3332. static bool isAssignmentOp(Opcode Opc) {
  3333. return Opc >= BO_Assign && Opc <= BO_OrAssign;
  3334. }
  3335. bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
  3336. static bool isCompoundAssignmentOp(Opcode Opc) {
  3337. return Opc > BO_Assign && Opc <= BO_OrAssign;
  3338. }
  3339. bool isCompoundAssignmentOp() const {
  3340. return isCompoundAssignmentOp(getOpcode());
  3341. }
  3342. static Opcode getOpForCompoundAssignment(Opcode Opc) {
  3343. assert(isCompoundAssignmentOp(Opc));
  3344. if (Opc >= BO_AndAssign)
  3345. return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
  3346. else
  3347. return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
  3348. }
  3349. static bool isShiftAssignOp(Opcode Opc) {
  3350. return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
  3351. }
  3352. bool isShiftAssignOp() const {
  3353. return isShiftAssignOp(getOpcode());
  3354. }
  3355. // Return true if a binary operator using the specified opcode and operands
  3356. // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
  3357. // integer to a pointer.
  3358. static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
  3359. Expr *LHS, Expr *RHS);
  3360. static bool classof(const Stmt *S) {
  3361. return S->getStmtClass() >= firstBinaryOperatorConstant &&
  3362. S->getStmtClass() <= lastBinaryOperatorConstant;
  3363. }
  3364. // Iterators
  3365. child_range children() {
  3366. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  3367. }
  3368. const_child_range children() const {
  3369. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  3370. }
  3371. /// Set and fetch the bit that shows whether FPFeatures needs to be
  3372. /// allocated in Trailing Storage
  3373. void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
  3374. bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
  3375. /// Get FPFeatures from trailing storage
  3376. FPOptionsOverride getStoredFPFeatures() const {
  3377. assert(hasStoredFPFeatures());
  3378. return *getTrailingFPFeatures();
  3379. }
  3380. /// Set FPFeatures in trailing storage, used only by Serialization
  3381. void setStoredFPFeatures(FPOptionsOverride F) {
  3382. assert(BinaryOperatorBits.HasFPFeatures);
  3383. *getTrailingFPFeatures() = F;
  3384. }
  3385. // Get the FP features status of this operator. Only meaningful for
  3386. // operations on floating point types.
  3387. FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
  3388. if (BinaryOperatorBits.HasFPFeatures)
  3389. return getStoredFPFeatures().applyOverrides(LO);
  3390. return FPOptions::defaultWithoutTrailingStorage(LO);
  3391. }
  3392. // This is used in ASTImporter
  3393. FPOptionsOverride getFPFeatures(const LangOptions &LO) const {
  3394. if (BinaryOperatorBits.HasFPFeatures)
  3395. return getStoredFPFeatures();
  3396. return FPOptionsOverride();
  3397. }
  3398. // Get the FP contractability status of this operator. Only meaningful for
  3399. // operations on floating point types.
  3400. bool isFPContractableWithinStatement(const LangOptions &LO) const {
  3401. return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
  3402. }
  3403. // Get the FENV_ACCESS status of this operator. Only meaningful for
  3404. // operations on floating point types.
  3405. bool isFEnvAccessOn(const LangOptions &LO) const {
  3406. return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
  3407. }
  3408. protected:
  3409. BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
  3410. QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
  3411. SourceLocation opLoc, FPOptionsOverride FPFeatures,
  3412. bool dead2);
  3413. /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
  3414. BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
  3415. BinaryOperatorBits.Opc = BO_MulAssign;
  3416. }
  3417. /// Return the size in bytes needed for the trailing objects.
  3418. /// Used to allocate the right amount of storage.
  3419. static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
  3420. return HasFPFeatures * sizeof(FPOptionsOverride);
  3421. }
  3422. };
  3423. /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
  3424. /// track of the type the operation is performed in. Due to the semantics of
  3425. /// these operators, the operands are promoted, the arithmetic performed, an
  3426. /// implicit conversion back to the result type done, then the assignment takes
  3427. /// place. This captures the intermediate type which the computation is done
  3428. /// in.
  3429. class CompoundAssignOperator : public BinaryOperator {
  3430. QualType ComputationLHSType;
  3431. QualType ComputationResultType;
  3432. /// Construct an empty CompoundAssignOperator.
  3433. explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
  3434. bool hasFPFeatures)
  3435. : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
  3436. protected:
  3437. CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
  3438. QualType ResType, ExprValueKind VK, ExprObjectKind OK,
  3439. SourceLocation OpLoc, FPOptionsOverride FPFeatures,
  3440. QualType CompLHSType, QualType CompResultType)
  3441. : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
  3442. true),
  3443. ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
  3444. assert(isCompoundAssignmentOp() &&
  3445. "Only should be used for compound assignments");
  3446. }
  3447. public:
  3448. static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
  3449. bool hasFPFeatures);
  3450. static CompoundAssignOperator *
  3451. Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
  3452. ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
  3453. FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
  3454. QualType CompResultType = QualType());
  3455. // The two computation types are the type the LHS is converted
  3456. // to for the computation and the type of the result; the two are
  3457. // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
  3458. QualType getComputationLHSType() const { return ComputationLHSType; }
  3459. void setComputationLHSType(QualType T) { ComputationLHSType = T; }
  3460. QualType getComputationResultType() const { return ComputationResultType; }
  3461. void setComputationResultType(QualType T) { ComputationResultType = T; }
  3462. static bool classof(const Stmt *S) {
  3463. return S->getStmtClass() == CompoundAssignOperatorClass;
  3464. }
  3465. };
  3466. inline size_t BinaryOperator::offsetOfTrailingStorage() const {
  3467. assert(BinaryOperatorBits.HasFPFeatures);
  3468. return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
  3469. : sizeof(BinaryOperator);
  3470. }
  3471. /// AbstractConditionalOperator - An abstract base class for
  3472. /// ConditionalOperator and BinaryConditionalOperator.
  3473. class AbstractConditionalOperator : public Expr {
  3474. SourceLocation QuestionLoc, ColonLoc;
  3475. friend class ASTStmtReader;
  3476. protected:
  3477. AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
  3478. ExprObjectKind OK, SourceLocation qloc,
  3479. SourceLocation cloc)
  3480. : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
  3481. AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
  3482. : Expr(SC, Empty) { }
  3483. public:
  3484. // getCond - Return the expression representing the condition for
  3485. // the ?: operator.
  3486. Expr *getCond() const;
  3487. // getTrueExpr - Return the subexpression representing the value of
  3488. // the expression if the condition evaluates to true.
  3489. Expr *getTrueExpr() const;
  3490. // getFalseExpr - Return the subexpression representing the value of
  3491. // the expression if the condition evaluates to false. This is
  3492. // the same as getRHS.
  3493. Expr *getFalseExpr() const;
  3494. SourceLocation getQuestionLoc() const { return QuestionLoc; }
  3495. SourceLocation getColonLoc() const { return ColonLoc; }
  3496. static bool classof(const Stmt *T) {
  3497. return T->getStmtClass() == ConditionalOperatorClass ||
  3498. T->getStmtClass() == BinaryConditionalOperatorClass;
  3499. }
  3500. };
  3501. /// ConditionalOperator - The ?: ternary operator. The GNU "missing
  3502. /// middle" extension is a BinaryConditionalOperator.
  3503. class ConditionalOperator : public AbstractConditionalOperator {
  3504. enum { COND, LHS, RHS, END_EXPR };
  3505. Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
  3506. friend class ASTStmtReader;
  3507. public:
  3508. ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
  3509. SourceLocation CLoc, Expr *rhs, QualType t,
  3510. ExprValueKind VK, ExprObjectKind OK)
  3511. : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
  3512. CLoc) {
  3513. SubExprs[COND] = cond;
  3514. SubExprs[LHS] = lhs;
  3515. SubExprs[RHS] = rhs;
  3516. setDependence(computeDependence(this));
  3517. }
  3518. /// Build an empty conditional operator.
  3519. explicit ConditionalOperator(EmptyShell Empty)
  3520. : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
  3521. // getCond - Return the expression representing the condition for
  3522. // the ?: operator.
  3523. Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
  3524. // getTrueExpr - Return the subexpression representing the value of
  3525. // the expression if the condition evaluates to true.
  3526. Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
  3527. // getFalseExpr - Return the subexpression representing the value of
  3528. // the expression if the condition evaluates to false. This is
  3529. // the same as getRHS.
  3530. Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
  3531. Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  3532. Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  3533. SourceLocation getBeginLoc() const LLVM_READONLY {
  3534. return getCond()->getBeginLoc();
  3535. }
  3536. SourceLocation getEndLoc() const LLVM_READONLY {
  3537. return getRHS()->getEndLoc();
  3538. }
  3539. static bool classof(const Stmt *T) {
  3540. return T->getStmtClass() == ConditionalOperatorClass;
  3541. }
  3542. // Iterators
  3543. child_range children() {
  3544. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  3545. }
  3546. const_child_range children() const {
  3547. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  3548. }
  3549. };
  3550. /// BinaryConditionalOperator - The GNU extension to the conditional
  3551. /// operator which allows the middle operand to be omitted.
  3552. ///
  3553. /// This is a different expression kind on the assumption that almost
  3554. /// every client ends up needing to know that these are different.
  3555. class BinaryConditionalOperator : public AbstractConditionalOperator {
  3556. enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
  3557. /// - the common condition/left-hand-side expression, which will be
  3558. /// evaluated as the opaque value
  3559. /// - the condition, expressed in terms of the opaque value
  3560. /// - the left-hand-side, expressed in terms of the opaque value
  3561. /// - the right-hand-side
  3562. Stmt *SubExprs[NUM_SUBEXPRS];
  3563. OpaqueValueExpr *OpaqueValue;
  3564. friend class ASTStmtReader;
  3565. public:
  3566. BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
  3567. Expr *cond, Expr *lhs, Expr *rhs,
  3568. SourceLocation qloc, SourceLocation cloc,
  3569. QualType t, ExprValueKind VK, ExprObjectKind OK)
  3570. : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
  3571. qloc, cloc),
  3572. OpaqueValue(opaqueValue) {
  3573. SubExprs[COMMON] = common;
  3574. SubExprs[COND] = cond;
  3575. SubExprs[LHS] = lhs;
  3576. SubExprs[RHS] = rhs;
  3577. assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
  3578. setDependence(computeDependence(this));
  3579. }
  3580. /// Build an empty conditional operator.
  3581. explicit BinaryConditionalOperator(EmptyShell Empty)
  3582. : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
  3583. /// getCommon - Return the common expression, written to the
  3584. /// left of the condition. The opaque value will be bound to the
  3585. /// result of this expression.
  3586. Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
  3587. /// getOpaqueValue - Return the opaque value placeholder.
  3588. OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
  3589. /// getCond - Return the condition expression; this is defined
  3590. /// in terms of the opaque value.
  3591. Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
  3592. /// getTrueExpr - Return the subexpression which will be
  3593. /// evaluated if the condition evaluates to true; this is defined
  3594. /// in terms of the opaque value.
  3595. Expr *getTrueExpr() const {
  3596. return cast<Expr>(SubExprs[LHS]);
  3597. }
  3598. /// getFalseExpr - Return the subexpression which will be
  3599. /// evaluated if the condnition evaluates to false; this is
  3600. /// defined in terms of the opaque value.
  3601. Expr *getFalseExpr() const {
  3602. return cast<Expr>(SubExprs[RHS]);
  3603. }
  3604. SourceLocation getBeginLoc() const LLVM_READONLY {
  3605. return getCommon()->getBeginLoc();
  3606. }
  3607. SourceLocation getEndLoc() const LLVM_READONLY {
  3608. return getFalseExpr()->getEndLoc();
  3609. }
  3610. static bool classof(const Stmt *T) {
  3611. return T->getStmtClass() == BinaryConditionalOperatorClass;
  3612. }
  3613. // Iterators
  3614. child_range children() {
  3615. return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
  3616. }
  3617. const_child_range children() const {
  3618. return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
  3619. }
  3620. };
  3621. inline Expr *AbstractConditionalOperator::getCond() const {
  3622. if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
  3623. return co->getCond();
  3624. return cast<BinaryConditionalOperator>(this)->getCond();
  3625. }
  3626. inline Expr *AbstractConditionalOperator::getTrueExpr() const {
  3627. if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
  3628. return co->getTrueExpr();
  3629. return cast<BinaryConditionalOperator>(this)->getTrueExpr();
  3630. }
  3631. inline Expr *AbstractConditionalOperator::getFalseExpr() const {
  3632. if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
  3633. return co->getFalseExpr();
  3634. return cast<BinaryConditionalOperator>(this)->getFalseExpr();
  3635. }
  3636. /// AddrLabelExpr - The GNU address of label extension, representing &&label.
  3637. class AddrLabelExpr : public Expr {
  3638. SourceLocation AmpAmpLoc, LabelLoc;
  3639. LabelDecl *Label;
  3640. public:
  3641. AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
  3642. QualType t)
  3643. : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
  3644. LabelLoc(LLoc), Label(L) {
  3645. setDependence(ExprDependence::None);
  3646. }
  3647. /// Build an empty address of a label expression.
  3648. explicit AddrLabelExpr(EmptyShell Empty)
  3649. : Expr(AddrLabelExprClass, Empty) { }
  3650. SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
  3651. void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
  3652. SourceLocation getLabelLoc() const { return LabelLoc; }
  3653. void setLabelLoc(SourceLocation L) { LabelLoc = L; }
  3654. SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
  3655. SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
  3656. LabelDecl *getLabel() const { return Label; }
  3657. void setLabel(LabelDecl *L) { Label = L; }
  3658. static bool classof(const Stmt *T) {
  3659. return T->getStmtClass() == AddrLabelExprClass;
  3660. }
  3661. // Iterators
  3662. child_range children() {
  3663. return child_range(child_iterator(), child_iterator());
  3664. }
  3665. const_child_range children() const {
  3666. return const_child_range(const_child_iterator(), const_child_iterator());
  3667. }
  3668. };
  3669. /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
  3670. /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
  3671. /// takes the value of the last subexpression.
  3672. ///
  3673. /// A StmtExpr is always an r-value; values "returned" out of a
  3674. /// StmtExpr will be copied.
  3675. class StmtExpr : public Expr {
  3676. Stmt *SubStmt;
  3677. SourceLocation LParenLoc, RParenLoc;
  3678. public:
  3679. StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
  3680. SourceLocation RParenLoc, unsigned TemplateDepth)
  3681. : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
  3682. LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
  3683. setDependence(computeDependence(this, TemplateDepth));
  3684. // FIXME: A templated statement expression should have an associated
  3685. // DeclContext so that nested declarations always have a dependent context.
  3686. StmtExprBits.TemplateDepth = TemplateDepth;
  3687. }
  3688. /// Build an empty statement expression.
  3689. explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
  3690. CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
  3691. const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
  3692. void setSubStmt(CompoundStmt *S) { SubStmt = S; }
  3693. SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
  3694. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3695. SourceLocation getLParenLoc() const { return LParenLoc; }
  3696. void setLParenLoc(SourceLocation L) { LParenLoc = L; }
  3697. SourceLocation getRParenLoc() const { return RParenLoc; }
  3698. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3699. unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
  3700. static bool classof(const Stmt *T) {
  3701. return T->getStmtClass() == StmtExprClass;
  3702. }
  3703. // Iterators
  3704. child_range children() { return child_range(&SubStmt, &SubStmt+1); }
  3705. const_child_range children() const {
  3706. return const_child_range(&SubStmt, &SubStmt + 1);
  3707. }
  3708. };
  3709. /// ShuffleVectorExpr - clang-specific builtin-in function
  3710. /// __builtin_shufflevector.
  3711. /// This AST node represents a operator that does a constant
  3712. /// shuffle, similar to LLVM's shufflevector instruction. It takes
  3713. /// two vectors and a variable number of constant indices,
  3714. /// and returns the appropriately shuffled vector.
  3715. class ShuffleVectorExpr : public Expr {
  3716. SourceLocation BuiltinLoc, RParenLoc;
  3717. // SubExprs - the list of values passed to the __builtin_shufflevector
  3718. // function. The first two are vectors, and the rest are constant
  3719. // indices. The number of values in this list is always
  3720. // 2+the number of indices in the vector type.
  3721. Stmt **SubExprs;
  3722. unsigned NumExprs;
  3723. public:
  3724. ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
  3725. SourceLocation BLoc, SourceLocation RP);
  3726. /// Build an empty vector-shuffle expression.
  3727. explicit ShuffleVectorExpr(EmptyShell Empty)
  3728. : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
  3729. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3730. void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
  3731. SourceLocation getRParenLoc() const { return RParenLoc; }
  3732. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3733. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3734. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3735. static bool classof(const Stmt *T) {
  3736. return T->getStmtClass() == ShuffleVectorExprClass;
  3737. }
  3738. /// getNumSubExprs - Return the size of the SubExprs array. This includes the
  3739. /// constant expression, the actual arguments passed in, and the function
  3740. /// pointers.
  3741. unsigned getNumSubExprs() const { return NumExprs; }
  3742. /// Retrieve the array of expressions.
  3743. Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
  3744. /// getExpr - Return the Expr at the specified index.
  3745. Expr *getExpr(unsigned Index) {
  3746. assert((Index < NumExprs) && "Arg access out of range!");
  3747. return cast<Expr>(SubExprs[Index]);
  3748. }
  3749. const Expr *getExpr(unsigned Index) const {
  3750. assert((Index < NumExprs) && "Arg access out of range!");
  3751. return cast<Expr>(SubExprs[Index]);
  3752. }
  3753. void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
  3754. llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
  3755. assert((N < NumExprs - 2) && "Shuffle idx out of range!");
  3756. return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
  3757. }
  3758. // Iterators
  3759. child_range children() {
  3760. return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
  3761. }
  3762. const_child_range children() const {
  3763. return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
  3764. }
  3765. };
  3766. /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
  3767. /// This AST node provides support for converting a vector type to another
  3768. /// vector type of the same arity.
  3769. class ConvertVectorExpr : public Expr {
  3770. private:
  3771. Stmt *SrcExpr;
  3772. TypeSourceInfo *TInfo;
  3773. SourceLocation BuiltinLoc, RParenLoc;
  3774. friend class ASTReader;
  3775. friend class ASTStmtReader;
  3776. explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
  3777. public:
  3778. ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
  3779. ExprValueKind VK, ExprObjectKind OK,
  3780. SourceLocation BuiltinLoc, SourceLocation RParenLoc)
  3781. : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
  3782. TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
  3783. setDependence(computeDependence(this));
  3784. }
  3785. /// getSrcExpr - Return the Expr to be converted.
  3786. Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
  3787. /// getTypeSourceInfo - Return the destination type.
  3788. TypeSourceInfo *getTypeSourceInfo() const {
  3789. return TInfo;
  3790. }
  3791. void setTypeSourceInfo(TypeSourceInfo *ti) {
  3792. TInfo = ti;
  3793. }
  3794. /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
  3795. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3796. /// getRParenLoc - Return the location of final right parenthesis.
  3797. SourceLocation getRParenLoc() const { return RParenLoc; }
  3798. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3799. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3800. static bool classof(const Stmt *T) {
  3801. return T->getStmtClass() == ConvertVectorExprClass;
  3802. }
  3803. // Iterators
  3804. child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
  3805. const_child_range children() const {
  3806. return const_child_range(&SrcExpr, &SrcExpr + 1);
  3807. }
  3808. };
  3809. /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
  3810. /// This AST node is similar to the conditional operator (?:) in C, with
  3811. /// the following exceptions:
  3812. /// - the test expression must be a integer constant expression.
  3813. /// - the expression returned acts like the chosen subexpression in every
  3814. /// visible way: the type is the same as that of the chosen subexpression,
  3815. /// and all predicates (whether it's an l-value, whether it's an integer
  3816. /// constant expression, etc.) return the same result as for the chosen
  3817. /// sub-expression.
  3818. class ChooseExpr : public Expr {
  3819. enum { COND, LHS, RHS, END_EXPR };
  3820. Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
  3821. SourceLocation BuiltinLoc, RParenLoc;
  3822. bool CondIsTrue;
  3823. public:
  3824. ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
  3825. ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
  3826. bool condIsTrue)
  3827. : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
  3828. CondIsTrue(condIsTrue) {
  3829. SubExprs[COND] = cond;
  3830. SubExprs[LHS] = lhs;
  3831. SubExprs[RHS] = rhs;
  3832. setDependence(computeDependence(this));
  3833. }
  3834. /// Build an empty __builtin_choose_expr.
  3835. explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
  3836. /// isConditionTrue - Return whether the condition is true (i.e. not
  3837. /// equal to zero).
  3838. bool isConditionTrue() const {
  3839. assert(!isConditionDependent() &&
  3840. "Dependent condition isn't true or false");
  3841. return CondIsTrue;
  3842. }
  3843. void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
  3844. bool isConditionDependent() const {
  3845. return getCond()->isTypeDependent() || getCond()->isValueDependent();
  3846. }
  3847. /// getChosenSubExpr - Return the subexpression chosen according to the
  3848. /// condition.
  3849. Expr *getChosenSubExpr() const {
  3850. return isConditionTrue() ? getLHS() : getRHS();
  3851. }
  3852. Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
  3853. void setCond(Expr *E) { SubExprs[COND] = E; }
  3854. Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
  3855. void setLHS(Expr *E) { SubExprs[LHS] = E; }
  3856. Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
  3857. void setRHS(Expr *E) { SubExprs[RHS] = E; }
  3858. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3859. void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
  3860. SourceLocation getRParenLoc() const { return RParenLoc; }
  3861. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3862. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3863. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3864. static bool classof(const Stmt *T) {
  3865. return T->getStmtClass() == ChooseExprClass;
  3866. }
  3867. // Iterators
  3868. child_range children() {
  3869. return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
  3870. }
  3871. const_child_range children() const {
  3872. return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
  3873. }
  3874. };
  3875. /// GNUNullExpr - Implements the GNU __null extension, which is a name
  3876. /// for a null pointer constant that has integral type (e.g., int or
  3877. /// long) and is the same size and alignment as a pointer. The __null
  3878. /// extension is typically only used by system headers, which define
  3879. /// NULL as __null in C++ rather than using 0 (which is an integer
  3880. /// that may not match the size of a pointer).
  3881. class GNUNullExpr : public Expr {
  3882. /// TokenLoc - The location of the __null keyword.
  3883. SourceLocation TokenLoc;
  3884. public:
  3885. GNUNullExpr(QualType Ty, SourceLocation Loc)
  3886. : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
  3887. setDependence(ExprDependence::None);
  3888. }
  3889. /// Build an empty GNU __null expression.
  3890. explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
  3891. /// getTokenLocation - The location of the __null token.
  3892. SourceLocation getTokenLocation() const { return TokenLoc; }
  3893. void setTokenLocation(SourceLocation L) { TokenLoc = L; }
  3894. SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
  3895. SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
  3896. static bool classof(const Stmt *T) {
  3897. return T->getStmtClass() == GNUNullExprClass;
  3898. }
  3899. // Iterators
  3900. child_range children() {
  3901. return child_range(child_iterator(), child_iterator());
  3902. }
  3903. const_child_range children() const {
  3904. return const_child_range(const_child_iterator(), const_child_iterator());
  3905. }
  3906. };
  3907. /// Represents a call to the builtin function \c __builtin_va_arg.
  3908. class VAArgExpr : public Expr {
  3909. Stmt *Val;
  3910. llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
  3911. SourceLocation BuiltinLoc, RParenLoc;
  3912. public:
  3913. VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
  3914. SourceLocation RPLoc, QualType t, bool IsMS)
  3915. : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
  3916. TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
  3917. setDependence(computeDependence(this));
  3918. }
  3919. /// Create an empty __builtin_va_arg expression.
  3920. explicit VAArgExpr(EmptyShell Empty)
  3921. : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
  3922. const Expr *getSubExpr() const { return cast<Expr>(Val); }
  3923. Expr *getSubExpr() { return cast<Expr>(Val); }
  3924. void setSubExpr(Expr *E) { Val = E; }
  3925. /// Returns whether this is really a Win64 ABI va_arg expression.
  3926. bool isMicrosoftABI() const { return TInfo.getInt(); }
  3927. void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
  3928. TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
  3929. void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
  3930. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  3931. void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
  3932. SourceLocation getRParenLoc() const { return RParenLoc; }
  3933. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3934. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  3935. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  3936. static bool classof(const Stmt *T) {
  3937. return T->getStmtClass() == VAArgExprClass;
  3938. }
  3939. // Iterators
  3940. child_range children() { return child_range(&Val, &Val+1); }
  3941. const_child_range children() const {
  3942. return const_child_range(&Val, &Val + 1);
  3943. }
  3944. };
  3945. /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
  3946. /// __builtin_FUNCTION(), or __builtin_FILE().
  3947. class SourceLocExpr final : public Expr {
  3948. SourceLocation BuiltinLoc, RParenLoc;
  3949. DeclContext *ParentContext;
  3950. public:
  3951. enum IdentKind { Function, File, Line, Column };
  3952. SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc,
  3953. SourceLocation RParenLoc, DeclContext *Context);
  3954. /// Build an empty call expression.
  3955. explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
  3956. /// Return the result of evaluating this SourceLocExpr in the specified
  3957. /// (and possibly null) default argument or initialization context.
  3958. APValue EvaluateInContext(const ASTContext &Ctx,
  3959. const Expr *DefaultExpr) const;
  3960. /// Return a string representing the name of the specific builtin function.
  3961. StringRef getBuiltinStr() const;
  3962. IdentKind getIdentKind() const {
  3963. return static_cast<IdentKind>(SourceLocExprBits.Kind);
  3964. }
  3965. bool isStringType() const {
  3966. switch (getIdentKind()) {
  3967. case File:
  3968. case Function:
  3969. return true;
  3970. case Line:
  3971. case Column:
  3972. return false;
  3973. }
  3974. llvm_unreachable("unknown source location expression kind");
  3975. }
  3976. bool isIntType() const LLVM_READONLY { return !isStringType(); }
  3977. /// If the SourceLocExpr has been resolved return the subexpression
  3978. /// representing the resolved value. Otherwise return null.
  3979. const DeclContext *getParentContext() const { return ParentContext; }
  3980. DeclContext *getParentContext() { return ParentContext; }
  3981. SourceLocation getLocation() const { return BuiltinLoc; }
  3982. SourceLocation getBeginLoc() const { return BuiltinLoc; }
  3983. SourceLocation getEndLoc() const { return RParenLoc; }
  3984. child_range children() {
  3985. return child_range(child_iterator(), child_iterator());
  3986. }
  3987. const_child_range children() const {
  3988. return const_child_range(child_iterator(), child_iterator());
  3989. }
  3990. static bool classof(const Stmt *T) {
  3991. return T->getStmtClass() == SourceLocExprClass;
  3992. }
  3993. private:
  3994. friend class ASTStmtReader;
  3995. };
  3996. /// Describes an C or C++ initializer list.
  3997. ///
  3998. /// InitListExpr describes an initializer list, which can be used to
  3999. /// initialize objects of different types, including
  4000. /// struct/class/union types, arrays, and vectors. For example:
  4001. ///
  4002. /// @code
  4003. /// struct foo x = { 1, { 2, 3 } };
  4004. /// @endcode
  4005. ///
  4006. /// Prior to semantic analysis, an initializer list will represent the
  4007. /// initializer list as written by the user, but will have the
  4008. /// placeholder type "void". This initializer list is called the
  4009. /// syntactic form of the initializer, and may contain C99 designated
  4010. /// initializers (represented as DesignatedInitExprs), initializations
  4011. /// of subobject members without explicit braces, and so on. Clients
  4012. /// interested in the original syntax of the initializer list should
  4013. /// use the syntactic form of the initializer list.
  4014. ///
  4015. /// After semantic analysis, the initializer list will represent the
  4016. /// semantic form of the initializer, where the initializations of all
  4017. /// subobjects are made explicit with nested InitListExpr nodes and
  4018. /// C99 designators have been eliminated by placing the designated
  4019. /// initializations into the subobject they initialize. Additionally,
  4020. /// any "holes" in the initialization, where no initializer has been
  4021. /// specified for a particular subobject, will be replaced with
  4022. /// implicitly-generated ImplicitValueInitExpr expressions that
  4023. /// value-initialize the subobjects. Note, however, that the
  4024. /// initializer lists may still have fewer initializers than there are
  4025. /// elements to initialize within the object.
  4026. ///
  4027. /// After semantic analysis has completed, given an initializer list,
  4028. /// method isSemanticForm() returns true if and only if this is the
  4029. /// semantic form of the initializer list (note: the same AST node
  4030. /// may at the same time be the syntactic form).
  4031. /// Given the semantic form of the initializer list, one can retrieve
  4032. /// the syntactic form of that initializer list (when different)
  4033. /// using method getSyntacticForm(); the method returns null if applied
  4034. /// to a initializer list which is already in syntactic form.
  4035. /// Similarly, given the syntactic form (i.e., an initializer list such
  4036. /// that isSemanticForm() returns false), one can retrieve the semantic
  4037. /// form using method getSemanticForm().
  4038. /// Since many initializer lists have the same syntactic and semantic forms,
  4039. /// getSyntacticForm() may return NULL, indicating that the current
  4040. /// semantic initializer list also serves as its syntactic form.
  4041. class InitListExpr : public Expr {
  4042. // FIXME: Eliminate this vector in favor of ASTContext allocation
  4043. typedef ASTVector<Stmt *> InitExprsTy;
  4044. InitExprsTy InitExprs;
  4045. SourceLocation LBraceLoc, RBraceLoc;
  4046. /// The alternative form of the initializer list (if it exists).
  4047. /// The int part of the pair stores whether this initializer list is
  4048. /// in semantic form. If not null, the pointer points to:
  4049. /// - the syntactic form, if this is in semantic form;
  4050. /// - the semantic form, if this is in syntactic form.
  4051. llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
  4052. /// Either:
  4053. /// If this initializer list initializes an array with more elements than
  4054. /// there are initializers in the list, specifies an expression to be used
  4055. /// for value initialization of the rest of the elements.
  4056. /// Or
  4057. /// If this initializer list initializes a union, specifies which
  4058. /// field within the union will be initialized.
  4059. llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
  4060. public:
  4061. InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
  4062. ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
  4063. /// Build an empty initializer list.
  4064. explicit InitListExpr(EmptyShell Empty)
  4065. : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
  4066. unsigned getNumInits() const { return InitExprs.size(); }
  4067. /// Retrieve the set of initializers.
  4068. Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
  4069. /// Retrieve the set of initializers.
  4070. Expr * const *getInits() const {
  4071. return reinterpret_cast<Expr * const *>(InitExprs.data());
  4072. }
  4073. ArrayRef<Expr *> inits() {
  4074. return llvm::makeArrayRef(getInits(), getNumInits());
  4075. }
  4076. ArrayRef<Expr *> inits() const {
  4077. return llvm::makeArrayRef(getInits(), getNumInits());
  4078. }
  4079. const Expr *getInit(unsigned Init) const {
  4080. assert(Init < getNumInits() && "Initializer access out of range!");
  4081. return cast_or_null<Expr>(InitExprs[Init]);
  4082. }
  4083. Expr *getInit(unsigned Init) {
  4084. assert(Init < getNumInits() && "Initializer access out of range!");
  4085. return cast_or_null<Expr>(InitExprs[Init]);
  4086. }
  4087. void setInit(unsigned Init, Expr *expr) {
  4088. assert(Init < getNumInits() && "Initializer access out of range!");
  4089. InitExprs[Init] = expr;
  4090. if (expr)
  4091. setDependence(getDependence() | expr->getDependence());
  4092. }
  4093. /// Mark the semantic form of the InitListExpr as error when the semantic
  4094. /// analysis fails.
  4095. void markError() {
  4096. assert(isSemanticForm());
  4097. setDependence(getDependence() | ExprDependence::ErrorDependent);
  4098. }
  4099. /// Reserve space for some number of initializers.
  4100. void reserveInits(const ASTContext &C, unsigned NumInits);
  4101. /// Specify the number of initializers
  4102. ///
  4103. /// If there are more than @p NumInits initializers, the remaining
  4104. /// initializers will be destroyed. If there are fewer than @p
  4105. /// NumInits initializers, NULL expressions will be added for the
  4106. /// unknown initializers.
  4107. void resizeInits(const ASTContext &Context, unsigned NumInits);
  4108. /// Updates the initializer at index @p Init with the new
  4109. /// expression @p expr, and returns the old expression at that
  4110. /// location.
  4111. ///
  4112. /// When @p Init is out of range for this initializer list, the
  4113. /// initializer list will be extended with NULL expressions to
  4114. /// accommodate the new entry.
  4115. Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
  4116. /// If this initializer list initializes an array with more elements
  4117. /// than there are initializers in the list, specifies an expression to be
  4118. /// used for value initialization of the rest of the elements.
  4119. Expr *getArrayFiller() {
  4120. return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
  4121. }
  4122. const Expr *getArrayFiller() const {
  4123. return const_cast<InitListExpr *>(this)->getArrayFiller();
  4124. }
  4125. void setArrayFiller(Expr *filler);
  4126. /// Return true if this is an array initializer and its array "filler"
  4127. /// has been set.
  4128. bool hasArrayFiller() const { return getArrayFiller(); }
  4129. /// If this initializes a union, specifies which field in the
  4130. /// union to initialize.
  4131. ///
  4132. /// Typically, this field is the first named field within the
  4133. /// union. However, a designated initializer can specify the
  4134. /// initialization of a different field within the union.
  4135. FieldDecl *getInitializedFieldInUnion() {
  4136. return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
  4137. }
  4138. const FieldDecl *getInitializedFieldInUnion() const {
  4139. return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
  4140. }
  4141. void setInitializedFieldInUnion(FieldDecl *FD) {
  4142. assert((FD == nullptr
  4143. || getInitializedFieldInUnion() == nullptr
  4144. || getInitializedFieldInUnion() == FD)
  4145. && "Only one field of a union may be initialized at a time!");
  4146. ArrayFillerOrUnionFieldInit = FD;
  4147. }
  4148. // Explicit InitListExpr's originate from source code (and have valid source
  4149. // locations). Implicit InitListExpr's are created by the semantic analyzer.
  4150. // FIXME: This is wrong; InitListExprs created by semantic analysis have
  4151. // valid source locations too!
  4152. bool isExplicit() const {
  4153. return LBraceLoc.isValid() && RBraceLoc.isValid();
  4154. }
  4155. // Is this an initializer for an array of characters, initialized by a string
  4156. // literal or an @encode?
  4157. bool isStringLiteralInit() const;
  4158. /// Is this a transparent initializer list (that is, an InitListExpr that is
  4159. /// purely syntactic, and whose semantics are that of the sole contained
  4160. /// initializer)?
  4161. bool isTransparent() const;
  4162. /// Is this the zero initializer {0} in a language which considers it
  4163. /// idiomatic?
  4164. bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
  4165. SourceLocation getLBraceLoc() const { return LBraceLoc; }
  4166. void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
  4167. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  4168. void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
  4169. bool isSemanticForm() const { return AltForm.getInt(); }
  4170. InitListExpr *getSemanticForm() const {
  4171. return isSemanticForm() ? nullptr : AltForm.getPointer();
  4172. }
  4173. bool isSyntacticForm() const {
  4174. return !AltForm.getInt() || !AltForm.getPointer();
  4175. }
  4176. InitListExpr *getSyntacticForm() const {
  4177. return isSemanticForm() ? AltForm.getPointer() : nullptr;
  4178. }
  4179. void setSyntacticForm(InitListExpr *Init) {
  4180. AltForm.setPointer(Init);
  4181. AltForm.setInt(true);
  4182. Init->AltForm.setPointer(this);
  4183. Init->AltForm.setInt(false);
  4184. }
  4185. bool hadArrayRangeDesignator() const {
  4186. return InitListExprBits.HadArrayRangeDesignator != 0;
  4187. }
  4188. void sawArrayRangeDesignator(bool ARD = true) {
  4189. InitListExprBits.HadArrayRangeDesignator = ARD;
  4190. }
  4191. SourceLocation getBeginLoc() const LLVM_READONLY;
  4192. SourceLocation getEndLoc() const LLVM_READONLY;
  4193. static bool classof(const Stmt *T) {
  4194. return T->getStmtClass() == InitListExprClass;
  4195. }
  4196. // Iterators
  4197. child_range children() {
  4198. const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
  4199. return child_range(cast_away_const(CCR.begin()),
  4200. cast_away_const(CCR.end()));
  4201. }
  4202. const_child_range children() const {
  4203. // FIXME: This does not include the array filler expression.
  4204. if (InitExprs.empty())
  4205. return const_child_range(const_child_iterator(), const_child_iterator());
  4206. return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
  4207. }
  4208. typedef InitExprsTy::iterator iterator;
  4209. typedef InitExprsTy::const_iterator const_iterator;
  4210. typedef InitExprsTy::reverse_iterator reverse_iterator;
  4211. typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
  4212. iterator begin() { return InitExprs.begin(); }
  4213. const_iterator begin() const { return InitExprs.begin(); }
  4214. iterator end() { return InitExprs.end(); }
  4215. const_iterator end() const { return InitExprs.end(); }
  4216. reverse_iterator rbegin() { return InitExprs.rbegin(); }
  4217. const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
  4218. reverse_iterator rend() { return InitExprs.rend(); }
  4219. const_reverse_iterator rend() const { return InitExprs.rend(); }
  4220. friend class ASTStmtReader;
  4221. friend class ASTStmtWriter;
  4222. };
  4223. /// Represents a C99 designated initializer expression.
  4224. ///
  4225. /// A designated initializer expression (C99 6.7.8) contains one or
  4226. /// more designators (which can be field designators, array
  4227. /// designators, or GNU array-range designators) followed by an
  4228. /// expression that initializes the field or element(s) that the
  4229. /// designators refer to. For example, given:
  4230. ///
  4231. /// @code
  4232. /// struct point {
  4233. /// double x;
  4234. /// double y;
  4235. /// };
  4236. /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
  4237. /// @endcode
  4238. ///
  4239. /// The InitListExpr contains three DesignatedInitExprs, the first of
  4240. /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
  4241. /// designators, one array designator for @c [2] followed by one field
  4242. /// designator for @c .y. The initialization expression will be 1.0.
  4243. class DesignatedInitExpr final
  4244. : public Expr,
  4245. private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
  4246. public:
  4247. /// Forward declaration of the Designator class.
  4248. class Designator;
  4249. private:
  4250. /// The location of the '=' or ':' prior to the actual initializer
  4251. /// expression.
  4252. SourceLocation EqualOrColonLoc;
  4253. /// Whether this designated initializer used the GNU deprecated
  4254. /// syntax rather than the C99 '=' syntax.
  4255. unsigned GNUSyntax : 1;
  4256. /// The number of designators in this initializer expression.
  4257. unsigned NumDesignators : 15;
  4258. /// The number of subexpressions of this initializer expression,
  4259. /// which contains both the initializer and any additional
  4260. /// expressions used by array and array-range designators.
  4261. unsigned NumSubExprs : 16;
  4262. /// The designators in this designated initialization
  4263. /// expression.
  4264. Designator *Designators;
  4265. DesignatedInitExpr(const ASTContext &C, QualType Ty,
  4266. llvm::ArrayRef<Designator> Designators,
  4267. SourceLocation EqualOrColonLoc, bool GNUSyntax,
  4268. ArrayRef<Expr *> IndexExprs, Expr *Init);
  4269. explicit DesignatedInitExpr(unsigned NumSubExprs)
  4270. : Expr(DesignatedInitExprClass, EmptyShell()),
  4271. NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
  4272. public:
  4273. /// A field designator, e.g., ".x".
  4274. struct FieldDesignator {
  4275. /// Refers to the field that is being initialized. The low bit
  4276. /// of this field determines whether this is actually a pointer
  4277. /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
  4278. /// initially constructed, a field designator will store an
  4279. /// IdentifierInfo*. After semantic analysis has resolved that
  4280. /// name, the field designator will instead store a FieldDecl*.
  4281. uintptr_t NameOrField;
  4282. /// The location of the '.' in the designated initializer.
  4283. SourceLocation DotLoc;
  4284. /// The location of the field name in the designated initializer.
  4285. SourceLocation FieldLoc;
  4286. };
  4287. /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
  4288. struct ArrayOrRangeDesignator {
  4289. /// Location of the first index expression within the designated
  4290. /// initializer expression's list of subexpressions.
  4291. unsigned Index;
  4292. /// The location of the '[' starting the array range designator.
  4293. SourceLocation LBracketLoc;
  4294. /// The location of the ellipsis separating the start and end
  4295. /// indices. Only valid for GNU array-range designators.
  4296. SourceLocation EllipsisLoc;
  4297. /// The location of the ']' terminating the array range designator.
  4298. SourceLocation RBracketLoc;
  4299. };
  4300. /// Represents a single C99 designator.
  4301. ///
  4302. /// @todo This class is infuriatingly similar to clang::Designator,
  4303. /// but minor differences (storing indices vs. storing pointers)
  4304. /// keep us from reusing it. Try harder, later, to rectify these
  4305. /// differences.
  4306. class Designator {
  4307. /// The kind of designator this describes.
  4308. enum {
  4309. FieldDesignator,
  4310. ArrayDesignator,
  4311. ArrayRangeDesignator
  4312. } Kind;
  4313. union {
  4314. /// A field designator, e.g., ".x".
  4315. struct FieldDesignator Field;
  4316. /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
  4317. struct ArrayOrRangeDesignator ArrayOrRange;
  4318. };
  4319. friend class DesignatedInitExpr;
  4320. public:
  4321. Designator() {}
  4322. /// Initializes a field designator.
  4323. Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
  4324. SourceLocation FieldLoc)
  4325. : Kind(FieldDesignator) {
  4326. new (&Field) DesignatedInitExpr::FieldDesignator;
  4327. Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
  4328. Field.DotLoc = DotLoc;
  4329. Field.FieldLoc = FieldLoc;
  4330. }
  4331. /// Initializes an array designator.
  4332. Designator(unsigned Index, SourceLocation LBracketLoc,
  4333. SourceLocation RBracketLoc)
  4334. : Kind(ArrayDesignator) {
  4335. new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
  4336. ArrayOrRange.Index = Index;
  4337. ArrayOrRange.LBracketLoc = LBracketLoc;
  4338. ArrayOrRange.EllipsisLoc = SourceLocation();
  4339. ArrayOrRange.RBracketLoc = RBracketLoc;
  4340. }
  4341. /// Initializes a GNU array-range designator.
  4342. Designator(unsigned Index, SourceLocation LBracketLoc,
  4343. SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
  4344. : Kind(ArrayRangeDesignator) {
  4345. new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
  4346. ArrayOrRange.Index = Index;
  4347. ArrayOrRange.LBracketLoc = LBracketLoc;
  4348. ArrayOrRange.EllipsisLoc = EllipsisLoc;
  4349. ArrayOrRange.RBracketLoc = RBracketLoc;
  4350. }
  4351. bool isFieldDesignator() const { return Kind == FieldDesignator; }
  4352. bool isArrayDesignator() const { return Kind == ArrayDesignator; }
  4353. bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
  4354. IdentifierInfo *getFieldName() const;
  4355. FieldDecl *getField() const {
  4356. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4357. if (Field.NameOrField & 0x01)
  4358. return nullptr;
  4359. else
  4360. return reinterpret_cast<FieldDecl *>(Field.NameOrField);
  4361. }
  4362. void setField(FieldDecl *FD) {
  4363. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4364. Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
  4365. }
  4366. SourceLocation getDotLoc() const {
  4367. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4368. return Field.DotLoc;
  4369. }
  4370. SourceLocation getFieldLoc() const {
  4371. assert(Kind == FieldDesignator && "Only valid on a field designator");
  4372. return Field.FieldLoc;
  4373. }
  4374. SourceLocation getLBracketLoc() const {
  4375. assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
  4376. "Only valid on an array or array-range designator");
  4377. return ArrayOrRange.LBracketLoc;
  4378. }
  4379. SourceLocation getRBracketLoc() const {
  4380. assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
  4381. "Only valid on an array or array-range designator");
  4382. return ArrayOrRange.RBracketLoc;
  4383. }
  4384. SourceLocation getEllipsisLoc() const {
  4385. assert(Kind == ArrayRangeDesignator &&
  4386. "Only valid on an array-range designator");
  4387. return ArrayOrRange.EllipsisLoc;
  4388. }
  4389. unsigned getFirstExprIndex() const {
  4390. assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
  4391. "Only valid on an array or array-range designator");
  4392. return ArrayOrRange.Index;
  4393. }
  4394. SourceLocation getBeginLoc() const LLVM_READONLY {
  4395. if (Kind == FieldDesignator)
  4396. return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
  4397. else
  4398. return getLBracketLoc();
  4399. }
  4400. SourceLocation getEndLoc() const LLVM_READONLY {
  4401. return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
  4402. }
  4403. SourceRange getSourceRange() const LLVM_READONLY {
  4404. return SourceRange(getBeginLoc(), getEndLoc());
  4405. }
  4406. };
  4407. static DesignatedInitExpr *Create(const ASTContext &C,
  4408. llvm::ArrayRef<Designator> Designators,
  4409. ArrayRef<Expr*> IndexExprs,
  4410. SourceLocation EqualOrColonLoc,
  4411. bool GNUSyntax, Expr *Init);
  4412. static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
  4413. unsigned NumIndexExprs);
  4414. /// Returns the number of designators in this initializer.
  4415. unsigned size() const { return NumDesignators; }
  4416. // Iterator access to the designators.
  4417. llvm::MutableArrayRef<Designator> designators() {
  4418. return {Designators, NumDesignators};
  4419. }
  4420. llvm::ArrayRef<Designator> designators() const {
  4421. return {Designators, NumDesignators};
  4422. }
  4423. Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
  4424. const Designator *getDesignator(unsigned Idx) const {
  4425. return &designators()[Idx];
  4426. }
  4427. void setDesignators(const ASTContext &C, const Designator *Desigs,
  4428. unsigned NumDesigs);
  4429. Expr *getArrayIndex(const Designator &D) const;
  4430. Expr *getArrayRangeStart(const Designator &D) const;
  4431. Expr *getArrayRangeEnd(const Designator &D) const;
  4432. /// Retrieve the location of the '=' that precedes the
  4433. /// initializer value itself, if present.
  4434. SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
  4435. void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
  4436. /// Whether this designated initializer should result in direct-initialization
  4437. /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
  4438. bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
  4439. /// Determines whether this designated initializer used the
  4440. /// deprecated GNU syntax for designated initializers.
  4441. bool usesGNUSyntax() const { return GNUSyntax; }
  4442. void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
  4443. /// Retrieve the initializer value.
  4444. Expr *getInit() const {
  4445. return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
  4446. }
  4447. void setInit(Expr *init) {
  4448. *child_begin() = init;
  4449. }
  4450. /// Retrieve the total number of subexpressions in this
  4451. /// designated initializer expression, including the actual
  4452. /// initialized value and any expressions that occur within array
  4453. /// and array-range designators.
  4454. unsigned getNumSubExprs() const { return NumSubExprs; }
  4455. Expr *getSubExpr(unsigned Idx) const {
  4456. assert(Idx < NumSubExprs && "Subscript out of range");
  4457. return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
  4458. }
  4459. void setSubExpr(unsigned Idx, Expr *E) {
  4460. assert(Idx < NumSubExprs && "Subscript out of range");
  4461. getTrailingObjects<Stmt *>()[Idx] = E;
  4462. }
  4463. /// Replaces the designator at index @p Idx with the series
  4464. /// of designators in [First, Last).
  4465. void ExpandDesignator(const ASTContext &C, unsigned Idx,
  4466. const Designator *First, const Designator *Last);
  4467. SourceRange getDesignatorsSourceRange() const;
  4468. SourceLocation getBeginLoc() const LLVM_READONLY;
  4469. SourceLocation getEndLoc() const LLVM_READONLY;
  4470. static bool classof(const Stmt *T) {
  4471. return T->getStmtClass() == DesignatedInitExprClass;
  4472. }
  4473. // Iterators
  4474. child_range children() {
  4475. Stmt **begin = getTrailingObjects<Stmt *>();
  4476. return child_range(begin, begin + NumSubExprs);
  4477. }
  4478. const_child_range children() const {
  4479. Stmt * const *begin = getTrailingObjects<Stmt *>();
  4480. return const_child_range(begin, begin + NumSubExprs);
  4481. }
  4482. friend TrailingObjects;
  4483. };
  4484. /// Represents a place-holder for an object not to be initialized by
  4485. /// anything.
  4486. ///
  4487. /// This only makes sense when it appears as part of an updater of a
  4488. /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
  4489. /// initializes a big object, and the NoInitExpr's mark the spots within the
  4490. /// big object not to be overwritten by the updater.
  4491. ///
  4492. /// \see DesignatedInitUpdateExpr
  4493. class NoInitExpr : public Expr {
  4494. public:
  4495. explicit NoInitExpr(QualType ty)
  4496. : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
  4497. setDependence(computeDependence(this));
  4498. }
  4499. explicit NoInitExpr(EmptyShell Empty)
  4500. : Expr(NoInitExprClass, Empty) { }
  4501. static bool classof(const Stmt *T) {
  4502. return T->getStmtClass() == NoInitExprClass;
  4503. }
  4504. SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
  4505. SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
  4506. // Iterators
  4507. child_range children() {
  4508. return child_range(child_iterator(), child_iterator());
  4509. }
  4510. const_child_range children() const {
  4511. return const_child_range(const_child_iterator(), const_child_iterator());
  4512. }
  4513. };
  4514. // In cases like:
  4515. // struct Q { int a, b, c; };
  4516. // Q *getQ();
  4517. // void foo() {
  4518. // struct A { Q q; } a = { *getQ(), .q.b = 3 };
  4519. // }
  4520. //
  4521. // We will have an InitListExpr for a, with type A, and then a
  4522. // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
  4523. // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
  4524. //
  4525. class DesignatedInitUpdateExpr : public Expr {
  4526. // BaseAndUpdaterExprs[0] is the base expression;
  4527. // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
  4528. Stmt *BaseAndUpdaterExprs[2];
  4529. public:
  4530. DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
  4531. Expr *baseExprs, SourceLocation rBraceLoc);
  4532. explicit DesignatedInitUpdateExpr(EmptyShell Empty)
  4533. : Expr(DesignatedInitUpdateExprClass, Empty) { }
  4534. SourceLocation getBeginLoc() const LLVM_READONLY;
  4535. SourceLocation getEndLoc() const LLVM_READONLY;
  4536. static bool classof(const Stmt *T) {
  4537. return T->getStmtClass() == DesignatedInitUpdateExprClass;
  4538. }
  4539. Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
  4540. void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
  4541. InitListExpr *getUpdater() const {
  4542. return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
  4543. }
  4544. void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
  4545. // Iterators
  4546. // children = the base and the updater
  4547. child_range children() {
  4548. return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
  4549. }
  4550. const_child_range children() const {
  4551. return const_child_range(&BaseAndUpdaterExprs[0],
  4552. &BaseAndUpdaterExprs[0] + 2);
  4553. }
  4554. };
  4555. /// Represents a loop initializing the elements of an array.
  4556. ///
  4557. /// The need to initialize the elements of an array occurs in a number of
  4558. /// contexts:
  4559. ///
  4560. /// * in the implicit copy/move constructor for a class with an array member
  4561. /// * when a lambda-expression captures an array by value
  4562. /// * when a decomposition declaration decomposes an array
  4563. ///
  4564. /// There are two subexpressions: a common expression (the source array)
  4565. /// that is evaluated once up-front, and a per-element initializer that
  4566. /// runs once for each array element.
  4567. ///
  4568. /// Within the per-element initializer, the common expression may be referenced
  4569. /// via an OpaqueValueExpr, and the current index may be obtained via an
  4570. /// ArrayInitIndexExpr.
  4571. class ArrayInitLoopExpr : public Expr {
  4572. Stmt *SubExprs[2];
  4573. explicit ArrayInitLoopExpr(EmptyShell Empty)
  4574. : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
  4575. public:
  4576. explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
  4577. : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
  4578. SubExprs{CommonInit, ElementInit} {
  4579. setDependence(computeDependence(this));
  4580. }
  4581. /// Get the common subexpression shared by all initializations (the source
  4582. /// array).
  4583. OpaqueValueExpr *getCommonExpr() const {
  4584. return cast<OpaqueValueExpr>(SubExprs[0]);
  4585. }
  4586. /// Get the initializer to use for each array element.
  4587. Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
  4588. llvm::APInt getArraySize() const {
  4589. return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
  4590. ->getSize();
  4591. }
  4592. static bool classof(const Stmt *S) {
  4593. return S->getStmtClass() == ArrayInitLoopExprClass;
  4594. }
  4595. SourceLocation getBeginLoc() const LLVM_READONLY {
  4596. return getCommonExpr()->getBeginLoc();
  4597. }
  4598. SourceLocation getEndLoc() const LLVM_READONLY {
  4599. return getCommonExpr()->getEndLoc();
  4600. }
  4601. child_range children() {
  4602. return child_range(SubExprs, SubExprs + 2);
  4603. }
  4604. const_child_range children() const {
  4605. return const_child_range(SubExprs, SubExprs + 2);
  4606. }
  4607. friend class ASTReader;
  4608. friend class ASTStmtReader;
  4609. friend class ASTStmtWriter;
  4610. };
  4611. /// Represents the index of the current element of an array being
  4612. /// initialized by an ArrayInitLoopExpr. This can only appear within the
  4613. /// subexpression of an ArrayInitLoopExpr.
  4614. class ArrayInitIndexExpr : public Expr {
  4615. explicit ArrayInitIndexExpr(EmptyShell Empty)
  4616. : Expr(ArrayInitIndexExprClass, Empty) {}
  4617. public:
  4618. explicit ArrayInitIndexExpr(QualType T)
  4619. : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
  4620. setDependence(ExprDependence::None);
  4621. }
  4622. static bool classof(const Stmt *S) {
  4623. return S->getStmtClass() == ArrayInitIndexExprClass;
  4624. }
  4625. SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
  4626. SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
  4627. child_range children() {
  4628. return child_range(child_iterator(), child_iterator());
  4629. }
  4630. const_child_range children() const {
  4631. return const_child_range(const_child_iterator(), const_child_iterator());
  4632. }
  4633. friend class ASTReader;
  4634. friend class ASTStmtReader;
  4635. };
  4636. /// Represents an implicitly-generated value initialization of
  4637. /// an object of a given type.
  4638. ///
  4639. /// Implicit value initializations occur within semantic initializer
  4640. /// list expressions (InitListExpr) as placeholders for subobject
  4641. /// initializations not explicitly specified by the user.
  4642. ///
  4643. /// \see InitListExpr
  4644. class ImplicitValueInitExpr : public Expr {
  4645. public:
  4646. explicit ImplicitValueInitExpr(QualType ty)
  4647. : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
  4648. setDependence(computeDependence(this));
  4649. }
  4650. /// Construct an empty implicit value initialization.
  4651. explicit ImplicitValueInitExpr(EmptyShell Empty)
  4652. : Expr(ImplicitValueInitExprClass, Empty) { }
  4653. static bool classof(const Stmt *T) {
  4654. return T->getStmtClass() == ImplicitValueInitExprClass;
  4655. }
  4656. SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
  4657. SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
  4658. // Iterators
  4659. child_range children() {
  4660. return child_range(child_iterator(), child_iterator());
  4661. }
  4662. const_child_range children() const {
  4663. return const_child_range(const_child_iterator(), const_child_iterator());
  4664. }
  4665. };
  4666. class ParenListExpr final
  4667. : public Expr,
  4668. private llvm::TrailingObjects<ParenListExpr, Stmt *> {
  4669. friend class ASTStmtReader;
  4670. friend TrailingObjects;
  4671. /// The location of the left and right parentheses.
  4672. SourceLocation LParenLoc, RParenLoc;
  4673. /// Build a paren list.
  4674. ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
  4675. SourceLocation RParenLoc);
  4676. /// Build an empty paren list.
  4677. ParenListExpr(EmptyShell Empty, unsigned NumExprs);
  4678. public:
  4679. /// Create a paren list.
  4680. static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
  4681. ArrayRef<Expr *> Exprs,
  4682. SourceLocation RParenLoc);
  4683. /// Create an empty paren list.
  4684. static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
  4685. /// Return the number of expressions in this paren list.
  4686. unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
  4687. Expr *getExpr(unsigned Init) {
  4688. assert(Init < getNumExprs() && "Initializer access out of range!");
  4689. return getExprs()[Init];
  4690. }
  4691. const Expr *getExpr(unsigned Init) const {
  4692. return const_cast<ParenListExpr *>(this)->getExpr(Init);
  4693. }
  4694. Expr **getExprs() {
  4695. return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
  4696. }
  4697. ArrayRef<Expr *> exprs() {
  4698. return llvm::makeArrayRef(getExprs(), getNumExprs());
  4699. }
  4700. SourceLocation getLParenLoc() const { return LParenLoc; }
  4701. SourceLocation getRParenLoc() const { return RParenLoc; }
  4702. SourceLocation getBeginLoc() const { return getLParenLoc(); }
  4703. SourceLocation getEndLoc() const { return getRParenLoc(); }
  4704. static bool classof(const Stmt *T) {
  4705. return T->getStmtClass() == ParenListExprClass;
  4706. }
  4707. // Iterators
  4708. child_range children() {
  4709. return child_range(getTrailingObjects<Stmt *>(),
  4710. getTrailingObjects<Stmt *>() + getNumExprs());
  4711. }
  4712. const_child_range children() const {
  4713. return const_child_range(getTrailingObjects<Stmt *>(),
  4714. getTrailingObjects<Stmt *>() + getNumExprs());
  4715. }
  4716. };
  4717. /// Represents a C11 generic selection.
  4718. ///
  4719. /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
  4720. /// expression, followed by one or more generic associations. Each generic
  4721. /// association specifies a type name and an expression, or "default" and an
  4722. /// expression (in which case it is known as a default generic association).
  4723. /// The type and value of the generic selection are identical to those of its
  4724. /// result expression, which is defined as the expression in the generic
  4725. /// association with a type name that is compatible with the type of the
  4726. /// controlling expression, or the expression in the default generic association
  4727. /// if no types are compatible. For example:
  4728. ///
  4729. /// @code
  4730. /// _Generic(X, double: 1, float: 2, default: 3)
  4731. /// @endcode
  4732. ///
  4733. /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
  4734. /// or 3 if "hello".
  4735. ///
  4736. /// As an extension, generic selections are allowed in C++, where the following
  4737. /// additional semantics apply:
  4738. ///
  4739. /// Any generic selection whose controlling expression is type-dependent or
  4740. /// which names a dependent type in its association list is result-dependent,
  4741. /// which means that the choice of result expression is dependent.
  4742. /// Result-dependent generic associations are both type- and value-dependent.
  4743. class GenericSelectionExpr final
  4744. : public Expr,
  4745. private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
  4746. TypeSourceInfo *> {
  4747. friend class ASTStmtReader;
  4748. friend class ASTStmtWriter;
  4749. friend TrailingObjects;
  4750. /// The number of association expressions and the index of the result
  4751. /// expression in the case where the generic selection expression is not
  4752. /// result-dependent. The result index is equal to ResultDependentIndex
  4753. /// if and only if the generic selection expression is result-dependent.
  4754. unsigned NumAssocs, ResultIndex;
  4755. enum : unsigned {
  4756. ResultDependentIndex = std::numeric_limits<unsigned>::max(),
  4757. ControllingIndex = 0,
  4758. AssocExprStartIndex = 1
  4759. };
  4760. /// The location of the "default" and of the right parenthesis.
  4761. SourceLocation DefaultLoc, RParenLoc;
  4762. // GenericSelectionExpr is followed by several trailing objects.
  4763. // They are (in order):
  4764. //
  4765. // * A single Stmt * for the controlling expression.
  4766. // * An array of getNumAssocs() Stmt * for the association expressions.
  4767. // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
  4768. // association expressions.
  4769. unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
  4770. // Add one to account for the controlling expression; the remainder
  4771. // are the associated expressions.
  4772. return 1 + getNumAssocs();
  4773. }
  4774. unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
  4775. return getNumAssocs();
  4776. }
  4777. template <bool Const> class AssociationIteratorTy;
  4778. /// Bundle together an association expression and its TypeSourceInfo.
  4779. /// The Const template parameter is for the const and non-const versions
  4780. /// of AssociationTy.
  4781. template <bool Const> class AssociationTy {
  4782. friend class GenericSelectionExpr;
  4783. template <bool OtherConst> friend class AssociationIteratorTy;
  4784. using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
  4785. using TSIPtrTy =
  4786. std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
  4787. ExprPtrTy E;
  4788. TSIPtrTy TSI;
  4789. bool Selected;
  4790. AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
  4791. : E(E), TSI(TSI), Selected(Selected) {}
  4792. public:
  4793. ExprPtrTy getAssociationExpr() const { return E; }
  4794. TSIPtrTy getTypeSourceInfo() const { return TSI; }
  4795. QualType getType() const { return TSI ? TSI->getType() : QualType(); }
  4796. bool isSelected() const { return Selected; }
  4797. AssociationTy *operator->() { return this; }
  4798. const AssociationTy *operator->() const { return this; }
  4799. }; // class AssociationTy
  4800. /// Iterator over const and non-const Association objects. The Association
  4801. /// objects are created on the fly when the iterator is dereferenced.
  4802. /// This abstract over how exactly the association expressions and the
  4803. /// corresponding TypeSourceInfo * are stored.
  4804. template <bool Const>
  4805. class AssociationIteratorTy
  4806. : public llvm::iterator_facade_base<
  4807. AssociationIteratorTy<Const>, std::input_iterator_tag,
  4808. AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
  4809. AssociationTy<Const>> {
  4810. friend class GenericSelectionExpr;
  4811. // FIXME: This iterator could conceptually be a random access iterator, and
  4812. // it would be nice if we could strengthen the iterator category someday.
  4813. // However this iterator does not satisfy two requirements of forward
  4814. // iterators:
  4815. // a) reference = T& or reference = const T&
  4816. // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
  4817. // if *It1 and *It2 are bound to the same objects.
  4818. // An alternative design approach was discussed during review;
  4819. // store an Association object inside the iterator, and return a reference
  4820. // to it when dereferenced. This idea was discarded beacuse of nasty
  4821. // lifetime issues:
  4822. // AssociationIterator It = ...;
  4823. // const Association &Assoc = *It++; // Oops, Assoc is dangling.
  4824. using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
  4825. using StmtPtrPtrTy =
  4826. std::conditional_t<Const, const Stmt *const *, Stmt **>;
  4827. using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
  4828. TypeSourceInfo **>;
  4829. StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
  4830. TSIPtrPtrTy TSI; // Kept in sync with E.
  4831. unsigned Offset = 0, SelectedOffset = 0;
  4832. AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
  4833. unsigned SelectedOffset)
  4834. : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
  4835. public:
  4836. AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
  4837. typename BaseTy::reference operator*() const {
  4838. return AssociationTy<Const>(cast<Expr>(*E), *TSI,
  4839. Offset == SelectedOffset);
  4840. }
  4841. typename BaseTy::pointer operator->() const { return **this; }
  4842. using BaseTy::operator++;
  4843. AssociationIteratorTy &operator++() {
  4844. ++E;
  4845. ++TSI;
  4846. ++Offset;
  4847. return *this;
  4848. }
  4849. bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
  4850. }; // class AssociationIterator
  4851. /// Build a non-result-dependent generic selection expression.
  4852. GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
  4853. Expr *ControllingExpr,
  4854. ArrayRef<TypeSourceInfo *> AssocTypes,
  4855. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4856. SourceLocation RParenLoc,
  4857. bool ContainsUnexpandedParameterPack,
  4858. unsigned ResultIndex);
  4859. /// Build a result-dependent generic selection expression.
  4860. GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
  4861. Expr *ControllingExpr,
  4862. ArrayRef<TypeSourceInfo *> AssocTypes,
  4863. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4864. SourceLocation RParenLoc,
  4865. bool ContainsUnexpandedParameterPack);
  4866. /// Build an empty generic selection expression for deserialization.
  4867. explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
  4868. public:
  4869. /// Create a non-result-dependent generic selection expression.
  4870. static GenericSelectionExpr *
  4871. Create(const ASTContext &Context, SourceLocation GenericLoc,
  4872. Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
  4873. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4874. SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
  4875. unsigned ResultIndex);
  4876. /// Create a result-dependent generic selection expression.
  4877. static GenericSelectionExpr *
  4878. Create(const ASTContext &Context, SourceLocation GenericLoc,
  4879. Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
  4880. ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
  4881. SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
  4882. /// Create an empty generic selection expression for deserialization.
  4883. static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
  4884. unsigned NumAssocs);
  4885. using Association = AssociationTy<false>;
  4886. using ConstAssociation = AssociationTy<true>;
  4887. using AssociationIterator = AssociationIteratorTy<false>;
  4888. using ConstAssociationIterator = AssociationIteratorTy<true>;
  4889. using association_range = llvm::iterator_range<AssociationIterator>;
  4890. using const_association_range =
  4891. llvm::iterator_range<ConstAssociationIterator>;
  4892. /// The number of association expressions.
  4893. unsigned getNumAssocs() const { return NumAssocs; }
  4894. /// The zero-based index of the result expression's generic association in
  4895. /// the generic selection's association list. Defined only if the
  4896. /// generic selection is not result-dependent.
  4897. unsigned getResultIndex() const {
  4898. assert(!isResultDependent() &&
  4899. "Generic selection is result-dependent but getResultIndex called!");
  4900. return ResultIndex;
  4901. }
  4902. /// Whether this generic selection is result-dependent.
  4903. bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
  4904. /// Return the controlling expression of this generic selection expression.
  4905. Expr *getControllingExpr() {
  4906. return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
  4907. }
  4908. const Expr *getControllingExpr() const {
  4909. return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
  4910. }
  4911. /// Return the result expression of this controlling expression. Defined if
  4912. /// and only if the generic selection expression is not result-dependent.
  4913. Expr *getResultExpr() {
  4914. return cast<Expr>(
  4915. getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
  4916. }
  4917. const Expr *getResultExpr() const {
  4918. return cast<Expr>(
  4919. getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
  4920. }
  4921. ArrayRef<Expr *> getAssocExprs() const {
  4922. return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
  4923. AssocExprStartIndex),
  4924. NumAssocs};
  4925. }
  4926. ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
  4927. return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs};
  4928. }
  4929. /// Return the Ith association expression with its TypeSourceInfo,
  4930. /// bundled together in GenericSelectionExpr::(Const)Association.
  4931. Association getAssociation(unsigned I) {
  4932. assert(I < getNumAssocs() &&
  4933. "Out-of-range index in GenericSelectionExpr::getAssociation!");
  4934. return Association(
  4935. cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
  4936. getTrailingObjects<TypeSourceInfo *>()[I],
  4937. !isResultDependent() && (getResultIndex() == I));
  4938. }
  4939. ConstAssociation getAssociation(unsigned I) const {
  4940. assert(I < getNumAssocs() &&
  4941. "Out-of-range index in GenericSelectionExpr::getAssociation!");
  4942. return ConstAssociation(
  4943. cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
  4944. getTrailingObjects<TypeSourceInfo *>()[I],
  4945. !isResultDependent() && (getResultIndex() == I));
  4946. }
  4947. association_range associations() {
  4948. AssociationIterator Begin(getTrailingObjects<Stmt *>() +
  4949. AssocExprStartIndex,
  4950. getTrailingObjects<TypeSourceInfo *>(),
  4951. /*Offset=*/0, ResultIndex);
  4952. AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
  4953. /*Offset=*/NumAssocs, ResultIndex);
  4954. return llvm::make_range(Begin, End);
  4955. }
  4956. const_association_range associations() const {
  4957. ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
  4958. AssocExprStartIndex,
  4959. getTrailingObjects<TypeSourceInfo *>(),
  4960. /*Offset=*/0, ResultIndex);
  4961. ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
  4962. /*Offset=*/NumAssocs, ResultIndex);
  4963. return llvm::make_range(Begin, End);
  4964. }
  4965. SourceLocation getGenericLoc() const {
  4966. return GenericSelectionExprBits.GenericLoc;
  4967. }
  4968. SourceLocation getDefaultLoc() const { return DefaultLoc; }
  4969. SourceLocation getRParenLoc() const { return RParenLoc; }
  4970. SourceLocation getBeginLoc() const { return getGenericLoc(); }
  4971. SourceLocation getEndLoc() const { return getRParenLoc(); }
  4972. static bool classof(const Stmt *T) {
  4973. return T->getStmtClass() == GenericSelectionExprClass;
  4974. }
  4975. child_range children() {
  4976. return child_range(getTrailingObjects<Stmt *>(),
  4977. getTrailingObjects<Stmt *>() +
  4978. numTrailingObjects(OverloadToken<Stmt *>()));
  4979. }
  4980. const_child_range children() const {
  4981. return const_child_range(getTrailingObjects<Stmt *>(),
  4982. getTrailingObjects<Stmt *>() +
  4983. numTrailingObjects(OverloadToken<Stmt *>()));
  4984. }
  4985. };
  4986. //===----------------------------------------------------------------------===//
  4987. // Clang Extensions
  4988. //===----------------------------------------------------------------------===//
  4989. /// ExtVectorElementExpr - This represents access to specific elements of a
  4990. /// vector, and may occur on the left hand side or right hand side. For example
  4991. /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
  4992. ///
  4993. /// Note that the base may have either vector or pointer to vector type, just
  4994. /// like a struct field reference.
  4995. ///
  4996. class ExtVectorElementExpr : public Expr {
  4997. Stmt *Base;
  4998. IdentifierInfo *Accessor;
  4999. SourceLocation AccessorLoc;
  5000. public:
  5001. ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
  5002. IdentifierInfo &accessor, SourceLocation loc)
  5003. : Expr(ExtVectorElementExprClass, ty, VK,
  5004. (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
  5005. Base(base), Accessor(&accessor), AccessorLoc(loc) {
  5006. setDependence(computeDependence(this));
  5007. }
  5008. /// Build an empty vector element expression.
  5009. explicit ExtVectorElementExpr(EmptyShell Empty)
  5010. : Expr(ExtVectorElementExprClass, Empty) { }
  5011. const Expr *getBase() const { return cast<Expr>(Base); }
  5012. Expr *getBase() { return cast<Expr>(Base); }
  5013. void setBase(Expr *E) { Base = E; }
  5014. IdentifierInfo &getAccessor() const { return *Accessor; }
  5015. void setAccessor(IdentifierInfo *II) { Accessor = II; }
  5016. SourceLocation getAccessorLoc() const { return AccessorLoc; }
  5017. void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
  5018. /// getNumElements - Get the number of components being selected.
  5019. unsigned getNumElements() const;
  5020. /// containsDuplicateElements - Return true if any element access is
  5021. /// repeated.
  5022. bool containsDuplicateElements() const;
  5023. /// getEncodedElementAccess - Encode the elements accessed into an llvm
  5024. /// aggregate Constant of ConstantInt(s).
  5025. void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
  5026. SourceLocation getBeginLoc() const LLVM_READONLY {
  5027. return getBase()->getBeginLoc();
  5028. }
  5029. SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
  5030. /// isArrow - Return true if the base expression is a pointer to vector,
  5031. /// return false if the base expression is a vector.
  5032. bool isArrow() const;
  5033. static bool classof(const Stmt *T) {
  5034. return T->getStmtClass() == ExtVectorElementExprClass;
  5035. }
  5036. // Iterators
  5037. child_range children() { return child_range(&Base, &Base+1); }
  5038. const_child_range children() const {
  5039. return const_child_range(&Base, &Base + 1);
  5040. }
  5041. };
  5042. /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
  5043. /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
  5044. class BlockExpr : public Expr {
  5045. protected:
  5046. BlockDecl *TheBlock;
  5047. public:
  5048. BlockExpr(BlockDecl *BD, QualType ty)
  5049. : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
  5050. setDependence(computeDependence(this));
  5051. }
  5052. /// Build an empty block expression.
  5053. explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
  5054. const BlockDecl *getBlockDecl() const { return TheBlock; }
  5055. BlockDecl *getBlockDecl() { return TheBlock; }
  5056. void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
  5057. // Convenience functions for probing the underlying BlockDecl.
  5058. SourceLocation getCaretLocation() const;
  5059. const Stmt *getBody() const;
  5060. Stmt *getBody();
  5061. SourceLocation getBeginLoc() const LLVM_READONLY {
  5062. return getCaretLocation();
  5063. }
  5064. SourceLocation getEndLoc() const LLVM_READONLY {
  5065. return getBody()->getEndLoc();
  5066. }
  5067. /// getFunctionType - Return the underlying function type for this block.
  5068. const FunctionProtoType *getFunctionType() const;
  5069. static bool classof(const Stmt *T) {
  5070. return T->getStmtClass() == BlockExprClass;
  5071. }
  5072. // Iterators
  5073. child_range children() {
  5074. return child_range(child_iterator(), child_iterator());
  5075. }
  5076. const_child_range children() const {
  5077. return const_child_range(const_child_iterator(), const_child_iterator());
  5078. }
  5079. };
  5080. /// Copy initialization expr of a __block variable and a boolean flag that
  5081. /// indicates whether the expression can throw.
  5082. struct BlockVarCopyInit {
  5083. BlockVarCopyInit() = default;
  5084. BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
  5085. : ExprAndFlag(CopyExpr, CanThrow) {}
  5086. void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
  5087. ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
  5088. }
  5089. Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
  5090. bool canThrow() const { return ExprAndFlag.getInt(); }
  5091. llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
  5092. };
  5093. /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
  5094. /// This AST node provides support for reinterpreting a type to another
  5095. /// type of the same size.
  5096. class AsTypeExpr : public Expr {
  5097. private:
  5098. Stmt *SrcExpr;
  5099. SourceLocation BuiltinLoc, RParenLoc;
  5100. friend class ASTReader;
  5101. friend class ASTStmtReader;
  5102. explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
  5103. public:
  5104. AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
  5105. ExprObjectKind OK, SourceLocation BuiltinLoc,
  5106. SourceLocation RParenLoc)
  5107. : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
  5108. BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
  5109. setDependence(computeDependence(this));
  5110. }
  5111. /// getSrcExpr - Return the Expr to be converted.
  5112. Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
  5113. /// getBuiltinLoc - Return the location of the __builtin_astype token.
  5114. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  5115. /// getRParenLoc - Return the location of final right parenthesis.
  5116. SourceLocation getRParenLoc() const { return RParenLoc; }
  5117. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  5118. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  5119. static bool classof(const Stmt *T) {
  5120. return T->getStmtClass() == AsTypeExprClass;
  5121. }
  5122. // Iterators
  5123. child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
  5124. const_child_range children() const {
  5125. return const_child_range(&SrcExpr, &SrcExpr + 1);
  5126. }
  5127. };
  5128. /// PseudoObjectExpr - An expression which accesses a pseudo-object
  5129. /// l-value. A pseudo-object is an abstract object, accesses to which
  5130. /// are translated to calls. The pseudo-object expression has a
  5131. /// syntactic form, which shows how the expression was actually
  5132. /// written in the source code, and a semantic form, which is a series
  5133. /// of expressions to be executed in order which detail how the
  5134. /// operation is actually evaluated. Optionally, one of the semantic
  5135. /// forms may also provide a result value for the expression.
  5136. ///
  5137. /// If any of the semantic-form expressions is an OpaqueValueExpr,
  5138. /// that OVE is required to have a source expression, and it is bound
  5139. /// to the result of that source expression. Such OVEs may appear
  5140. /// only in subsequent semantic-form expressions and as
  5141. /// sub-expressions of the syntactic form.
  5142. ///
  5143. /// PseudoObjectExpr should be used only when an operation can be
  5144. /// usefully described in terms of fairly simple rewrite rules on
  5145. /// objects and functions that are meant to be used by end-developers.
  5146. /// For example, under the Itanium ABI, dynamic casts are implemented
  5147. /// as a call to a runtime function called __dynamic_cast; using this
  5148. /// class to describe that would be inappropriate because that call is
  5149. /// not really part of the user-visible semantics, and instead the
  5150. /// cast is properly reflected in the AST and IR-generation has been
  5151. /// taught to generate the call as necessary. In contrast, an
  5152. /// Objective-C property access is semantically defined to be
  5153. /// equivalent to a particular message send, and this is very much
  5154. /// part of the user model. The name of this class encourages this
  5155. /// modelling design.
  5156. class PseudoObjectExpr final
  5157. : public Expr,
  5158. private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
  5159. // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
  5160. // Always at least two, because the first sub-expression is the
  5161. // syntactic form.
  5162. // PseudoObjectExprBits.ResultIndex - The index of the
  5163. // sub-expression holding the result. 0 means the result is void,
  5164. // which is unambiguous because it's the index of the syntactic
  5165. // form. Note that this is therefore 1 higher than the value passed
  5166. // in to Create, which is an index within the semantic forms.
  5167. // Note also that ASTStmtWriter assumes this encoding.
  5168. Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
  5169. const Expr * const *getSubExprsBuffer() const {
  5170. return getTrailingObjects<Expr *>();
  5171. }
  5172. PseudoObjectExpr(QualType type, ExprValueKind VK,
  5173. Expr *syntactic, ArrayRef<Expr*> semantic,
  5174. unsigned resultIndex);
  5175. PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
  5176. unsigned getNumSubExprs() const {
  5177. return PseudoObjectExprBits.NumSubExprs;
  5178. }
  5179. public:
  5180. /// NoResult - A value for the result index indicating that there is
  5181. /// no semantic result.
  5182. enum : unsigned { NoResult = ~0U };
  5183. static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
  5184. ArrayRef<Expr*> semantic,
  5185. unsigned resultIndex);
  5186. static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
  5187. unsigned numSemanticExprs);
  5188. /// Return the syntactic form of this expression, i.e. the
  5189. /// expression it actually looks like. Likely to be expressed in
  5190. /// terms of OpaqueValueExprs bound in the semantic form.
  5191. Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
  5192. const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
  5193. /// Return the index of the result-bearing expression into the semantics
  5194. /// expressions, or PseudoObjectExpr::NoResult if there is none.
  5195. unsigned getResultExprIndex() const {
  5196. if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
  5197. return PseudoObjectExprBits.ResultIndex - 1;
  5198. }
  5199. /// Return the result-bearing expression, or null if there is none.
  5200. Expr *getResultExpr() {
  5201. if (PseudoObjectExprBits.ResultIndex == 0)
  5202. return nullptr;
  5203. return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
  5204. }
  5205. const Expr *getResultExpr() const {
  5206. return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
  5207. }
  5208. unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
  5209. typedef Expr * const *semantics_iterator;
  5210. typedef const Expr * const *const_semantics_iterator;
  5211. semantics_iterator semantics_begin() {
  5212. return getSubExprsBuffer() + 1;
  5213. }
  5214. const_semantics_iterator semantics_begin() const {
  5215. return getSubExprsBuffer() + 1;
  5216. }
  5217. semantics_iterator semantics_end() {
  5218. return getSubExprsBuffer() + getNumSubExprs();
  5219. }
  5220. const_semantics_iterator semantics_end() const {
  5221. return getSubExprsBuffer() + getNumSubExprs();
  5222. }
  5223. llvm::iterator_range<semantics_iterator> semantics() {
  5224. return llvm::make_range(semantics_begin(), semantics_end());
  5225. }
  5226. llvm::iterator_range<const_semantics_iterator> semantics() const {
  5227. return llvm::make_range(semantics_begin(), semantics_end());
  5228. }
  5229. Expr *getSemanticExpr(unsigned index) {
  5230. assert(index + 1 < getNumSubExprs());
  5231. return getSubExprsBuffer()[index + 1];
  5232. }
  5233. const Expr *getSemanticExpr(unsigned index) const {
  5234. return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
  5235. }
  5236. SourceLocation getExprLoc() const LLVM_READONLY {
  5237. return getSyntacticForm()->getExprLoc();
  5238. }
  5239. SourceLocation getBeginLoc() const LLVM_READONLY {
  5240. return getSyntacticForm()->getBeginLoc();
  5241. }
  5242. SourceLocation getEndLoc() const LLVM_READONLY {
  5243. return getSyntacticForm()->getEndLoc();
  5244. }
  5245. child_range children() {
  5246. const_child_range CCR =
  5247. const_cast<const PseudoObjectExpr *>(this)->children();
  5248. return child_range(cast_away_const(CCR.begin()),
  5249. cast_away_const(CCR.end()));
  5250. }
  5251. const_child_range children() const {
  5252. Stmt *const *cs = const_cast<Stmt *const *>(
  5253. reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
  5254. return const_child_range(cs, cs + getNumSubExprs());
  5255. }
  5256. static bool classof(const Stmt *T) {
  5257. return T->getStmtClass() == PseudoObjectExprClass;
  5258. }
  5259. friend TrailingObjects;
  5260. friend class ASTStmtReader;
  5261. };
  5262. /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
  5263. /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
  5264. /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
  5265. /// and corresponding __opencl_atomic_* for OpenCL 2.0.
  5266. /// All of these instructions take one primary pointer, at least one memory
  5267. /// order. The instructions for which getScopeModel returns non-null value
  5268. /// take one synch scope.
  5269. class AtomicExpr : public Expr {
  5270. public:
  5271. enum AtomicOp {
  5272. #define BUILTIN(ID, TYPE, ATTRS)
  5273. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
  5274. #include "clang/Basic/Builtins.def"
  5275. // Avoid trailing comma
  5276. BI_First = 0
  5277. };
  5278. private:
  5279. /// Location of sub-expressions.
  5280. /// The location of Scope sub-expression is NumSubExprs - 1, which is
  5281. /// not fixed, therefore is not defined in enum.
  5282. enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
  5283. Stmt *SubExprs[END_EXPR + 1];
  5284. unsigned NumSubExprs;
  5285. SourceLocation BuiltinLoc, RParenLoc;
  5286. AtomicOp Op;
  5287. friend class ASTStmtReader;
  5288. public:
  5289. AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
  5290. AtomicOp op, SourceLocation RP);
  5291. /// Determine the number of arguments the specified atomic builtin
  5292. /// should have.
  5293. static unsigned getNumSubExprs(AtomicOp Op);
  5294. /// Build an empty AtomicExpr.
  5295. explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
  5296. Expr *getPtr() const {
  5297. return cast<Expr>(SubExprs[PTR]);
  5298. }
  5299. Expr *getOrder() const {
  5300. return cast<Expr>(SubExprs[ORDER]);
  5301. }
  5302. Expr *getScope() const {
  5303. assert(getScopeModel() && "No scope");
  5304. return cast<Expr>(SubExprs[NumSubExprs - 1]);
  5305. }
  5306. Expr *getVal1() const {
  5307. if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
  5308. return cast<Expr>(SubExprs[ORDER]);
  5309. assert(NumSubExprs > VAL1);
  5310. return cast<Expr>(SubExprs[VAL1]);
  5311. }
  5312. Expr *getOrderFail() const {
  5313. assert(NumSubExprs > ORDER_FAIL);
  5314. return cast<Expr>(SubExprs[ORDER_FAIL]);
  5315. }
  5316. Expr *getVal2() const {
  5317. if (Op == AO__atomic_exchange)
  5318. return cast<Expr>(SubExprs[ORDER_FAIL]);
  5319. assert(NumSubExprs > VAL2);
  5320. return cast<Expr>(SubExprs[VAL2]);
  5321. }
  5322. Expr *getWeak() const {
  5323. assert(NumSubExprs > WEAK);
  5324. return cast<Expr>(SubExprs[WEAK]);
  5325. }
  5326. QualType getValueType() const;
  5327. AtomicOp getOp() const { return Op; }
  5328. unsigned getNumSubExprs() const { return NumSubExprs; }
  5329. Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
  5330. const Expr * const *getSubExprs() const {
  5331. return reinterpret_cast<Expr * const *>(SubExprs);
  5332. }
  5333. bool isVolatile() const {
  5334. return getPtr()->getType()->getPointeeType().isVolatileQualified();
  5335. }
  5336. bool isCmpXChg() const {
  5337. return getOp() == AO__c11_atomic_compare_exchange_strong ||
  5338. getOp() == AO__c11_atomic_compare_exchange_weak ||
  5339. getOp() == AO__hip_atomic_compare_exchange_strong ||
  5340. getOp() == AO__opencl_atomic_compare_exchange_strong ||
  5341. getOp() == AO__opencl_atomic_compare_exchange_weak ||
  5342. getOp() == AO__hip_atomic_compare_exchange_weak ||
  5343. getOp() == AO__atomic_compare_exchange ||
  5344. getOp() == AO__atomic_compare_exchange_n;
  5345. }
  5346. bool isOpenCL() const {
  5347. return getOp() >= AO__opencl_atomic_init &&
  5348. getOp() <= AO__opencl_atomic_fetch_max;
  5349. }
  5350. SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
  5351. SourceLocation getRParenLoc() const { return RParenLoc; }
  5352. SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
  5353. SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
  5354. static bool classof(const Stmt *T) {
  5355. return T->getStmtClass() == AtomicExprClass;
  5356. }
  5357. // Iterators
  5358. child_range children() {
  5359. return child_range(SubExprs, SubExprs+NumSubExprs);
  5360. }
  5361. const_child_range children() const {
  5362. return const_child_range(SubExprs, SubExprs + NumSubExprs);
  5363. }
  5364. /// Get atomic scope model for the atomic op code.
  5365. /// \return empty atomic scope model if the atomic op code does not have
  5366. /// scope operand.
  5367. static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
  5368. auto Kind =
  5369. (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
  5370. ? AtomicScopeModelKind::OpenCL
  5371. : (Op >= AO__hip_atomic_load && Op <= AO__hip_atomic_fetch_max)
  5372. ? AtomicScopeModelKind::HIP
  5373. : AtomicScopeModelKind::None;
  5374. return AtomicScopeModel::create(Kind);
  5375. }
  5376. /// Get atomic scope model.
  5377. /// \return empty atomic scope model if this atomic expression does not have
  5378. /// scope operand.
  5379. std::unique_ptr<AtomicScopeModel> getScopeModel() const {
  5380. return getScopeModel(getOp());
  5381. }
  5382. };
  5383. /// TypoExpr - Internal placeholder for expressions where typo correction
  5384. /// still needs to be performed and/or an error diagnostic emitted.
  5385. class TypoExpr : public Expr {
  5386. // The location for the typo name.
  5387. SourceLocation TypoLoc;
  5388. public:
  5389. TypoExpr(QualType T, SourceLocation TypoLoc)
  5390. : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) {
  5391. assert(T->isDependentType() && "TypoExpr given a non-dependent type");
  5392. setDependence(ExprDependence::TypeValueInstantiation |
  5393. ExprDependence::Error);
  5394. }
  5395. child_range children() {
  5396. return child_range(child_iterator(), child_iterator());
  5397. }
  5398. const_child_range children() const {
  5399. return const_child_range(const_child_iterator(), const_child_iterator());
  5400. }
  5401. SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; }
  5402. SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; }
  5403. static bool classof(const Stmt *T) {
  5404. return T->getStmtClass() == TypoExprClass;
  5405. }
  5406. };
  5407. /// Frontend produces RecoveryExprs on semantic errors that prevent creating
  5408. /// other well-formed expressions. E.g. when type-checking of a binary operator
  5409. /// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
  5410. /// to produce a recovery expression storing left and right operands.
  5411. ///
  5412. /// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
  5413. /// preserve expressions in AST that would otherwise be dropped. It captures
  5414. /// subexpressions of some expression that we could not construct and source
  5415. /// range covered by the expression.
  5416. ///
  5417. /// By default, RecoveryExpr uses dependence-bits to take advantage of existing
  5418. /// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
  5419. /// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
  5420. /// addition to that, clang does not report most errors on dependent
  5421. /// expressions, so we get rid of bogus errors for free. However, note that
  5422. /// unlike other dependent expressions, RecoveryExpr can be produced in
  5423. /// non-template contexts.
  5424. ///
  5425. /// We will preserve the type in RecoveryExpr when the type is known, e.g.
  5426. /// preserving the return type for a broken non-overloaded function call, a
  5427. /// overloaded call where all candidates have the same return type. In this
  5428. /// case, the expression is not type-dependent (unless the known type is itself
  5429. /// dependent)
  5430. ///
  5431. /// One can also reliably suppress all bogus errors on expressions containing
  5432. /// recovery expressions by examining results of Expr::containsErrors().
  5433. class RecoveryExpr final : public Expr,
  5434. private llvm::TrailingObjects<RecoveryExpr, Expr *> {
  5435. public:
  5436. static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
  5437. SourceLocation BeginLoc, SourceLocation EndLoc,
  5438. ArrayRef<Expr *> SubExprs);
  5439. static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
  5440. ArrayRef<Expr *> subExpressions() {
  5441. auto *B = getTrailingObjects<Expr *>();
  5442. return llvm::makeArrayRef(B, B + NumExprs);
  5443. }
  5444. ArrayRef<const Expr *> subExpressions() const {
  5445. return const_cast<RecoveryExpr *>(this)->subExpressions();
  5446. }
  5447. child_range children() {
  5448. Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
  5449. return child_range(B, B + NumExprs);
  5450. }
  5451. SourceLocation getBeginLoc() const { return BeginLoc; }
  5452. SourceLocation getEndLoc() const { return EndLoc; }
  5453. static bool classof(const Stmt *T) {
  5454. return T->getStmtClass() == RecoveryExprClass;
  5455. }
  5456. private:
  5457. RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
  5458. SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
  5459. RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
  5460. : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
  5461. size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
  5462. SourceLocation BeginLoc, EndLoc;
  5463. unsigned NumExprs;
  5464. friend TrailingObjects;
  5465. friend class ASTStmtReader;
  5466. friend class ASTStmtWriter;
  5467. };
  5468. } // end namespace clang
  5469. #endif // LLVM_CLANG_AST_EXPR_H
  5470. #ifdef __GNUC__
  5471. #pragma GCC diagnostic pop
  5472. #endif