ExprConstant.cpp 495 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include <cstring>
  35. #include <functional>
  36. #include "Interp/Context.h"
  37. #include "Interp/Frame.h"
  38. #include "Interp/State.h"
  39. #include "clang/AST/APValue.h"
  40. #include "clang/AST/ASTContext.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/ASTLambda.h"
  43. #include "clang/AST/CXXInheritance.h"
  44. #include "clang/AST/CharUnits.h"
  45. #include "clang/AST/CurrentSourceLocExprScope.h"
  46. #include "clang/AST/Expr.h"
  47. #include "clang/AST/OSLog.h"
  48. #include "clang/AST/OptionalDiagnostic.h"
  49. #include "clang/AST/RecordLayout.h"
  50. #include "clang/AST/StmtVisitor.h"
  51. #include "clang/AST/TypeLoc.h"
  52. #include "clang/Basic/Builtins.h"
  53. #include "clang/Basic/FixedPoint.h"
  54. #include "clang/Basic/TargetInfo.h"
  55. #include "llvm/ADT/Optional.h"
  56. #include "llvm/ADT/SmallBitVector.h"
  57. #include "llvm/Support/SaveAndRestore.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #define DEBUG_TYPE "exprconstant"
  60. using namespace clang;
  61. using llvm::APInt;
  62. using llvm::APSInt;
  63. using llvm::APFloat;
  64. using llvm::Optional;
  65. namespace {
  66. struct LValue;
  67. class CallStackFrame;
  68. class EvalInfo;
  69. using SourceLocExprScopeGuard =
  70. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  71. static QualType getType(APValue::LValueBase B) {
  72. if (!B) return QualType();
  73. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  74. // FIXME: It's unclear where we're supposed to take the type from, and
  75. // this actually matters for arrays of unknown bound. Eg:
  76. //
  77. // extern int arr[]; void f() { extern int arr[3]; };
  78. // constexpr int *p = &arr[1]; // valid?
  79. //
  80. // For now, we take the array bound from the most recent declaration.
  81. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  82. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  83. QualType T = Redecl->getType();
  84. if (!T->isIncompleteArrayType())
  85. return T;
  86. }
  87. return D->getType();
  88. }
  89. if (B.is<TypeInfoLValue>())
  90. return B.getTypeInfoType();
  91. if (B.is<DynamicAllocLValue>())
  92. return B.getDynamicAllocType();
  93. const Expr *Base = B.get<const Expr*>();
  94. // For a materialized temporary, the type of the temporary we materialized
  95. // may not be the type of the expression.
  96. if (const MaterializeTemporaryExpr *MTE =
  97. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  98. SmallVector<const Expr *, 2> CommaLHSs;
  99. SmallVector<SubobjectAdjustment, 2> Adjustments;
  100. const Expr *Temp = MTE->GetTemporaryExpr();
  101. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  102. Adjustments);
  103. // Keep any cv-qualifiers from the reference if we generated a temporary
  104. // for it directly. Otherwise use the type after adjustment.
  105. if (!Adjustments.empty())
  106. return Inner->getType();
  107. }
  108. return Base->getType();
  109. }
  110. /// Get an LValue path entry, which is known to not be an array index, as a
  111. /// field declaration.
  112. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  113. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  114. }
  115. /// Get an LValue path entry, which is known to not be an array index, as a
  116. /// base class declaration.
  117. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  118. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  119. }
  120. /// Determine whether this LValue path entry for a base class names a virtual
  121. /// base class.
  122. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  123. return E.getAsBaseOrMember().getInt();
  124. }
  125. /// Given an expression, determine the type used to store the result of
  126. /// evaluating that expression.
  127. static QualType getStorageType(ASTContext &Ctx, Expr *E) {
  128. if (E->isRValue())
  129. return E->getType();
  130. return Ctx.getLValueReferenceType(E->getType());
  131. }
  132. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  133. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  134. const FunctionDecl *Callee = CE->getDirectCallee();
  135. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  136. }
  137. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  138. /// This will look through a single cast.
  139. ///
  140. /// Returns null if we couldn't unwrap a function with alloc_size.
  141. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  142. if (!E->getType()->isPointerType())
  143. return nullptr;
  144. E = E->IgnoreParens();
  145. // If we're doing a variable assignment from e.g. malloc(N), there will
  146. // probably be a cast of some kind. In exotic cases, we might also see a
  147. // top-level ExprWithCleanups. Ignore them either way.
  148. if (const auto *FE = dyn_cast<FullExpr>(E))
  149. E = FE->getSubExpr()->IgnoreParens();
  150. if (const auto *Cast = dyn_cast<CastExpr>(E))
  151. E = Cast->getSubExpr()->IgnoreParens();
  152. if (const auto *CE = dyn_cast<CallExpr>(E))
  153. return getAllocSizeAttr(CE) ? CE : nullptr;
  154. return nullptr;
  155. }
  156. /// Determines whether or not the given Base contains a call to a function
  157. /// with the alloc_size attribute.
  158. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  159. const auto *E = Base.dyn_cast<const Expr *>();
  160. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  161. }
  162. /// The bound to claim that an array of unknown bound has.
  163. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  164. /// to an arbitrary value that's likely to loudly break things if it's used.
  165. static const uint64_t AssumedSizeForUnsizedArray =
  166. std::numeric_limits<uint64_t>::max() / 2;
  167. /// Determines if an LValue with the given LValueBase will have an unsized
  168. /// array in its designator.
  169. /// Find the path length and type of the most-derived subobject in the given
  170. /// path, and find the size of the containing array, if any.
  171. static unsigned
  172. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  173. ArrayRef<APValue::LValuePathEntry> Path,
  174. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  175. bool &FirstEntryIsUnsizedArray) {
  176. // This only accepts LValueBases from APValues, and APValues don't support
  177. // arrays that lack size info.
  178. assert(!isBaseAnAllocSizeCall(Base) &&
  179. "Unsized arrays shouldn't appear here");
  180. unsigned MostDerivedLength = 0;
  181. Type = getType(Base);
  182. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  183. if (Type->isArrayType()) {
  184. const ArrayType *AT = Ctx.getAsArrayType(Type);
  185. Type = AT->getElementType();
  186. MostDerivedLength = I + 1;
  187. IsArray = true;
  188. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  189. ArraySize = CAT->getSize().getZExtValue();
  190. } else {
  191. assert(I == 0 && "unexpected unsized array designator");
  192. FirstEntryIsUnsizedArray = true;
  193. ArraySize = AssumedSizeForUnsizedArray;
  194. }
  195. } else if (Type->isAnyComplexType()) {
  196. const ComplexType *CT = Type->castAs<ComplexType>();
  197. Type = CT->getElementType();
  198. ArraySize = 2;
  199. MostDerivedLength = I + 1;
  200. IsArray = true;
  201. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  202. Type = FD->getType();
  203. ArraySize = 0;
  204. MostDerivedLength = I + 1;
  205. IsArray = false;
  206. } else {
  207. // Path[I] describes a base class.
  208. ArraySize = 0;
  209. IsArray = false;
  210. }
  211. }
  212. return MostDerivedLength;
  213. }
  214. /// A path from a glvalue to a subobject of that glvalue.
  215. struct SubobjectDesignator {
  216. /// True if the subobject was named in a manner not supported by C++11. Such
  217. /// lvalues can still be folded, but they are not core constant expressions
  218. /// and we cannot perform lvalue-to-rvalue conversions on them.
  219. unsigned Invalid : 1;
  220. /// Is this a pointer one past the end of an object?
  221. unsigned IsOnePastTheEnd : 1;
  222. /// Indicator of whether the first entry is an unsized array.
  223. unsigned FirstEntryIsAnUnsizedArray : 1;
  224. /// Indicator of whether the most-derived object is an array element.
  225. unsigned MostDerivedIsArrayElement : 1;
  226. /// The length of the path to the most-derived object of which this is a
  227. /// subobject.
  228. unsigned MostDerivedPathLength : 28;
  229. /// The size of the array of which the most-derived object is an element.
  230. /// This will always be 0 if the most-derived object is not an array
  231. /// element. 0 is not an indicator of whether or not the most-derived object
  232. /// is an array, however, because 0-length arrays are allowed.
  233. ///
  234. /// If the current array is an unsized array, the value of this is
  235. /// undefined.
  236. uint64_t MostDerivedArraySize;
  237. /// The type of the most derived object referred to by this address.
  238. QualType MostDerivedType;
  239. typedef APValue::LValuePathEntry PathEntry;
  240. /// The entries on the path from the glvalue to the designated subobject.
  241. SmallVector<PathEntry, 8> Entries;
  242. SubobjectDesignator() : Invalid(true) {}
  243. explicit SubobjectDesignator(QualType T)
  244. : Invalid(false), IsOnePastTheEnd(false),
  245. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  246. MostDerivedPathLength(0), MostDerivedArraySize(0),
  247. MostDerivedType(T) {}
  248. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  249. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  250. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  251. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  252. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  253. if (!Invalid) {
  254. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  255. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  256. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  257. if (V.getLValueBase()) {
  258. bool IsArray = false;
  259. bool FirstIsUnsizedArray = false;
  260. MostDerivedPathLength = findMostDerivedSubobject(
  261. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  262. MostDerivedType, IsArray, FirstIsUnsizedArray);
  263. MostDerivedIsArrayElement = IsArray;
  264. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  265. }
  266. }
  267. }
  268. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  269. unsigned NewLength) {
  270. if (Invalid)
  271. return;
  272. assert(Base && "cannot truncate path for null pointer");
  273. assert(NewLength <= Entries.size() && "not a truncation");
  274. if (NewLength == Entries.size())
  275. return;
  276. Entries.resize(NewLength);
  277. bool IsArray = false;
  278. bool FirstIsUnsizedArray = false;
  279. MostDerivedPathLength = findMostDerivedSubobject(
  280. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  281. FirstIsUnsizedArray);
  282. MostDerivedIsArrayElement = IsArray;
  283. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  284. }
  285. void setInvalid() {
  286. Invalid = true;
  287. Entries.clear();
  288. }
  289. /// Determine whether the most derived subobject is an array without a
  290. /// known bound.
  291. bool isMostDerivedAnUnsizedArray() const {
  292. assert(!Invalid && "Calling this makes no sense on invalid designators");
  293. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  294. }
  295. /// Determine what the most derived array's size is. Results in an assertion
  296. /// failure if the most derived array lacks a size.
  297. uint64_t getMostDerivedArraySize() const {
  298. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  299. return MostDerivedArraySize;
  300. }
  301. /// Determine whether this is a one-past-the-end pointer.
  302. bool isOnePastTheEnd() const {
  303. assert(!Invalid);
  304. if (IsOnePastTheEnd)
  305. return true;
  306. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  307. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  308. MostDerivedArraySize)
  309. return true;
  310. return false;
  311. }
  312. /// Get the range of valid index adjustments in the form
  313. /// {maximum value that can be subtracted from this pointer,
  314. /// maximum value that can be added to this pointer}
  315. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  316. if (Invalid || isMostDerivedAnUnsizedArray())
  317. return {0, 0};
  318. // [expr.add]p4: For the purposes of these operators, a pointer to a
  319. // nonarray object behaves the same as a pointer to the first element of
  320. // an array of length one with the type of the object as its element type.
  321. bool IsArray = MostDerivedPathLength == Entries.size() &&
  322. MostDerivedIsArrayElement;
  323. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  324. : (uint64_t)IsOnePastTheEnd;
  325. uint64_t ArraySize =
  326. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  327. return {ArrayIndex, ArraySize - ArrayIndex};
  328. }
  329. /// Check that this refers to a valid subobject.
  330. bool isValidSubobject() const {
  331. if (Invalid)
  332. return false;
  333. return !isOnePastTheEnd();
  334. }
  335. /// Check that this refers to a valid subobject, and if not, produce a
  336. /// relevant diagnostic and set the designator as invalid.
  337. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  338. /// Get the type of the designated object.
  339. QualType getType(ASTContext &Ctx) const {
  340. assert(!Invalid && "invalid designator has no subobject type");
  341. return MostDerivedPathLength == Entries.size()
  342. ? MostDerivedType
  343. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  344. }
  345. /// Update this designator to refer to the first element within this array.
  346. void addArrayUnchecked(const ConstantArrayType *CAT) {
  347. Entries.push_back(PathEntry::ArrayIndex(0));
  348. // This is a most-derived object.
  349. MostDerivedType = CAT->getElementType();
  350. MostDerivedIsArrayElement = true;
  351. MostDerivedArraySize = CAT->getSize().getZExtValue();
  352. MostDerivedPathLength = Entries.size();
  353. }
  354. /// Update this designator to refer to the first element within the array of
  355. /// elements of type T. This is an array of unknown size.
  356. void addUnsizedArrayUnchecked(QualType ElemTy) {
  357. Entries.push_back(PathEntry::ArrayIndex(0));
  358. MostDerivedType = ElemTy;
  359. MostDerivedIsArrayElement = true;
  360. // The value in MostDerivedArraySize is undefined in this case. So, set it
  361. // to an arbitrary value that's likely to loudly break things if it's
  362. // used.
  363. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  364. MostDerivedPathLength = Entries.size();
  365. }
  366. /// Update this designator to refer to the given base or member of this
  367. /// object.
  368. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  369. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  370. // If this isn't a base class, it's a new most-derived object.
  371. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  372. MostDerivedType = FD->getType();
  373. MostDerivedIsArrayElement = false;
  374. MostDerivedArraySize = 0;
  375. MostDerivedPathLength = Entries.size();
  376. }
  377. }
  378. /// Update this designator to refer to the given complex component.
  379. void addComplexUnchecked(QualType EltTy, bool Imag) {
  380. Entries.push_back(PathEntry::ArrayIndex(Imag));
  381. // This is technically a most-derived object, though in practice this
  382. // is unlikely to matter.
  383. MostDerivedType = EltTy;
  384. MostDerivedIsArrayElement = true;
  385. MostDerivedArraySize = 2;
  386. MostDerivedPathLength = Entries.size();
  387. }
  388. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  389. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  390. const APSInt &N);
  391. /// Add N to the address of this subobject.
  392. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  393. if (Invalid || !N) return;
  394. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  395. if (isMostDerivedAnUnsizedArray()) {
  396. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  397. // Can't verify -- trust that the user is doing the right thing (or if
  398. // not, trust that the caller will catch the bad behavior).
  399. // FIXME: Should we reject if this overflows, at least?
  400. Entries.back() = PathEntry::ArrayIndex(
  401. Entries.back().getAsArrayIndex() + TruncatedN);
  402. return;
  403. }
  404. // [expr.add]p4: For the purposes of these operators, a pointer to a
  405. // nonarray object behaves the same as a pointer to the first element of
  406. // an array of length one with the type of the object as its element type.
  407. bool IsArray = MostDerivedPathLength == Entries.size() &&
  408. MostDerivedIsArrayElement;
  409. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  410. : (uint64_t)IsOnePastTheEnd;
  411. uint64_t ArraySize =
  412. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  413. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  414. // Calculate the actual index in a wide enough type, so we can include
  415. // it in the note.
  416. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  417. (llvm::APInt&)N += ArrayIndex;
  418. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  419. diagnosePointerArithmetic(Info, E, N);
  420. setInvalid();
  421. return;
  422. }
  423. ArrayIndex += TruncatedN;
  424. assert(ArrayIndex <= ArraySize &&
  425. "bounds check succeeded for out-of-bounds index");
  426. if (IsArray)
  427. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  428. else
  429. IsOnePastTheEnd = (ArrayIndex != 0);
  430. }
  431. };
  432. /// A stack frame in the constexpr call stack.
  433. class CallStackFrame : public interp::Frame {
  434. public:
  435. EvalInfo &Info;
  436. /// Parent - The caller of this stack frame.
  437. CallStackFrame *Caller;
  438. /// Callee - The function which was called.
  439. const FunctionDecl *Callee;
  440. /// This - The binding for the this pointer in this call, if any.
  441. const LValue *This;
  442. /// Arguments - Parameter bindings for this function call, indexed by
  443. /// parameters' function scope indices.
  444. APValue *Arguments;
  445. /// Source location information about the default argument or default
  446. /// initializer expression we're evaluating, if any.
  447. CurrentSourceLocExprScope CurSourceLocExprScope;
  448. // Note that we intentionally use std::map here so that references to
  449. // values are stable.
  450. typedef std::pair<const void *, unsigned> MapKeyTy;
  451. typedef std::map<MapKeyTy, APValue> MapTy;
  452. /// Temporaries - Temporary lvalues materialized within this stack frame.
  453. MapTy Temporaries;
  454. /// CallLoc - The location of the call expression for this call.
  455. SourceLocation CallLoc;
  456. /// Index - The call index of this call.
  457. unsigned Index;
  458. /// The stack of integers for tracking version numbers for temporaries.
  459. SmallVector<unsigned, 2> TempVersionStack = {1};
  460. unsigned CurTempVersion = TempVersionStack.back();
  461. unsigned getTempVersion() const { return TempVersionStack.back(); }
  462. void pushTempVersion() {
  463. TempVersionStack.push_back(++CurTempVersion);
  464. }
  465. void popTempVersion() {
  466. TempVersionStack.pop_back();
  467. }
  468. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  469. // on the overall stack usage of deeply-recursing constexpr evaluations.
  470. // (We should cache this map rather than recomputing it repeatedly.)
  471. // But let's try this and see how it goes; we can look into caching the map
  472. // as a later change.
  473. /// LambdaCaptureFields - Mapping from captured variables/this to
  474. /// corresponding data members in the closure class.
  475. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  476. FieldDecl *LambdaThisCaptureField;
  477. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  478. const FunctionDecl *Callee, const LValue *This,
  479. APValue *Arguments);
  480. ~CallStackFrame();
  481. // Return the temporary for Key whose version number is Version.
  482. APValue *getTemporary(const void *Key, unsigned Version) {
  483. MapKeyTy KV(Key, Version);
  484. auto LB = Temporaries.lower_bound(KV);
  485. if (LB != Temporaries.end() && LB->first == KV)
  486. return &LB->second;
  487. // Pair (Key,Version) wasn't found in the map. Check that no elements
  488. // in the map have 'Key' as their key.
  489. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  490. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  491. "Element with key 'Key' found in map");
  492. return nullptr;
  493. }
  494. // Return the current temporary for Key in the map.
  495. APValue *getCurrentTemporary(const void *Key) {
  496. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  497. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  498. return &std::prev(UB)->second;
  499. return nullptr;
  500. }
  501. // Return the version number of the current temporary for Key.
  502. unsigned getCurrentTemporaryVersion(const void *Key) const {
  503. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  504. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  505. return std::prev(UB)->first.second;
  506. return 0;
  507. }
  508. /// Allocate storage for an object of type T in this stack frame.
  509. /// Populates LV with a handle to the created object. Key identifies
  510. /// the temporary within the stack frame, and must not be reused without
  511. /// bumping the temporary version number.
  512. template<typename KeyT>
  513. APValue &createTemporary(const KeyT *Key, QualType T,
  514. bool IsLifetimeExtended, LValue &LV);
  515. void describe(llvm::raw_ostream &OS) override;
  516. Frame *getCaller() const override { return Caller; }
  517. SourceLocation getCallLocation() const override { return CallLoc; }
  518. const FunctionDecl *getCallee() const override { return Callee; }
  519. };
  520. /// Temporarily override 'this'.
  521. class ThisOverrideRAII {
  522. public:
  523. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  524. : Frame(Frame), OldThis(Frame.This) {
  525. if (Enable)
  526. Frame.This = NewThis;
  527. }
  528. ~ThisOverrideRAII() {
  529. Frame.This = OldThis;
  530. }
  531. private:
  532. CallStackFrame &Frame;
  533. const LValue *OldThis;
  534. };
  535. }
  536. static bool HandleDestructorCall(EvalInfo &Info, SourceLocation Loc,
  537. APValue::LValueBase LVBase, APValue &Value,
  538. QualType T);
  539. namespace {
  540. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  541. class Cleanup {
  542. llvm::PointerIntPair<APValue*, 1, bool> Value;
  543. APValue::LValueBase Base;
  544. QualType T;
  545. public:
  546. Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
  547. bool IsLifetimeExtended)
  548. : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
  549. bool isLifetimeExtended() const { return Value.getInt(); }
  550. bool endLifetime(EvalInfo &Info, bool RunDestructors) {
  551. if (RunDestructors) {
  552. SourceLocation Loc;
  553. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  554. Loc = VD->getLocation();
  555. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  556. Loc = E->getExprLoc();
  557. return HandleDestructorCall(Info, Loc, Base, *Value.getPointer(), T);
  558. }
  559. *Value.getPointer() = APValue();
  560. return true;
  561. }
  562. bool hasSideEffect() {
  563. return T.isDestructedType();
  564. }
  565. };
  566. /// A reference to an object whose construction we are currently evaluating.
  567. struct ObjectUnderConstruction {
  568. APValue::LValueBase Base;
  569. ArrayRef<APValue::LValuePathEntry> Path;
  570. friend bool operator==(const ObjectUnderConstruction &LHS,
  571. const ObjectUnderConstruction &RHS) {
  572. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  573. }
  574. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  575. return llvm::hash_combine(Obj.Base, Obj.Path);
  576. }
  577. };
  578. enum class ConstructionPhase {
  579. None,
  580. Bases,
  581. AfterBases,
  582. Destroying,
  583. DestroyingBases
  584. };
  585. }
  586. namespace llvm {
  587. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  588. using Base = DenseMapInfo<APValue::LValueBase>;
  589. static ObjectUnderConstruction getEmptyKey() {
  590. return {Base::getEmptyKey(), {}}; }
  591. static ObjectUnderConstruction getTombstoneKey() {
  592. return {Base::getTombstoneKey(), {}};
  593. }
  594. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  595. return hash_value(Object);
  596. }
  597. static bool isEqual(const ObjectUnderConstruction &LHS,
  598. const ObjectUnderConstruction &RHS) {
  599. return LHS == RHS;
  600. }
  601. };
  602. }
  603. namespace {
  604. /// EvalInfo - This is a private struct used by the evaluator to capture
  605. /// information about a subexpression as it is folded. It retains information
  606. /// about the AST context, but also maintains information about the folded
  607. /// expression.
  608. ///
  609. /// If an expression could be evaluated, it is still possible it is not a C
  610. /// "integer constant expression" or constant expression. If not, this struct
  611. /// captures information about how and why not.
  612. ///
  613. /// One bit of information passed *into* the request for constant folding
  614. /// indicates whether the subexpression is "evaluated" or not according to C
  615. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  616. /// evaluate the expression regardless of what the RHS is, but C only allows
  617. /// certain things in certain situations.
  618. class EvalInfo : public interp::State {
  619. public:
  620. ASTContext &Ctx;
  621. /// EvalStatus - Contains information about the evaluation.
  622. Expr::EvalStatus &EvalStatus;
  623. /// CurrentCall - The top of the constexpr call stack.
  624. CallStackFrame *CurrentCall;
  625. /// CallStackDepth - The number of calls in the call stack right now.
  626. unsigned CallStackDepth;
  627. /// NextCallIndex - The next call index to assign.
  628. unsigned NextCallIndex;
  629. /// StepsLeft - The remaining number of evaluation steps we're permitted
  630. /// to perform. This is essentially a limit for the number of statements
  631. /// we will evaluate.
  632. unsigned StepsLeft;
  633. /// Force the use of the experimental new constant interpreter, bailing out
  634. /// with an error if a feature is not supported.
  635. bool ForceNewConstInterp;
  636. /// Enable the experimental new constant interpreter.
  637. bool EnableNewConstInterp;
  638. /// BottomFrame - The frame in which evaluation started. This must be
  639. /// initialized after CurrentCall and CallStackDepth.
  640. CallStackFrame BottomFrame;
  641. /// A stack of values whose lifetimes end at the end of some surrounding
  642. /// evaluation frame.
  643. llvm::SmallVector<Cleanup, 16> CleanupStack;
  644. /// EvaluatingDecl - This is the declaration whose initializer is being
  645. /// evaluated, if any.
  646. APValue::LValueBase EvaluatingDecl;
  647. /// EvaluatingDeclValue - This is the value being constructed for the
  648. /// declaration whose initializer is being evaluated, if any.
  649. APValue *EvaluatingDeclValue;
  650. /// Set of objects that are currently being constructed.
  651. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  652. ObjectsUnderConstruction;
  653. /// A dynamically-allocated heap object.
  654. struct DynAlloc {
  655. /// The value of this heap-allocated object.
  656. APValue Value;
  657. /// The allocating expression; used for diagnostics.
  658. const Expr *AllocExpr = nullptr;
  659. };
  660. struct DynAllocOrder {
  661. bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
  662. return L.getIndex() < R.getIndex();
  663. }
  664. };
  665. /// Current heap allocations, along with the location where each was
  666. /// allocated. We use std::map here because we need stable addresses
  667. /// for the stored APValues.
  668. std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
  669. /// The number of heap allocations performed so far in this evaluation.
  670. unsigned NumHeapAllocs = 0;
  671. struct EvaluatingConstructorRAII {
  672. EvalInfo &EI;
  673. ObjectUnderConstruction Object;
  674. bool DidInsert;
  675. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  676. bool HasBases)
  677. : EI(EI), Object(Object) {
  678. DidInsert =
  679. EI.ObjectsUnderConstruction
  680. .insert({Object, HasBases ? ConstructionPhase::Bases
  681. : ConstructionPhase::AfterBases})
  682. .second;
  683. }
  684. void finishedConstructingBases() {
  685. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  686. }
  687. ~EvaluatingConstructorRAII() {
  688. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  689. }
  690. };
  691. struct EvaluatingDestructorRAII {
  692. EvalInfo &EI;
  693. ObjectUnderConstruction Object;
  694. bool DidInsert;
  695. EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
  696. : EI(EI), Object(Object) {
  697. DidInsert = EI.ObjectsUnderConstruction
  698. .insert({Object, ConstructionPhase::Destroying})
  699. .second;
  700. }
  701. void startedDestroyingBases() {
  702. EI.ObjectsUnderConstruction[Object] =
  703. ConstructionPhase::DestroyingBases;
  704. }
  705. ~EvaluatingDestructorRAII() {
  706. if (DidInsert)
  707. EI.ObjectsUnderConstruction.erase(Object);
  708. }
  709. };
  710. ConstructionPhase
  711. isEvaluatingCtorDtor(APValue::LValueBase Base,
  712. ArrayRef<APValue::LValuePathEntry> Path) {
  713. return ObjectsUnderConstruction.lookup({Base, Path});
  714. }
  715. /// If we're currently speculatively evaluating, the outermost call stack
  716. /// depth at which we can mutate state, otherwise 0.
  717. unsigned SpeculativeEvaluationDepth = 0;
  718. /// The current array initialization index, if we're performing array
  719. /// initialization.
  720. uint64_t ArrayInitIndex = -1;
  721. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  722. /// notes attached to it will also be stored, otherwise they will not be.
  723. bool HasActiveDiagnostic;
  724. /// Have we emitted a diagnostic explaining why we couldn't constant
  725. /// fold (not just why it's not strictly a constant expression)?
  726. bool HasFoldFailureDiagnostic;
  727. /// Whether or not we're in a context where the front end requires a
  728. /// constant value.
  729. bool InConstantContext;
  730. /// Whether we're checking that an expression is a potential constant
  731. /// expression. If so, do not fail on constructs that could become constant
  732. /// later on (such as a use of an undefined global).
  733. bool CheckingPotentialConstantExpression = false;
  734. /// Whether we're checking for an expression that has undefined behavior.
  735. /// If so, we will produce warnings if we encounter an operation that is
  736. /// always undefined.
  737. bool CheckingForUndefinedBehavior = false;
  738. enum EvaluationMode {
  739. /// Evaluate as a constant expression. Stop if we find that the expression
  740. /// is not a constant expression.
  741. EM_ConstantExpression,
  742. /// Evaluate as a constant expression. Stop if we find that the expression
  743. /// is not a constant expression. Some expressions can be retried in the
  744. /// optimizer if we don't constant fold them here, but in an unevaluated
  745. /// context we try to fold them immediately since the optimizer never
  746. /// gets a chance to look at it.
  747. EM_ConstantExpressionUnevaluated,
  748. /// Fold the expression to a constant. Stop if we hit a side-effect that
  749. /// we can't model.
  750. EM_ConstantFold,
  751. /// Evaluate in any way we know how. Don't worry about side-effects that
  752. /// can't be modeled.
  753. EM_IgnoreSideEffects,
  754. } EvalMode;
  755. /// Are we checking whether the expression is a potential constant
  756. /// expression?
  757. bool checkingPotentialConstantExpression() const override {
  758. return CheckingPotentialConstantExpression;
  759. }
  760. /// Are we checking an expression for overflow?
  761. // FIXME: We should check for any kind of undefined or suspicious behavior
  762. // in such constructs, not just overflow.
  763. bool checkingForUndefinedBehavior() const override {
  764. return CheckingForUndefinedBehavior;
  765. }
  766. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  767. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  768. CallStackDepth(0), NextCallIndex(1),
  769. StepsLeft(getLangOpts().ConstexprStepLimit),
  770. ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
  771. EnableNewConstInterp(ForceNewConstInterp ||
  772. getLangOpts().EnableNewConstInterp),
  773. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  774. EvaluatingDecl((const ValueDecl *)nullptr),
  775. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  776. HasFoldFailureDiagnostic(false), InConstantContext(false),
  777. EvalMode(Mode) {}
  778. ~EvalInfo() {
  779. discardCleanups();
  780. }
  781. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  782. EvaluatingDecl = Base;
  783. EvaluatingDeclValue = &Value;
  784. }
  785. bool CheckCallLimit(SourceLocation Loc) {
  786. // Don't perform any constexpr calls (other than the call we're checking)
  787. // when checking a potential constant expression.
  788. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  789. return false;
  790. if (NextCallIndex == 0) {
  791. // NextCallIndex has wrapped around.
  792. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  793. return false;
  794. }
  795. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  796. return true;
  797. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  798. << getLangOpts().ConstexprCallDepth;
  799. return false;
  800. }
  801. std::pair<CallStackFrame *, unsigned>
  802. getCallFrameAndDepth(unsigned CallIndex) {
  803. assert(CallIndex && "no call index in getCallFrameAndDepth");
  804. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  805. // be null in this loop.
  806. unsigned Depth = CallStackDepth;
  807. CallStackFrame *Frame = CurrentCall;
  808. while (Frame->Index > CallIndex) {
  809. Frame = Frame->Caller;
  810. --Depth;
  811. }
  812. if (Frame->Index == CallIndex)
  813. return {Frame, Depth};
  814. return {nullptr, 0};
  815. }
  816. bool nextStep(const Stmt *S) {
  817. if (!StepsLeft) {
  818. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  819. return false;
  820. }
  821. --StepsLeft;
  822. return true;
  823. }
  824. APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
  825. Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
  826. Optional<DynAlloc*> Result;
  827. auto It = HeapAllocs.find(DA);
  828. if (It != HeapAllocs.end())
  829. Result = &It->second;
  830. return Result;
  831. }
  832. void performLifetimeExtension() {
  833. // Disable the cleanups for lifetime-extended temporaries.
  834. CleanupStack.erase(
  835. std::remove_if(CleanupStack.begin(), CleanupStack.end(),
  836. [](Cleanup &C) { return C.isLifetimeExtended(); }),
  837. CleanupStack.end());
  838. }
  839. /// Throw away any remaining cleanups at the end of evaluation. If any
  840. /// cleanups would have had a side-effect, note that as an unmodeled
  841. /// side-effect and return false. Otherwise, return true.
  842. bool discardCleanups() {
  843. for (Cleanup &C : CleanupStack)
  844. if (C.hasSideEffect())
  845. if (!noteSideEffect())
  846. return false;
  847. return true;
  848. }
  849. private:
  850. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  851. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  852. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  853. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  854. void setFoldFailureDiagnostic(bool Flag) override {
  855. HasFoldFailureDiagnostic = Flag;
  856. }
  857. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  858. ASTContext &getCtx() const override { return Ctx; }
  859. // If we have a prior diagnostic, it will be noting that the expression
  860. // isn't a constant expression. This diagnostic is more important,
  861. // unless we require this evaluation to produce a constant expression.
  862. //
  863. // FIXME: We might want to show both diagnostics to the user in
  864. // EM_ConstantFold mode.
  865. bool hasPriorDiagnostic() override {
  866. if (!EvalStatus.Diag->empty()) {
  867. switch (EvalMode) {
  868. case EM_ConstantFold:
  869. case EM_IgnoreSideEffects:
  870. if (!HasFoldFailureDiagnostic)
  871. break;
  872. // We've already failed to fold something. Keep that diagnostic.
  873. LLVM_FALLTHROUGH;
  874. case EM_ConstantExpression:
  875. case EM_ConstantExpressionUnevaluated:
  876. setActiveDiagnostic(false);
  877. return true;
  878. }
  879. }
  880. return false;
  881. }
  882. unsigned getCallStackDepth() override { return CallStackDepth; }
  883. public:
  884. /// Should we continue evaluation after encountering a side-effect that we
  885. /// couldn't model?
  886. bool keepEvaluatingAfterSideEffect() {
  887. switch (EvalMode) {
  888. case EM_IgnoreSideEffects:
  889. return true;
  890. case EM_ConstantExpression:
  891. case EM_ConstantExpressionUnevaluated:
  892. case EM_ConstantFold:
  893. // By default, assume any side effect might be valid in some other
  894. // evaluation of this expression from a different context.
  895. return checkingPotentialConstantExpression() ||
  896. checkingForUndefinedBehavior();
  897. }
  898. llvm_unreachable("Missed EvalMode case");
  899. }
  900. /// Note that we have had a side-effect, and determine whether we should
  901. /// keep evaluating.
  902. bool noteSideEffect() {
  903. EvalStatus.HasSideEffects = true;
  904. return keepEvaluatingAfterSideEffect();
  905. }
  906. /// Should we continue evaluation after encountering undefined behavior?
  907. bool keepEvaluatingAfterUndefinedBehavior() {
  908. switch (EvalMode) {
  909. case EM_IgnoreSideEffects:
  910. case EM_ConstantFold:
  911. return true;
  912. case EM_ConstantExpression:
  913. case EM_ConstantExpressionUnevaluated:
  914. return checkingForUndefinedBehavior();
  915. }
  916. llvm_unreachable("Missed EvalMode case");
  917. }
  918. /// Note that we hit something that was technically undefined behavior, but
  919. /// that we can evaluate past it (such as signed overflow or floating-point
  920. /// division by zero.)
  921. bool noteUndefinedBehavior() override {
  922. EvalStatus.HasUndefinedBehavior = true;
  923. return keepEvaluatingAfterUndefinedBehavior();
  924. }
  925. /// Should we continue evaluation as much as possible after encountering a
  926. /// construct which can't be reduced to a value?
  927. bool keepEvaluatingAfterFailure() const override {
  928. if (!StepsLeft)
  929. return false;
  930. switch (EvalMode) {
  931. case EM_ConstantExpression:
  932. case EM_ConstantExpressionUnevaluated:
  933. case EM_ConstantFold:
  934. case EM_IgnoreSideEffects:
  935. return checkingPotentialConstantExpression() ||
  936. checkingForUndefinedBehavior();
  937. }
  938. llvm_unreachable("Missed EvalMode case");
  939. }
  940. /// Notes that we failed to evaluate an expression that other expressions
  941. /// directly depend on, and determine if we should keep evaluating. This
  942. /// should only be called if we actually intend to keep evaluating.
  943. ///
  944. /// Call noteSideEffect() instead if we may be able to ignore the value that
  945. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  946. ///
  947. /// (Foo(), 1) // use noteSideEffect
  948. /// (Foo() || true) // use noteSideEffect
  949. /// Foo() + 1 // use noteFailure
  950. LLVM_NODISCARD bool noteFailure() {
  951. // Failure when evaluating some expression often means there is some
  952. // subexpression whose evaluation was skipped. Therefore, (because we
  953. // don't track whether we skipped an expression when unwinding after an
  954. // evaluation failure) every evaluation failure that bubbles up from a
  955. // subexpression implies that a side-effect has potentially happened. We
  956. // skip setting the HasSideEffects flag to true until we decide to
  957. // continue evaluating after that point, which happens here.
  958. bool KeepGoing = keepEvaluatingAfterFailure();
  959. EvalStatus.HasSideEffects |= KeepGoing;
  960. return KeepGoing;
  961. }
  962. class ArrayInitLoopIndex {
  963. EvalInfo &Info;
  964. uint64_t OuterIndex;
  965. public:
  966. ArrayInitLoopIndex(EvalInfo &Info)
  967. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  968. Info.ArrayInitIndex = 0;
  969. }
  970. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  971. operator uint64_t&() { return Info.ArrayInitIndex; }
  972. };
  973. };
  974. /// Object used to treat all foldable expressions as constant expressions.
  975. struct FoldConstant {
  976. EvalInfo &Info;
  977. bool Enabled;
  978. bool HadNoPriorDiags;
  979. EvalInfo::EvaluationMode OldMode;
  980. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  981. : Info(Info),
  982. Enabled(Enabled),
  983. HadNoPriorDiags(Info.EvalStatus.Diag &&
  984. Info.EvalStatus.Diag->empty() &&
  985. !Info.EvalStatus.HasSideEffects),
  986. OldMode(Info.EvalMode) {
  987. if (Enabled)
  988. Info.EvalMode = EvalInfo::EM_ConstantFold;
  989. }
  990. void keepDiagnostics() { Enabled = false; }
  991. ~FoldConstant() {
  992. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  993. !Info.EvalStatus.HasSideEffects)
  994. Info.EvalStatus.Diag->clear();
  995. Info.EvalMode = OldMode;
  996. }
  997. };
  998. /// RAII object used to set the current evaluation mode to ignore
  999. /// side-effects.
  1000. struct IgnoreSideEffectsRAII {
  1001. EvalInfo &Info;
  1002. EvalInfo::EvaluationMode OldMode;
  1003. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1004. : Info(Info), OldMode(Info.EvalMode) {
  1005. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1006. }
  1007. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1008. };
  1009. /// RAII object used to optionally suppress diagnostics and side-effects from
  1010. /// a speculative evaluation.
  1011. class SpeculativeEvaluationRAII {
  1012. EvalInfo *Info = nullptr;
  1013. Expr::EvalStatus OldStatus;
  1014. unsigned OldSpeculativeEvaluationDepth;
  1015. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1016. Info = Other.Info;
  1017. OldStatus = Other.OldStatus;
  1018. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1019. Other.Info = nullptr;
  1020. }
  1021. void maybeRestoreState() {
  1022. if (!Info)
  1023. return;
  1024. Info->EvalStatus = OldStatus;
  1025. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1026. }
  1027. public:
  1028. SpeculativeEvaluationRAII() = default;
  1029. SpeculativeEvaluationRAII(
  1030. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1031. : Info(&Info), OldStatus(Info.EvalStatus),
  1032. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1033. Info.EvalStatus.Diag = NewDiag;
  1034. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1035. }
  1036. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1037. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1038. moveFromAndCancel(std::move(Other));
  1039. }
  1040. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1041. maybeRestoreState();
  1042. moveFromAndCancel(std::move(Other));
  1043. return *this;
  1044. }
  1045. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1046. };
  1047. /// RAII object wrapping a full-expression or block scope, and handling
  1048. /// the ending of the lifetime of temporaries created within it.
  1049. template<bool IsFullExpression>
  1050. class ScopeRAII {
  1051. EvalInfo &Info;
  1052. unsigned OldStackSize;
  1053. public:
  1054. ScopeRAII(EvalInfo &Info)
  1055. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1056. // Push a new temporary version. This is needed to distinguish between
  1057. // temporaries created in different iterations of a loop.
  1058. Info.CurrentCall->pushTempVersion();
  1059. }
  1060. bool destroy(bool RunDestructors = true) {
  1061. bool OK = cleanup(Info, RunDestructors, OldStackSize);
  1062. OldStackSize = -1U;
  1063. return OK;
  1064. }
  1065. ~ScopeRAII() {
  1066. if (OldStackSize != -1U)
  1067. destroy(false);
  1068. // Body moved to a static method to encourage the compiler to inline away
  1069. // instances of this class.
  1070. Info.CurrentCall->popTempVersion();
  1071. }
  1072. private:
  1073. static bool cleanup(EvalInfo &Info, bool RunDestructors,
  1074. unsigned OldStackSize) {
  1075. assert(OldStackSize <= Info.CleanupStack.size() &&
  1076. "running cleanups out of order?");
  1077. // Run all cleanups for a block scope, and non-lifetime-extended cleanups
  1078. // for a full-expression scope.
  1079. for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
  1080. if (!(IsFullExpression &&
  1081. Info.CleanupStack[I - 1].isLifetimeExtended())) {
  1082. if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors))
  1083. return false;
  1084. }
  1085. }
  1086. // Compact lifetime-extended cleanups.
  1087. auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
  1088. if (IsFullExpression)
  1089. NewEnd =
  1090. std::remove_if(NewEnd, Info.CleanupStack.end(),
  1091. [](Cleanup &C) { return !C.isLifetimeExtended(); });
  1092. Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
  1093. return true;
  1094. }
  1095. };
  1096. typedef ScopeRAII<false> BlockScopeRAII;
  1097. typedef ScopeRAII<true> FullExpressionRAII;
  1098. }
  1099. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1100. CheckSubobjectKind CSK) {
  1101. if (Invalid)
  1102. return false;
  1103. if (isOnePastTheEnd()) {
  1104. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1105. << CSK;
  1106. setInvalid();
  1107. return false;
  1108. }
  1109. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1110. // must actually be at least one array element; even a VLA cannot have a
  1111. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1112. return true;
  1113. }
  1114. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1115. const Expr *E) {
  1116. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1117. // Do not set the designator as invalid: we can represent this situation,
  1118. // and correct handling of __builtin_object_size requires us to do so.
  1119. }
  1120. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1121. const Expr *E,
  1122. const APSInt &N) {
  1123. // If we're complaining, we must be able to statically determine the size of
  1124. // the most derived array.
  1125. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1126. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1127. << N << /*array*/ 0
  1128. << static_cast<unsigned>(getMostDerivedArraySize());
  1129. else
  1130. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1131. << N << /*non-array*/ 1;
  1132. setInvalid();
  1133. }
  1134. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1135. const FunctionDecl *Callee, const LValue *This,
  1136. APValue *Arguments)
  1137. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1138. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1139. Info.CurrentCall = this;
  1140. ++Info.CallStackDepth;
  1141. }
  1142. CallStackFrame::~CallStackFrame() {
  1143. assert(Info.CurrentCall == this && "calls retired out of order");
  1144. --Info.CallStackDepth;
  1145. Info.CurrentCall = Caller;
  1146. }
  1147. static bool isRead(AccessKinds AK) {
  1148. return AK == AK_Read || AK == AK_ReadObjectRepresentation;
  1149. }
  1150. static bool isModification(AccessKinds AK) {
  1151. switch (AK) {
  1152. case AK_Read:
  1153. case AK_ReadObjectRepresentation:
  1154. case AK_MemberCall:
  1155. case AK_DynamicCast:
  1156. case AK_TypeId:
  1157. return false;
  1158. case AK_Assign:
  1159. case AK_Increment:
  1160. case AK_Decrement:
  1161. return true;
  1162. }
  1163. llvm_unreachable("unknown access kind");
  1164. }
  1165. /// Is this an access per the C++ definition?
  1166. static bool isFormalAccess(AccessKinds AK) {
  1167. return isRead(AK) || isModification(AK);
  1168. }
  1169. namespace {
  1170. struct ComplexValue {
  1171. private:
  1172. bool IsInt;
  1173. public:
  1174. APSInt IntReal, IntImag;
  1175. APFloat FloatReal, FloatImag;
  1176. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1177. void makeComplexFloat() { IsInt = false; }
  1178. bool isComplexFloat() const { return !IsInt; }
  1179. APFloat &getComplexFloatReal() { return FloatReal; }
  1180. APFloat &getComplexFloatImag() { return FloatImag; }
  1181. void makeComplexInt() { IsInt = true; }
  1182. bool isComplexInt() const { return IsInt; }
  1183. APSInt &getComplexIntReal() { return IntReal; }
  1184. APSInt &getComplexIntImag() { return IntImag; }
  1185. void moveInto(APValue &v) const {
  1186. if (isComplexFloat())
  1187. v = APValue(FloatReal, FloatImag);
  1188. else
  1189. v = APValue(IntReal, IntImag);
  1190. }
  1191. void setFrom(const APValue &v) {
  1192. assert(v.isComplexFloat() || v.isComplexInt());
  1193. if (v.isComplexFloat()) {
  1194. makeComplexFloat();
  1195. FloatReal = v.getComplexFloatReal();
  1196. FloatImag = v.getComplexFloatImag();
  1197. } else {
  1198. makeComplexInt();
  1199. IntReal = v.getComplexIntReal();
  1200. IntImag = v.getComplexIntImag();
  1201. }
  1202. }
  1203. };
  1204. struct LValue {
  1205. APValue::LValueBase Base;
  1206. CharUnits Offset;
  1207. SubobjectDesignator Designator;
  1208. bool IsNullPtr : 1;
  1209. bool InvalidBase : 1;
  1210. const APValue::LValueBase getLValueBase() const { return Base; }
  1211. CharUnits &getLValueOffset() { return Offset; }
  1212. const CharUnits &getLValueOffset() const { return Offset; }
  1213. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1214. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1215. bool isNullPointer() const { return IsNullPtr;}
  1216. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1217. unsigned getLValueVersion() const { return Base.getVersion(); }
  1218. void moveInto(APValue &V) const {
  1219. if (Designator.Invalid)
  1220. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1221. else {
  1222. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1223. V = APValue(Base, Offset, Designator.Entries,
  1224. Designator.IsOnePastTheEnd, IsNullPtr);
  1225. }
  1226. }
  1227. void setFrom(ASTContext &Ctx, const APValue &V) {
  1228. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1229. Base = V.getLValueBase();
  1230. Offset = V.getLValueOffset();
  1231. InvalidBase = false;
  1232. Designator = SubobjectDesignator(Ctx, V);
  1233. IsNullPtr = V.isNullPointer();
  1234. }
  1235. void set(APValue::LValueBase B, bool BInvalid = false) {
  1236. #ifndef NDEBUG
  1237. // We only allow a few types of invalid bases. Enforce that here.
  1238. if (BInvalid) {
  1239. const auto *E = B.get<const Expr *>();
  1240. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1241. "Unexpected type of invalid base");
  1242. }
  1243. #endif
  1244. Base = B;
  1245. Offset = CharUnits::fromQuantity(0);
  1246. InvalidBase = BInvalid;
  1247. Designator = SubobjectDesignator(getType(B));
  1248. IsNullPtr = false;
  1249. }
  1250. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1251. Base = (Expr *)nullptr;
  1252. Offset = CharUnits::fromQuantity(TargetVal);
  1253. InvalidBase = false;
  1254. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1255. IsNullPtr = true;
  1256. }
  1257. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1258. set(B, true);
  1259. }
  1260. private:
  1261. // Check that this LValue is not based on a null pointer. If it is, produce
  1262. // a diagnostic and mark the designator as invalid.
  1263. template <typename GenDiagType>
  1264. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1265. if (Designator.Invalid)
  1266. return false;
  1267. if (IsNullPtr) {
  1268. GenDiag();
  1269. Designator.setInvalid();
  1270. return false;
  1271. }
  1272. return true;
  1273. }
  1274. public:
  1275. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1276. CheckSubobjectKind CSK) {
  1277. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1278. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1279. });
  1280. }
  1281. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1282. AccessKinds AK) {
  1283. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1284. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1285. });
  1286. }
  1287. // Check this LValue refers to an object. If not, set the designator to be
  1288. // invalid and emit a diagnostic.
  1289. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1290. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1291. Designator.checkSubobject(Info, E, CSK);
  1292. }
  1293. void addDecl(EvalInfo &Info, const Expr *E,
  1294. const Decl *D, bool Virtual = false) {
  1295. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1296. Designator.addDeclUnchecked(D, Virtual);
  1297. }
  1298. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1299. if (!Designator.Entries.empty()) {
  1300. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1301. Designator.setInvalid();
  1302. return;
  1303. }
  1304. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1305. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1306. Designator.FirstEntryIsAnUnsizedArray = true;
  1307. Designator.addUnsizedArrayUnchecked(ElemTy);
  1308. }
  1309. }
  1310. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1311. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1312. Designator.addArrayUnchecked(CAT);
  1313. }
  1314. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1315. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1316. Designator.addComplexUnchecked(EltTy, Imag);
  1317. }
  1318. void clearIsNullPointer() {
  1319. IsNullPtr = false;
  1320. }
  1321. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1322. const APSInt &Index, CharUnits ElementSize) {
  1323. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1324. // but we're not required to diagnose it and it's valid in C++.)
  1325. if (!Index)
  1326. return;
  1327. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1328. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1329. // offsets.
  1330. uint64_t Offset64 = Offset.getQuantity();
  1331. uint64_t ElemSize64 = ElementSize.getQuantity();
  1332. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1333. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1334. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1335. Designator.adjustIndex(Info, E, Index);
  1336. clearIsNullPointer();
  1337. }
  1338. void adjustOffset(CharUnits N) {
  1339. Offset += N;
  1340. if (N.getQuantity())
  1341. clearIsNullPointer();
  1342. }
  1343. };
  1344. struct MemberPtr {
  1345. MemberPtr() {}
  1346. explicit MemberPtr(const ValueDecl *Decl) :
  1347. DeclAndIsDerivedMember(Decl, false), Path() {}
  1348. /// The member or (direct or indirect) field referred to by this member
  1349. /// pointer, or 0 if this is a null member pointer.
  1350. const ValueDecl *getDecl() const {
  1351. return DeclAndIsDerivedMember.getPointer();
  1352. }
  1353. /// Is this actually a member of some type derived from the relevant class?
  1354. bool isDerivedMember() const {
  1355. return DeclAndIsDerivedMember.getInt();
  1356. }
  1357. /// Get the class which the declaration actually lives in.
  1358. const CXXRecordDecl *getContainingRecord() const {
  1359. return cast<CXXRecordDecl>(
  1360. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1361. }
  1362. void moveInto(APValue &V) const {
  1363. V = APValue(getDecl(), isDerivedMember(), Path);
  1364. }
  1365. void setFrom(const APValue &V) {
  1366. assert(V.isMemberPointer());
  1367. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1368. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1369. Path.clear();
  1370. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1371. Path.insert(Path.end(), P.begin(), P.end());
  1372. }
  1373. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1374. /// whether the member is a member of some class derived from the class type
  1375. /// of the member pointer.
  1376. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1377. /// Path - The path of base/derived classes from the member declaration's
  1378. /// class (exclusive) to the class type of the member pointer (inclusive).
  1379. SmallVector<const CXXRecordDecl*, 4> Path;
  1380. /// Perform a cast towards the class of the Decl (either up or down the
  1381. /// hierarchy).
  1382. bool castBack(const CXXRecordDecl *Class) {
  1383. assert(!Path.empty());
  1384. const CXXRecordDecl *Expected;
  1385. if (Path.size() >= 2)
  1386. Expected = Path[Path.size() - 2];
  1387. else
  1388. Expected = getContainingRecord();
  1389. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1390. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1391. // if B does not contain the original member and is not a base or
  1392. // derived class of the class containing the original member, the result
  1393. // of the cast is undefined.
  1394. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1395. // (D::*). We consider that to be a language defect.
  1396. return false;
  1397. }
  1398. Path.pop_back();
  1399. return true;
  1400. }
  1401. /// Perform a base-to-derived member pointer cast.
  1402. bool castToDerived(const CXXRecordDecl *Derived) {
  1403. if (!getDecl())
  1404. return true;
  1405. if (!isDerivedMember()) {
  1406. Path.push_back(Derived);
  1407. return true;
  1408. }
  1409. if (!castBack(Derived))
  1410. return false;
  1411. if (Path.empty())
  1412. DeclAndIsDerivedMember.setInt(false);
  1413. return true;
  1414. }
  1415. /// Perform a derived-to-base member pointer cast.
  1416. bool castToBase(const CXXRecordDecl *Base) {
  1417. if (!getDecl())
  1418. return true;
  1419. if (Path.empty())
  1420. DeclAndIsDerivedMember.setInt(true);
  1421. if (isDerivedMember()) {
  1422. Path.push_back(Base);
  1423. return true;
  1424. }
  1425. return castBack(Base);
  1426. }
  1427. };
  1428. /// Compare two member pointers, which are assumed to be of the same type.
  1429. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1430. if (!LHS.getDecl() || !RHS.getDecl())
  1431. return !LHS.getDecl() && !RHS.getDecl();
  1432. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1433. return false;
  1434. return LHS.Path == RHS.Path;
  1435. }
  1436. }
  1437. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1438. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1439. const LValue &This, const Expr *E,
  1440. bool AllowNonLiteralTypes = false);
  1441. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1442. bool InvalidBaseOK = false);
  1443. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1444. bool InvalidBaseOK = false);
  1445. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1446. EvalInfo &Info);
  1447. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1448. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1449. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1450. EvalInfo &Info);
  1451. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1452. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1453. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1454. EvalInfo &Info);
  1455. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1456. /// Evaluate an integer or fixed point expression into an APResult.
  1457. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1458. EvalInfo &Info);
  1459. /// Evaluate only a fixed point expression into an APResult.
  1460. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1461. EvalInfo &Info);
  1462. //===----------------------------------------------------------------------===//
  1463. // Misc utilities
  1464. //===----------------------------------------------------------------------===//
  1465. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1466. /// preserving its value (by extending by up to one bit as needed).
  1467. static void negateAsSigned(APSInt &Int) {
  1468. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1469. Int = Int.extend(Int.getBitWidth() + 1);
  1470. Int.setIsSigned(true);
  1471. }
  1472. Int = -Int;
  1473. }
  1474. template<typename KeyT>
  1475. APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
  1476. bool IsLifetimeExtended, LValue &LV) {
  1477. unsigned Version = getTempVersion();
  1478. APValue::LValueBase Base(Key, Index, Version);
  1479. LV.set(Base);
  1480. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1481. assert(Result.isAbsent() && "temporary created multiple times");
  1482. // If we're creating a temporary immediately in the operand of a speculative
  1483. // evaluation, don't register a cleanup to be run outside the speculative
  1484. // evaluation context, since we won't actually be able to initialize this
  1485. // object.
  1486. if (Index <= Info.SpeculativeEvaluationDepth) {
  1487. if (T.isDestructedType())
  1488. Info.noteSideEffect();
  1489. } else {
  1490. Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
  1491. }
  1492. return Result;
  1493. }
  1494. APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
  1495. if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
  1496. FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
  1497. return nullptr;
  1498. }
  1499. DynamicAllocLValue DA(NumHeapAllocs++);
  1500. LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
  1501. auto Result = HeapAllocs.emplace(std::piecewise_construct,
  1502. std::forward_as_tuple(DA), std::tuple<>());
  1503. assert(Result.second && "reused a heap alloc index?");
  1504. Result.first->second.AllocExpr = E;
  1505. return &Result.first->second.Value;
  1506. }
  1507. /// Produce a string describing the given constexpr call.
  1508. void CallStackFrame::describe(raw_ostream &Out) {
  1509. unsigned ArgIndex = 0;
  1510. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1511. !isa<CXXConstructorDecl>(Callee) &&
  1512. cast<CXXMethodDecl>(Callee)->isInstance();
  1513. if (!IsMemberCall)
  1514. Out << *Callee << '(';
  1515. if (This && IsMemberCall) {
  1516. APValue Val;
  1517. This->moveInto(Val);
  1518. Val.printPretty(Out, Info.Ctx,
  1519. This->Designator.MostDerivedType);
  1520. // FIXME: Add parens around Val if needed.
  1521. Out << "->" << *Callee << '(';
  1522. IsMemberCall = false;
  1523. }
  1524. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1525. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1526. if (ArgIndex > (unsigned)IsMemberCall)
  1527. Out << ", ";
  1528. const ParmVarDecl *Param = *I;
  1529. const APValue &Arg = Arguments[ArgIndex];
  1530. Arg.printPretty(Out, Info.Ctx, Param->getType());
  1531. if (ArgIndex == 0 && IsMemberCall)
  1532. Out << "->" << *Callee << '(';
  1533. }
  1534. Out << ')';
  1535. }
  1536. /// Evaluate an expression to see if it had side-effects, and discard its
  1537. /// result.
  1538. /// \return \c true if the caller should keep evaluating.
  1539. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1540. APValue Scratch;
  1541. if (!Evaluate(Scratch, Info, E))
  1542. // We don't need the value, but we might have skipped a side effect here.
  1543. return Info.noteSideEffect();
  1544. return true;
  1545. }
  1546. /// Should this call expression be treated as a string literal?
  1547. static bool IsStringLiteralCall(const CallExpr *E) {
  1548. unsigned Builtin = E->getBuiltinCallee();
  1549. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1550. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1551. }
  1552. static bool IsGlobalLValue(APValue::LValueBase B) {
  1553. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1554. // constant expression of pointer type that evaluates to...
  1555. // ... a null pointer value, or a prvalue core constant expression of type
  1556. // std::nullptr_t.
  1557. if (!B) return true;
  1558. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1559. // ... the address of an object with static storage duration,
  1560. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1561. return VD->hasGlobalStorage();
  1562. // ... the address of a function,
  1563. return isa<FunctionDecl>(D);
  1564. }
  1565. if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
  1566. return true;
  1567. const Expr *E = B.get<const Expr*>();
  1568. switch (E->getStmtClass()) {
  1569. default:
  1570. return false;
  1571. case Expr::CompoundLiteralExprClass: {
  1572. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1573. return CLE->isFileScope() && CLE->isLValue();
  1574. }
  1575. case Expr::MaterializeTemporaryExprClass:
  1576. // A materialized temporary might have been lifetime-extended to static
  1577. // storage duration.
  1578. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1579. // A string literal has static storage duration.
  1580. case Expr::StringLiteralClass:
  1581. case Expr::PredefinedExprClass:
  1582. case Expr::ObjCStringLiteralClass:
  1583. case Expr::ObjCEncodeExprClass:
  1584. case Expr::CXXUuidofExprClass:
  1585. return true;
  1586. case Expr::ObjCBoxedExprClass:
  1587. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1588. case Expr::CallExprClass:
  1589. return IsStringLiteralCall(cast<CallExpr>(E));
  1590. // For GCC compatibility, &&label has static storage duration.
  1591. case Expr::AddrLabelExprClass:
  1592. return true;
  1593. // A Block literal expression may be used as the initialization value for
  1594. // Block variables at global or local static scope.
  1595. case Expr::BlockExprClass:
  1596. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1597. case Expr::ImplicitValueInitExprClass:
  1598. // FIXME:
  1599. // We can never form an lvalue with an implicit value initialization as its
  1600. // base through expression evaluation, so these only appear in one case: the
  1601. // implicit variable declaration we invent when checking whether a constexpr
  1602. // constructor can produce a constant expression. We must assume that such
  1603. // an expression might be a global lvalue.
  1604. return true;
  1605. }
  1606. }
  1607. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1608. return LVal.Base.dyn_cast<const ValueDecl*>();
  1609. }
  1610. static bool IsLiteralLValue(const LValue &Value) {
  1611. if (Value.getLValueCallIndex())
  1612. return false;
  1613. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1614. return E && !isa<MaterializeTemporaryExpr>(E);
  1615. }
  1616. static bool IsWeakLValue(const LValue &Value) {
  1617. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1618. return Decl && Decl->isWeak();
  1619. }
  1620. static bool isZeroSized(const LValue &Value) {
  1621. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1622. if (Decl && isa<VarDecl>(Decl)) {
  1623. QualType Ty = Decl->getType();
  1624. if (Ty->isArrayType())
  1625. return Ty->isIncompleteType() ||
  1626. Decl->getASTContext().getTypeSize(Ty) == 0;
  1627. }
  1628. return false;
  1629. }
  1630. static bool HasSameBase(const LValue &A, const LValue &B) {
  1631. if (!A.getLValueBase())
  1632. return !B.getLValueBase();
  1633. if (!B.getLValueBase())
  1634. return false;
  1635. if (A.getLValueBase().getOpaqueValue() !=
  1636. B.getLValueBase().getOpaqueValue()) {
  1637. const Decl *ADecl = GetLValueBaseDecl(A);
  1638. if (!ADecl)
  1639. return false;
  1640. const Decl *BDecl = GetLValueBaseDecl(B);
  1641. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1642. return false;
  1643. }
  1644. return IsGlobalLValue(A.getLValueBase()) ||
  1645. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1646. A.getLValueVersion() == B.getLValueVersion());
  1647. }
  1648. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1649. assert(Base && "no location for a null lvalue");
  1650. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1651. if (VD)
  1652. Info.Note(VD->getLocation(), diag::note_declared_at);
  1653. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1654. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1655. else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  1656. // FIXME: Produce a note for dangling pointers too.
  1657. if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
  1658. Info.Note((*Alloc)->AllocExpr->getExprLoc(),
  1659. diag::note_constexpr_dynamic_alloc_here);
  1660. }
  1661. // We have no information to show for a typeid(T) object.
  1662. }
  1663. /// Check that this reference or pointer core constant expression is a valid
  1664. /// value for an address or reference constant expression. Return true if we
  1665. /// can fold this expression, whether or not it's a constant expression.
  1666. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1667. QualType Type, const LValue &LVal,
  1668. Expr::ConstExprUsage Usage) {
  1669. bool IsReferenceType = Type->isReferenceType();
  1670. APValue::LValueBase Base = LVal.getLValueBase();
  1671. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1672. // Check that the object is a global. Note that the fake 'this' object we
  1673. // manufacture when checking potential constant expressions is conservatively
  1674. // assumed to be global here.
  1675. if (!IsGlobalLValue(Base)) {
  1676. if (Info.getLangOpts().CPlusPlus11) {
  1677. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1678. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1679. << IsReferenceType << !Designator.Entries.empty()
  1680. << !!VD << VD;
  1681. NoteLValueLocation(Info, Base);
  1682. } else {
  1683. Info.FFDiag(Loc);
  1684. }
  1685. // Don't allow references to temporaries to escape.
  1686. return false;
  1687. }
  1688. assert((Info.checkingPotentialConstantExpression() ||
  1689. LVal.getLValueCallIndex() == 0) &&
  1690. "have call index for global lvalue");
  1691. if (Base.is<DynamicAllocLValue>()) {
  1692. Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
  1693. << IsReferenceType << !Designator.Entries.empty();
  1694. NoteLValueLocation(Info, Base);
  1695. return false;
  1696. }
  1697. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1698. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1699. // Check if this is a thread-local variable.
  1700. if (Var->getTLSKind())
  1701. // FIXME: Diagnostic!
  1702. return false;
  1703. // A dllimport variable never acts like a constant.
  1704. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1705. // FIXME: Diagnostic!
  1706. return false;
  1707. }
  1708. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1709. // __declspec(dllimport) must be handled very carefully:
  1710. // We must never initialize an expression with the thunk in C++.
  1711. // Doing otherwise would allow the same id-expression to yield
  1712. // different addresses for the same function in different translation
  1713. // units. However, this means that we must dynamically initialize the
  1714. // expression with the contents of the import address table at runtime.
  1715. //
  1716. // The C language has no notion of ODR; furthermore, it has no notion of
  1717. // dynamic initialization. This means that we are permitted to
  1718. // perform initialization with the address of the thunk.
  1719. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1720. FD->hasAttr<DLLImportAttr>())
  1721. // FIXME: Diagnostic!
  1722. return false;
  1723. }
  1724. }
  1725. // Allow address constant expressions to be past-the-end pointers. This is
  1726. // an extension: the standard requires them to point to an object.
  1727. if (!IsReferenceType)
  1728. return true;
  1729. // A reference constant expression must refer to an object.
  1730. if (!Base) {
  1731. // FIXME: diagnostic
  1732. Info.CCEDiag(Loc);
  1733. return true;
  1734. }
  1735. // Does this refer one past the end of some object?
  1736. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1737. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1738. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1739. << !Designator.Entries.empty() << !!VD << VD;
  1740. NoteLValueLocation(Info, Base);
  1741. }
  1742. return true;
  1743. }
  1744. /// Member pointers are constant expressions unless they point to a
  1745. /// non-virtual dllimport member function.
  1746. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1747. SourceLocation Loc,
  1748. QualType Type,
  1749. const APValue &Value,
  1750. Expr::ConstExprUsage Usage) {
  1751. const ValueDecl *Member = Value.getMemberPointerDecl();
  1752. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1753. if (!FD)
  1754. return true;
  1755. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1756. !FD->hasAttr<DLLImportAttr>();
  1757. }
  1758. /// Check that this core constant expression is of literal type, and if not,
  1759. /// produce an appropriate diagnostic.
  1760. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1761. const LValue *This = nullptr) {
  1762. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1763. return true;
  1764. // C++1y: A constant initializer for an object o [...] may also invoke
  1765. // constexpr constructors for o and its subobjects even if those objects
  1766. // are of non-literal class types.
  1767. //
  1768. // C++11 missed this detail for aggregates, so classes like this:
  1769. // struct foo_t { union { int i; volatile int j; } u; };
  1770. // are not (obviously) initializable like so:
  1771. // __attribute__((__require_constant_initialization__))
  1772. // static const foo_t x = {{0}};
  1773. // because "i" is a subobject with non-literal initialization (due to the
  1774. // volatile member of the union). See:
  1775. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1776. // Therefore, we use the C++1y behavior.
  1777. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1778. return true;
  1779. // Prvalue constant expressions must be of literal types.
  1780. if (Info.getLangOpts().CPlusPlus11)
  1781. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1782. << E->getType();
  1783. else
  1784. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1785. return false;
  1786. }
  1787. enum class CheckEvaluationResultKind {
  1788. ConstantExpression,
  1789. FullyInitialized,
  1790. };
  1791. static bool
  1792. CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
  1793. SourceLocation DiagLoc, QualType Type,
  1794. const APValue &Value, Expr::ConstExprUsage Usage,
  1795. SourceLocation SubobjectLoc = SourceLocation()) {
  1796. if (!Value.hasValue()) {
  1797. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1798. << true << Type;
  1799. if (SubobjectLoc.isValid())
  1800. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1801. return false;
  1802. }
  1803. // We allow _Atomic(T) to be initialized from anything that T can be
  1804. // initialized from.
  1805. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1806. Type = AT->getValueType();
  1807. // Core issue 1454: For a literal constant expression of array or class type,
  1808. // each subobject of its value shall have been initialized by a constant
  1809. // expression.
  1810. if (Value.isArray()) {
  1811. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1812. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1813. if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1814. Value.getArrayInitializedElt(I), Usage,
  1815. SubobjectLoc))
  1816. return false;
  1817. }
  1818. if (!Value.hasArrayFiller())
  1819. return true;
  1820. return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1821. Value.getArrayFiller(), Usage, SubobjectLoc);
  1822. }
  1823. if (Value.isUnion() && Value.getUnionField()) {
  1824. return CheckEvaluationResult(
  1825. CERK, Info, DiagLoc, Value.getUnionField()->getType(),
  1826. Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
  1827. }
  1828. if (Value.isStruct()) {
  1829. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1830. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1831. unsigned BaseIndex = 0;
  1832. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1833. if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
  1834. Value.getStructBase(BaseIndex), Usage,
  1835. BS.getBeginLoc()))
  1836. return false;
  1837. ++BaseIndex;
  1838. }
  1839. }
  1840. for (const auto *I : RD->fields()) {
  1841. if (I->isUnnamedBitfield())
  1842. continue;
  1843. if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
  1844. Value.getStructField(I->getFieldIndex()),
  1845. Usage, I->getLocation()))
  1846. return false;
  1847. }
  1848. }
  1849. if (Value.isLValue() &&
  1850. CERK == CheckEvaluationResultKind::ConstantExpression) {
  1851. LValue LVal;
  1852. LVal.setFrom(Info.Ctx, Value);
  1853. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1854. }
  1855. if (Value.isMemberPointer() &&
  1856. CERK == CheckEvaluationResultKind::ConstantExpression)
  1857. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1858. // Everything else is fine.
  1859. return true;
  1860. }
  1861. /// Check that this core constant expression value is a valid value for a
  1862. /// constant expression. If not, report an appropriate diagnostic. Does not
  1863. /// check that the expression is of literal type.
  1864. static bool
  1865. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1866. const APValue &Value,
  1867. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1868. return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1869. Info, DiagLoc, Type, Value, Usage);
  1870. }
  1871. /// Check that this evaluated value is fully-initialized and can be loaded by
  1872. /// an lvalue-to-rvalue conversion.
  1873. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
  1874. QualType Type, const APValue &Value) {
  1875. return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
  1876. Info, DiagLoc, Type, Value,
  1877. Expr::EvaluateForCodeGen);
  1878. }
  1879. /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
  1880. /// "the allocated storage is deallocated within the evaluation".
  1881. static bool CheckMemoryLeaks(EvalInfo &Info) {
  1882. if (!Info.HeapAllocs.empty()) {
  1883. // We can still fold to a constant despite a compile-time memory leak,
  1884. // so long as the heap allocation isn't referenced in the result (we check
  1885. // that in CheckConstantExpression).
  1886. Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
  1887. diag::note_constexpr_memory_leak)
  1888. << unsigned(Info.HeapAllocs.size() - 1);
  1889. }
  1890. return true;
  1891. }
  1892. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1893. // A null base expression indicates a null pointer. These are always
  1894. // evaluatable, and they are false unless the offset is zero.
  1895. if (!Value.getLValueBase()) {
  1896. Result = !Value.getLValueOffset().isZero();
  1897. return true;
  1898. }
  1899. // We have a non-null base. These are generally known to be true, but if it's
  1900. // a weak declaration it can be null at runtime.
  1901. Result = true;
  1902. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1903. return !Decl || !Decl->isWeak();
  1904. }
  1905. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1906. switch (Val.getKind()) {
  1907. case APValue::None:
  1908. case APValue::Indeterminate:
  1909. return false;
  1910. case APValue::Int:
  1911. Result = Val.getInt().getBoolValue();
  1912. return true;
  1913. case APValue::FixedPoint:
  1914. Result = Val.getFixedPoint().getBoolValue();
  1915. return true;
  1916. case APValue::Float:
  1917. Result = !Val.getFloat().isZero();
  1918. return true;
  1919. case APValue::ComplexInt:
  1920. Result = Val.getComplexIntReal().getBoolValue() ||
  1921. Val.getComplexIntImag().getBoolValue();
  1922. return true;
  1923. case APValue::ComplexFloat:
  1924. Result = !Val.getComplexFloatReal().isZero() ||
  1925. !Val.getComplexFloatImag().isZero();
  1926. return true;
  1927. case APValue::LValue:
  1928. return EvalPointerValueAsBool(Val, Result);
  1929. case APValue::MemberPointer:
  1930. Result = Val.getMemberPointerDecl();
  1931. return true;
  1932. case APValue::Vector:
  1933. case APValue::Array:
  1934. case APValue::Struct:
  1935. case APValue::Union:
  1936. case APValue::AddrLabelDiff:
  1937. return false;
  1938. }
  1939. llvm_unreachable("unknown APValue kind");
  1940. }
  1941. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1942. EvalInfo &Info) {
  1943. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1944. APValue Val;
  1945. if (!Evaluate(Val, Info, E))
  1946. return false;
  1947. return HandleConversionToBool(Val, Result);
  1948. }
  1949. template<typename T>
  1950. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1951. const T &SrcValue, QualType DestType) {
  1952. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1953. << SrcValue << DestType;
  1954. return Info.noteUndefinedBehavior();
  1955. }
  1956. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1957. QualType SrcType, const APFloat &Value,
  1958. QualType DestType, APSInt &Result) {
  1959. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1960. // Determine whether we are converting to unsigned or signed.
  1961. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1962. Result = APSInt(DestWidth, !DestSigned);
  1963. bool ignored;
  1964. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1965. & APFloat::opInvalidOp)
  1966. return HandleOverflow(Info, E, Value, DestType);
  1967. return true;
  1968. }
  1969. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1970. QualType SrcType, QualType DestType,
  1971. APFloat &Result) {
  1972. APFloat Value = Result;
  1973. bool ignored;
  1974. Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1975. APFloat::rmNearestTiesToEven, &ignored);
  1976. return true;
  1977. }
  1978. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1979. QualType DestType, QualType SrcType,
  1980. const APSInt &Value) {
  1981. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1982. // Figure out if this is a truncate, extend or noop cast.
  1983. // If the input is signed, do a sign extend, noop, or truncate.
  1984. APSInt Result = Value.extOrTrunc(DestWidth);
  1985. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1986. if (DestType->isBooleanType())
  1987. Result = Value.getBoolValue();
  1988. return Result;
  1989. }
  1990. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1991. QualType SrcType, const APSInt &Value,
  1992. QualType DestType, APFloat &Result) {
  1993. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1994. Result.convertFromAPInt(Value, Value.isSigned(),
  1995. APFloat::rmNearestTiesToEven);
  1996. return true;
  1997. }
  1998. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1999. APValue &Value, const FieldDecl *FD) {
  2000. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  2001. if (!Value.isInt()) {
  2002. // Trying to store a pointer-cast-to-integer into a bitfield.
  2003. // FIXME: In this case, we should provide the diagnostic for casting
  2004. // a pointer to an integer.
  2005. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  2006. Info.FFDiag(E);
  2007. return false;
  2008. }
  2009. APSInt &Int = Value.getInt();
  2010. unsigned OldBitWidth = Int.getBitWidth();
  2011. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2012. if (NewBitWidth < OldBitWidth)
  2013. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2014. return true;
  2015. }
  2016. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2017. llvm::APInt &Res) {
  2018. APValue SVal;
  2019. if (!Evaluate(SVal, Info, E))
  2020. return false;
  2021. if (SVal.isInt()) {
  2022. Res = SVal.getInt();
  2023. return true;
  2024. }
  2025. if (SVal.isFloat()) {
  2026. Res = SVal.getFloat().bitcastToAPInt();
  2027. return true;
  2028. }
  2029. if (SVal.isVector()) {
  2030. QualType VecTy = E->getType();
  2031. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2032. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2033. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2034. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2035. Res = llvm::APInt::getNullValue(VecSize);
  2036. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2037. APValue &Elt = SVal.getVectorElt(i);
  2038. llvm::APInt EltAsInt;
  2039. if (Elt.isInt()) {
  2040. EltAsInt = Elt.getInt();
  2041. } else if (Elt.isFloat()) {
  2042. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2043. } else {
  2044. // Don't try to handle vectors of anything other than int or float
  2045. // (not sure if it's possible to hit this case).
  2046. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2047. return false;
  2048. }
  2049. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2050. if (BigEndian)
  2051. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2052. else
  2053. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2054. }
  2055. return true;
  2056. }
  2057. // Give up if the input isn't an int, float, or vector. For example, we
  2058. // reject "(v4i16)(intptr_t)&a".
  2059. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2060. return false;
  2061. }
  2062. /// Perform the given integer operation, which is known to need at most BitWidth
  2063. /// bits, and check for overflow in the original type (if that type was not an
  2064. /// unsigned type).
  2065. template<typename Operation>
  2066. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2067. const APSInt &LHS, const APSInt &RHS,
  2068. unsigned BitWidth, Operation Op,
  2069. APSInt &Result) {
  2070. if (LHS.isUnsigned()) {
  2071. Result = Op(LHS, RHS);
  2072. return true;
  2073. }
  2074. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2075. Result = Value.trunc(LHS.getBitWidth());
  2076. if (Result.extend(BitWidth) != Value) {
  2077. if (Info.checkingForUndefinedBehavior())
  2078. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2079. diag::warn_integer_constant_overflow)
  2080. << Result.toString(10) << E->getType();
  2081. else
  2082. return HandleOverflow(Info, E, Value, E->getType());
  2083. }
  2084. return true;
  2085. }
  2086. /// Perform the given binary integer operation.
  2087. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2088. BinaryOperatorKind Opcode, APSInt RHS,
  2089. APSInt &Result) {
  2090. switch (Opcode) {
  2091. default:
  2092. Info.FFDiag(E);
  2093. return false;
  2094. case BO_Mul:
  2095. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2096. std::multiplies<APSInt>(), Result);
  2097. case BO_Add:
  2098. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2099. std::plus<APSInt>(), Result);
  2100. case BO_Sub:
  2101. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2102. std::minus<APSInt>(), Result);
  2103. case BO_And: Result = LHS & RHS; return true;
  2104. case BO_Xor: Result = LHS ^ RHS; return true;
  2105. case BO_Or: Result = LHS | RHS; return true;
  2106. case BO_Div:
  2107. case BO_Rem:
  2108. if (RHS == 0) {
  2109. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2110. return false;
  2111. }
  2112. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2113. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2114. // this operation and gives the two's complement result.
  2115. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2116. LHS.isSigned() && LHS.isMinSignedValue())
  2117. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2118. E->getType());
  2119. return true;
  2120. case BO_Shl: {
  2121. if (Info.getLangOpts().OpenCL)
  2122. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2123. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2124. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2125. RHS.isUnsigned());
  2126. else if (RHS.isSigned() && RHS.isNegative()) {
  2127. // During constant-folding, a negative shift is an opposite shift. Such
  2128. // a shift is not a constant expression.
  2129. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2130. RHS = -RHS;
  2131. goto shift_right;
  2132. }
  2133. shift_left:
  2134. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2135. // the shifted type.
  2136. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2137. if (SA != RHS) {
  2138. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2139. << RHS << E->getType() << LHS.getBitWidth();
  2140. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
  2141. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2142. // operand, and must not overflow the corresponding unsigned type.
  2143. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2144. // E1 x 2^E2 module 2^N.
  2145. if (LHS.isNegative())
  2146. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2147. else if (LHS.countLeadingZeros() < SA)
  2148. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2149. }
  2150. Result = LHS << SA;
  2151. return true;
  2152. }
  2153. case BO_Shr: {
  2154. if (Info.getLangOpts().OpenCL)
  2155. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2156. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2157. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2158. RHS.isUnsigned());
  2159. else if (RHS.isSigned() && RHS.isNegative()) {
  2160. // During constant-folding, a negative shift is an opposite shift. Such a
  2161. // shift is not a constant expression.
  2162. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2163. RHS = -RHS;
  2164. goto shift_left;
  2165. }
  2166. shift_right:
  2167. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2168. // shifted type.
  2169. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2170. if (SA != RHS)
  2171. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2172. << RHS << E->getType() << LHS.getBitWidth();
  2173. Result = LHS >> SA;
  2174. return true;
  2175. }
  2176. case BO_LT: Result = LHS < RHS; return true;
  2177. case BO_GT: Result = LHS > RHS; return true;
  2178. case BO_LE: Result = LHS <= RHS; return true;
  2179. case BO_GE: Result = LHS >= RHS; return true;
  2180. case BO_EQ: Result = LHS == RHS; return true;
  2181. case BO_NE: Result = LHS != RHS; return true;
  2182. case BO_Cmp:
  2183. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2184. }
  2185. }
  2186. /// Perform the given binary floating-point operation, in-place, on LHS.
  2187. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2188. APFloat &LHS, BinaryOperatorKind Opcode,
  2189. const APFloat &RHS) {
  2190. switch (Opcode) {
  2191. default:
  2192. Info.FFDiag(E);
  2193. return false;
  2194. case BO_Mul:
  2195. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2196. break;
  2197. case BO_Add:
  2198. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2199. break;
  2200. case BO_Sub:
  2201. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2202. break;
  2203. case BO_Div:
  2204. // [expr.mul]p4:
  2205. // If the second operand of / or % is zero the behavior is undefined.
  2206. if (RHS.isZero())
  2207. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2208. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2209. break;
  2210. }
  2211. // [expr.pre]p4:
  2212. // If during the evaluation of an expression, the result is not
  2213. // mathematically defined [...], the behavior is undefined.
  2214. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2215. if (LHS.isNaN()) {
  2216. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2217. return Info.noteUndefinedBehavior();
  2218. }
  2219. return true;
  2220. }
  2221. /// Cast an lvalue referring to a base subobject to a derived class, by
  2222. /// truncating the lvalue's path to the given length.
  2223. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2224. const RecordDecl *TruncatedType,
  2225. unsigned TruncatedElements) {
  2226. SubobjectDesignator &D = Result.Designator;
  2227. // Check we actually point to a derived class object.
  2228. if (TruncatedElements == D.Entries.size())
  2229. return true;
  2230. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2231. "not casting to a derived class");
  2232. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2233. return false;
  2234. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2235. const RecordDecl *RD = TruncatedType;
  2236. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2237. if (RD->isInvalidDecl()) return false;
  2238. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2239. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2240. if (isVirtualBaseClass(D.Entries[I]))
  2241. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2242. else
  2243. Result.Offset -= Layout.getBaseClassOffset(Base);
  2244. RD = Base;
  2245. }
  2246. D.Entries.resize(TruncatedElements);
  2247. return true;
  2248. }
  2249. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2250. const CXXRecordDecl *Derived,
  2251. const CXXRecordDecl *Base,
  2252. const ASTRecordLayout *RL = nullptr) {
  2253. if (!RL) {
  2254. if (Derived->isInvalidDecl()) return false;
  2255. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2256. }
  2257. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2258. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2259. return true;
  2260. }
  2261. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2262. const CXXRecordDecl *DerivedDecl,
  2263. const CXXBaseSpecifier *Base) {
  2264. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2265. if (!Base->isVirtual())
  2266. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2267. SubobjectDesignator &D = Obj.Designator;
  2268. if (D.Invalid)
  2269. return false;
  2270. // Extract most-derived object and corresponding type.
  2271. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2272. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2273. return false;
  2274. // Find the virtual base class.
  2275. if (DerivedDecl->isInvalidDecl()) return false;
  2276. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2277. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2278. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2279. return true;
  2280. }
  2281. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2282. QualType Type, LValue &Result) {
  2283. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2284. PathE = E->path_end();
  2285. PathI != PathE; ++PathI) {
  2286. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2287. *PathI))
  2288. return false;
  2289. Type = (*PathI)->getType();
  2290. }
  2291. return true;
  2292. }
  2293. /// Cast an lvalue referring to a derived class to a known base subobject.
  2294. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2295. const CXXRecordDecl *DerivedRD,
  2296. const CXXRecordDecl *BaseRD) {
  2297. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2298. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2299. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2300. llvm_unreachable("Class must be derived from the passed in base class!");
  2301. for (CXXBasePathElement &Elem : Paths.front())
  2302. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2303. return false;
  2304. return true;
  2305. }
  2306. /// Update LVal to refer to the given field, which must be a member of the type
  2307. /// currently described by LVal.
  2308. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2309. const FieldDecl *FD,
  2310. const ASTRecordLayout *RL = nullptr) {
  2311. if (!RL) {
  2312. if (FD->getParent()->isInvalidDecl()) return false;
  2313. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2314. }
  2315. unsigned I = FD->getFieldIndex();
  2316. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2317. LVal.addDecl(Info, E, FD);
  2318. return true;
  2319. }
  2320. /// Update LVal to refer to the given indirect field.
  2321. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2322. LValue &LVal,
  2323. const IndirectFieldDecl *IFD) {
  2324. for (const auto *C : IFD->chain())
  2325. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2326. return false;
  2327. return true;
  2328. }
  2329. /// Get the size of the given type in char units.
  2330. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2331. QualType Type, CharUnits &Size) {
  2332. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2333. // extension.
  2334. if (Type->isVoidType() || Type->isFunctionType()) {
  2335. Size = CharUnits::One();
  2336. return true;
  2337. }
  2338. if (Type->isDependentType()) {
  2339. Info.FFDiag(Loc);
  2340. return false;
  2341. }
  2342. if (!Type->isConstantSizeType()) {
  2343. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2344. // FIXME: Better diagnostic.
  2345. Info.FFDiag(Loc);
  2346. return false;
  2347. }
  2348. Size = Info.Ctx.getTypeSizeInChars(Type);
  2349. return true;
  2350. }
  2351. /// Update a pointer value to model pointer arithmetic.
  2352. /// \param Info - Information about the ongoing evaluation.
  2353. /// \param E - The expression being evaluated, for diagnostic purposes.
  2354. /// \param LVal - The pointer value to be updated.
  2355. /// \param EltTy - The pointee type represented by LVal.
  2356. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2357. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2358. LValue &LVal, QualType EltTy,
  2359. APSInt Adjustment) {
  2360. CharUnits SizeOfPointee;
  2361. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2362. return false;
  2363. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2364. return true;
  2365. }
  2366. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2367. LValue &LVal, QualType EltTy,
  2368. int64_t Adjustment) {
  2369. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2370. APSInt::get(Adjustment));
  2371. }
  2372. /// Update an lvalue to refer to a component of a complex number.
  2373. /// \param Info - Information about the ongoing evaluation.
  2374. /// \param LVal - The lvalue to be updated.
  2375. /// \param EltTy - The complex number's component type.
  2376. /// \param Imag - False for the real component, true for the imaginary.
  2377. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2378. LValue &LVal, QualType EltTy,
  2379. bool Imag) {
  2380. if (Imag) {
  2381. CharUnits SizeOfComponent;
  2382. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2383. return false;
  2384. LVal.Offset += SizeOfComponent;
  2385. }
  2386. LVal.addComplex(Info, E, EltTy, Imag);
  2387. return true;
  2388. }
  2389. /// Try to evaluate the initializer for a variable declaration.
  2390. ///
  2391. /// \param Info Information about the ongoing evaluation.
  2392. /// \param E An expression to be used when printing diagnostics.
  2393. /// \param VD The variable whose initializer should be obtained.
  2394. /// \param Frame The frame in which the variable was created. Must be null
  2395. /// if this variable is not local to the evaluation.
  2396. /// \param Result Filled in with a pointer to the value of the variable.
  2397. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2398. const VarDecl *VD, CallStackFrame *Frame,
  2399. APValue *&Result, const LValue *LVal) {
  2400. // If this is a parameter to an active constexpr function call, perform
  2401. // argument substitution.
  2402. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2403. // Assume arguments of a potential constant expression are unknown
  2404. // constant expressions.
  2405. if (Info.checkingPotentialConstantExpression())
  2406. return false;
  2407. if (!Frame || !Frame->Arguments) {
  2408. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2409. return false;
  2410. }
  2411. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2412. return true;
  2413. }
  2414. // If this is a local variable, dig out its value.
  2415. if (Frame) {
  2416. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2417. : Frame->getCurrentTemporary(VD);
  2418. if (!Result) {
  2419. // Assume variables referenced within a lambda's call operator that were
  2420. // not declared within the call operator are captures and during checking
  2421. // of a potential constant expression, assume they are unknown constant
  2422. // expressions.
  2423. assert(isLambdaCallOperator(Frame->Callee) &&
  2424. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2425. "missing value for local variable");
  2426. if (Info.checkingPotentialConstantExpression())
  2427. return false;
  2428. // FIXME: implement capture evaluation during constant expr evaluation.
  2429. Info.FFDiag(E->getBeginLoc(),
  2430. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2431. << "captures not currently allowed";
  2432. return false;
  2433. }
  2434. return true;
  2435. }
  2436. // Dig out the initializer, and use the declaration which it's attached to.
  2437. const Expr *Init = VD->getAnyInitializer(VD);
  2438. if (!Init || Init->isValueDependent()) {
  2439. // If we're checking a potential constant expression, the variable could be
  2440. // initialized later.
  2441. if (!Info.checkingPotentialConstantExpression())
  2442. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2443. return false;
  2444. }
  2445. // If we're currently evaluating the initializer of this declaration, use that
  2446. // in-flight value.
  2447. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2448. Result = Info.EvaluatingDeclValue;
  2449. return true;
  2450. }
  2451. // Never evaluate the initializer of a weak variable. We can't be sure that
  2452. // this is the definition which will be used.
  2453. if (VD->isWeak()) {
  2454. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2455. return false;
  2456. }
  2457. // Check that we can fold the initializer. In C++, we will have already done
  2458. // this in the cases where it matters for conformance.
  2459. SmallVector<PartialDiagnosticAt, 8> Notes;
  2460. if (!VD->evaluateValue(Notes)) {
  2461. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2462. Notes.size() + 1) << VD;
  2463. Info.Note(VD->getLocation(), diag::note_declared_at);
  2464. Info.addNotes(Notes);
  2465. return false;
  2466. } else if (!VD->checkInitIsICE()) {
  2467. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2468. Notes.size() + 1) << VD;
  2469. Info.Note(VD->getLocation(), diag::note_declared_at);
  2470. Info.addNotes(Notes);
  2471. }
  2472. Result = VD->getEvaluatedValue();
  2473. return true;
  2474. }
  2475. static bool IsConstNonVolatile(QualType T) {
  2476. Qualifiers Quals = T.getQualifiers();
  2477. return Quals.hasConst() && !Quals.hasVolatile();
  2478. }
  2479. /// Get the base index of the given base class within an APValue representing
  2480. /// the given derived class.
  2481. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2482. const CXXRecordDecl *Base) {
  2483. Base = Base->getCanonicalDecl();
  2484. unsigned Index = 0;
  2485. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2486. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2487. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2488. return Index;
  2489. }
  2490. llvm_unreachable("base class missing from derived class's bases list");
  2491. }
  2492. /// Extract the value of a character from a string literal.
  2493. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2494. uint64_t Index) {
  2495. assert(!isa<SourceLocExpr>(Lit) &&
  2496. "SourceLocExpr should have already been converted to a StringLiteral");
  2497. // FIXME: Support MakeStringConstant
  2498. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2499. std::string Str;
  2500. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2501. assert(Index <= Str.size() && "Index too large");
  2502. return APSInt::getUnsigned(Str.c_str()[Index]);
  2503. }
  2504. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2505. Lit = PE->getFunctionName();
  2506. const StringLiteral *S = cast<StringLiteral>(Lit);
  2507. const ConstantArrayType *CAT =
  2508. Info.Ctx.getAsConstantArrayType(S->getType());
  2509. assert(CAT && "string literal isn't an array");
  2510. QualType CharType = CAT->getElementType();
  2511. assert(CharType->isIntegerType() && "unexpected character type");
  2512. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2513. CharType->isUnsignedIntegerType());
  2514. if (Index < S->getLength())
  2515. Value = S->getCodeUnit(Index);
  2516. return Value;
  2517. }
  2518. // Expand a string literal into an array of characters.
  2519. //
  2520. // FIXME: This is inefficient; we should probably introduce something similar
  2521. // to the LLVM ConstantDataArray to make this cheaper.
  2522. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2523. APValue &Result,
  2524. QualType AllocType = QualType()) {
  2525. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  2526. AllocType.isNull() ? S->getType() : AllocType);
  2527. assert(CAT && "string literal isn't an array");
  2528. QualType CharType = CAT->getElementType();
  2529. assert(CharType->isIntegerType() && "unexpected character type");
  2530. unsigned Elts = CAT->getSize().getZExtValue();
  2531. Result = APValue(APValue::UninitArray(),
  2532. std::min(S->getLength(), Elts), Elts);
  2533. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2534. CharType->isUnsignedIntegerType());
  2535. if (Result.hasArrayFiller())
  2536. Result.getArrayFiller() = APValue(Value);
  2537. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2538. Value = S->getCodeUnit(I);
  2539. Result.getArrayInitializedElt(I) = APValue(Value);
  2540. }
  2541. }
  2542. // Expand an array so that it has more than Index filled elements.
  2543. static void expandArray(APValue &Array, unsigned Index) {
  2544. unsigned Size = Array.getArraySize();
  2545. assert(Index < Size);
  2546. // Always at least double the number of elements for which we store a value.
  2547. unsigned OldElts = Array.getArrayInitializedElts();
  2548. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2549. NewElts = std::min(Size, std::max(NewElts, 8u));
  2550. // Copy the data across.
  2551. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2552. for (unsigned I = 0; I != OldElts; ++I)
  2553. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2554. for (unsigned I = OldElts; I != NewElts; ++I)
  2555. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2556. if (NewValue.hasArrayFiller())
  2557. NewValue.getArrayFiller() = Array.getArrayFiller();
  2558. Array.swap(NewValue);
  2559. }
  2560. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2561. /// conversion. If it's of class type, we may assume that the copy operation
  2562. /// is trivial. Note that this is never true for a union type with fields
  2563. /// (because the copy always "reads" the active member) and always true for
  2564. /// a non-class type.
  2565. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2566. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2567. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2568. return true;
  2569. if (RD->isEmpty())
  2570. return false;
  2571. for (auto *Field : RD->fields())
  2572. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2573. return true;
  2574. for (auto &BaseSpec : RD->bases())
  2575. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2576. return true;
  2577. return false;
  2578. }
  2579. /// Diagnose an attempt to read from any unreadable field within the specified
  2580. /// type, which might be a class type.
  2581. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2582. QualType T) {
  2583. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2584. if (!RD)
  2585. return false;
  2586. if (!RD->hasMutableFields())
  2587. return false;
  2588. for (auto *Field : RD->fields()) {
  2589. // If we're actually going to read this field in some way, then it can't
  2590. // be mutable. If we're in a union, then assigning to a mutable field
  2591. // (even an empty one) can change the active member, so that's not OK.
  2592. // FIXME: Add core issue number for the union case.
  2593. if (Field->isMutable() &&
  2594. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2595. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2596. Info.Note(Field->getLocation(), diag::note_declared_at);
  2597. return true;
  2598. }
  2599. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2600. return true;
  2601. }
  2602. for (auto &BaseSpec : RD->bases())
  2603. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2604. return true;
  2605. // All mutable fields were empty, and thus not actually read.
  2606. return false;
  2607. }
  2608. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2609. APValue::LValueBase Base) {
  2610. // A temporary we created.
  2611. if (Base.getCallIndex())
  2612. return true;
  2613. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2614. if (!Evaluating)
  2615. return false;
  2616. // The variable whose initializer we're evaluating.
  2617. if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
  2618. if (declaresSameEntity(Evaluating, BaseD))
  2619. return true;
  2620. // A temporary lifetime-extended by the variable whose initializer we're
  2621. // evaluating.
  2622. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2623. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2624. if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
  2625. return true;
  2626. return false;
  2627. }
  2628. namespace {
  2629. /// A handle to a complete object (an object that is not a subobject of
  2630. /// another object).
  2631. struct CompleteObject {
  2632. /// The identity of the object.
  2633. APValue::LValueBase Base;
  2634. /// The value of the complete object.
  2635. APValue *Value;
  2636. /// The type of the complete object.
  2637. QualType Type;
  2638. CompleteObject() : Value(nullptr) {}
  2639. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2640. : Base(Base), Value(Value), Type(Type) {}
  2641. bool mayReadMutableMembers(EvalInfo &Info) const {
  2642. // In C++14 onwards, it is permitted to read a mutable member whose
  2643. // lifetime began within the evaluation.
  2644. // FIXME: Should we also allow this in C++11?
  2645. if (!Info.getLangOpts().CPlusPlus14)
  2646. return false;
  2647. return lifetimeStartedInEvaluation(Info, Base);
  2648. }
  2649. explicit operator bool() const { return !Type.isNull(); }
  2650. };
  2651. } // end anonymous namespace
  2652. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2653. bool IsMutable = false) {
  2654. // C++ [basic.type.qualifier]p1:
  2655. // - A const object is an object of type const T or a non-mutable subobject
  2656. // of a const object.
  2657. if (ObjType.isConstQualified() && !IsMutable)
  2658. SubobjType.addConst();
  2659. // - A volatile object is an object of type const T or a subobject of a
  2660. // volatile object.
  2661. if (ObjType.isVolatileQualified())
  2662. SubobjType.addVolatile();
  2663. return SubobjType;
  2664. }
  2665. /// Find the designated sub-object of an rvalue.
  2666. template<typename SubobjectHandler>
  2667. typename SubobjectHandler::result_type
  2668. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2669. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2670. if (Sub.Invalid)
  2671. // A diagnostic will have already been produced.
  2672. return handler.failed();
  2673. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2674. if (Info.getLangOpts().CPlusPlus11)
  2675. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2676. ? diag::note_constexpr_access_past_end
  2677. : diag::note_constexpr_access_unsized_array)
  2678. << handler.AccessKind;
  2679. else
  2680. Info.FFDiag(E);
  2681. return handler.failed();
  2682. }
  2683. APValue *O = Obj.Value;
  2684. QualType ObjType = Obj.Type;
  2685. const FieldDecl *LastField = nullptr;
  2686. const FieldDecl *VolatileField = nullptr;
  2687. // Walk the designator's path to find the subobject.
  2688. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2689. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2690. if (O->isAbsent() ||
  2691. (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
  2692. handler.AccessKind != AK_ReadObjectRepresentation)) {
  2693. if (!Info.checkingPotentialConstantExpression())
  2694. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2695. << handler.AccessKind << O->isIndeterminate();
  2696. return handler.failed();
  2697. }
  2698. // C++ [class.ctor]p5, C++ [class.dtor]p5:
  2699. // const and volatile semantics are not applied on an object under
  2700. // {con,de}struction.
  2701. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2702. ObjType->isRecordType() &&
  2703. Info.isEvaluatingCtorDtor(
  2704. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2705. Sub.Entries.begin() + I)) !=
  2706. ConstructionPhase::None) {
  2707. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2708. ObjType.removeLocalConst();
  2709. ObjType.removeLocalVolatile();
  2710. }
  2711. // If this is our last pass, check that the final object type is OK.
  2712. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2713. // Accesses to volatile objects are prohibited.
  2714. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2715. if (Info.getLangOpts().CPlusPlus) {
  2716. int DiagKind;
  2717. SourceLocation Loc;
  2718. const NamedDecl *Decl = nullptr;
  2719. if (VolatileField) {
  2720. DiagKind = 2;
  2721. Loc = VolatileField->getLocation();
  2722. Decl = VolatileField;
  2723. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2724. DiagKind = 1;
  2725. Loc = VD->getLocation();
  2726. Decl = VD;
  2727. } else {
  2728. DiagKind = 0;
  2729. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2730. Loc = E->getExprLoc();
  2731. }
  2732. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2733. << handler.AccessKind << DiagKind << Decl;
  2734. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2735. } else {
  2736. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2737. }
  2738. return handler.failed();
  2739. }
  2740. // If we are reading an object of class type, there may still be more
  2741. // things we need to check: if there are any mutable subobjects, we
  2742. // cannot perform this read. (This only happens when performing a trivial
  2743. // copy or assignment.)
  2744. if (ObjType->isRecordType() && isRead(handler.AccessKind) &&
  2745. !Obj.mayReadMutableMembers(Info) &&
  2746. diagnoseUnreadableFields(Info, E, ObjType))
  2747. return handler.failed();
  2748. }
  2749. if (I == N) {
  2750. if (!handler.found(*O, ObjType))
  2751. return false;
  2752. // If we modified a bit-field, truncate it to the right width.
  2753. if (isModification(handler.AccessKind) &&
  2754. LastField && LastField->isBitField() &&
  2755. !truncateBitfieldValue(Info, E, *O, LastField))
  2756. return false;
  2757. return true;
  2758. }
  2759. LastField = nullptr;
  2760. if (ObjType->isArrayType()) {
  2761. // Next subobject is an array element.
  2762. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2763. assert(CAT && "vla in literal type?");
  2764. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2765. if (CAT->getSize().ule(Index)) {
  2766. // Note, it should not be possible to form a pointer with a valid
  2767. // designator which points more than one past the end of the array.
  2768. if (Info.getLangOpts().CPlusPlus11)
  2769. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2770. << handler.AccessKind;
  2771. else
  2772. Info.FFDiag(E);
  2773. return handler.failed();
  2774. }
  2775. ObjType = CAT->getElementType();
  2776. if (O->getArrayInitializedElts() > Index)
  2777. O = &O->getArrayInitializedElt(Index);
  2778. else if (!isRead(handler.AccessKind)) {
  2779. expandArray(*O, Index);
  2780. O = &O->getArrayInitializedElt(Index);
  2781. } else
  2782. O = &O->getArrayFiller();
  2783. } else if (ObjType->isAnyComplexType()) {
  2784. // Next subobject is a complex number.
  2785. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2786. if (Index > 1) {
  2787. if (Info.getLangOpts().CPlusPlus11)
  2788. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2789. << handler.AccessKind;
  2790. else
  2791. Info.FFDiag(E);
  2792. return handler.failed();
  2793. }
  2794. ObjType = getSubobjectType(
  2795. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2796. assert(I == N - 1 && "extracting subobject of scalar?");
  2797. if (O->isComplexInt()) {
  2798. return handler.found(Index ? O->getComplexIntImag()
  2799. : O->getComplexIntReal(), ObjType);
  2800. } else {
  2801. assert(O->isComplexFloat());
  2802. return handler.found(Index ? O->getComplexFloatImag()
  2803. : O->getComplexFloatReal(), ObjType);
  2804. }
  2805. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2806. if (Field->isMutable() && isRead(handler.AccessKind) &&
  2807. !Obj.mayReadMutableMembers(Info)) {
  2808. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2809. << Field;
  2810. Info.Note(Field->getLocation(), diag::note_declared_at);
  2811. return handler.failed();
  2812. }
  2813. // Next subobject is a class, struct or union field.
  2814. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2815. if (RD->isUnion()) {
  2816. const FieldDecl *UnionField = O->getUnionField();
  2817. if (!UnionField ||
  2818. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2819. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2820. << handler.AccessKind << Field << !UnionField << UnionField;
  2821. return handler.failed();
  2822. }
  2823. O = &O->getUnionValue();
  2824. } else
  2825. O = &O->getStructField(Field->getFieldIndex());
  2826. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2827. LastField = Field;
  2828. if (Field->getType().isVolatileQualified())
  2829. VolatileField = Field;
  2830. } else {
  2831. // Next subobject is a base class.
  2832. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2833. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2834. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2835. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2836. }
  2837. }
  2838. }
  2839. namespace {
  2840. struct ExtractSubobjectHandler {
  2841. EvalInfo &Info;
  2842. const Expr *E;
  2843. APValue &Result;
  2844. const AccessKinds AccessKind;
  2845. typedef bool result_type;
  2846. bool failed() { return false; }
  2847. bool found(APValue &Subobj, QualType SubobjType) {
  2848. Result = Subobj;
  2849. if (AccessKind == AK_ReadObjectRepresentation)
  2850. return true;
  2851. return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
  2852. }
  2853. bool found(APSInt &Value, QualType SubobjType) {
  2854. Result = APValue(Value);
  2855. return true;
  2856. }
  2857. bool found(APFloat &Value, QualType SubobjType) {
  2858. Result = APValue(Value);
  2859. return true;
  2860. }
  2861. };
  2862. } // end anonymous namespace
  2863. /// Extract the designated sub-object of an rvalue.
  2864. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2865. const CompleteObject &Obj,
  2866. const SubobjectDesignator &Sub, APValue &Result,
  2867. AccessKinds AK = AK_Read) {
  2868. assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
  2869. ExtractSubobjectHandler Handler = {Info, E, Result, AK};
  2870. return findSubobject(Info, E, Obj, Sub, Handler);
  2871. }
  2872. namespace {
  2873. struct ModifySubobjectHandler {
  2874. EvalInfo &Info;
  2875. APValue &NewVal;
  2876. const Expr *E;
  2877. typedef bool result_type;
  2878. static const AccessKinds AccessKind = AK_Assign;
  2879. bool checkConst(QualType QT) {
  2880. // Assigning to a const object has undefined behavior.
  2881. if (QT.isConstQualified()) {
  2882. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2883. return false;
  2884. }
  2885. return true;
  2886. }
  2887. bool failed() { return false; }
  2888. bool found(APValue &Subobj, QualType SubobjType) {
  2889. if (!checkConst(SubobjType))
  2890. return false;
  2891. // We've been given ownership of NewVal, so just swap it in.
  2892. Subobj.swap(NewVal);
  2893. return true;
  2894. }
  2895. bool found(APSInt &Value, QualType SubobjType) {
  2896. if (!checkConst(SubobjType))
  2897. return false;
  2898. if (!NewVal.isInt()) {
  2899. // Maybe trying to write a cast pointer value into a complex?
  2900. Info.FFDiag(E);
  2901. return false;
  2902. }
  2903. Value = NewVal.getInt();
  2904. return true;
  2905. }
  2906. bool found(APFloat &Value, QualType SubobjType) {
  2907. if (!checkConst(SubobjType))
  2908. return false;
  2909. Value = NewVal.getFloat();
  2910. return true;
  2911. }
  2912. };
  2913. } // end anonymous namespace
  2914. const AccessKinds ModifySubobjectHandler::AccessKind;
  2915. /// Update the designated sub-object of an rvalue to the given value.
  2916. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2917. const CompleteObject &Obj,
  2918. const SubobjectDesignator &Sub,
  2919. APValue &NewVal) {
  2920. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2921. return findSubobject(Info, E, Obj, Sub, Handler);
  2922. }
  2923. /// Find the position where two subobject designators diverge, or equivalently
  2924. /// the length of the common initial subsequence.
  2925. static unsigned FindDesignatorMismatch(QualType ObjType,
  2926. const SubobjectDesignator &A,
  2927. const SubobjectDesignator &B,
  2928. bool &WasArrayIndex) {
  2929. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2930. for (/**/; I != N; ++I) {
  2931. if (!ObjType.isNull() &&
  2932. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2933. // Next subobject is an array element.
  2934. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  2935. WasArrayIndex = true;
  2936. return I;
  2937. }
  2938. if (ObjType->isAnyComplexType())
  2939. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2940. else
  2941. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2942. } else {
  2943. if (A.Entries[I].getAsBaseOrMember() !=
  2944. B.Entries[I].getAsBaseOrMember()) {
  2945. WasArrayIndex = false;
  2946. return I;
  2947. }
  2948. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2949. // Next subobject is a field.
  2950. ObjType = FD->getType();
  2951. else
  2952. // Next subobject is a base class.
  2953. ObjType = QualType();
  2954. }
  2955. }
  2956. WasArrayIndex = false;
  2957. return I;
  2958. }
  2959. /// Determine whether the given subobject designators refer to elements of the
  2960. /// same array object.
  2961. static bool AreElementsOfSameArray(QualType ObjType,
  2962. const SubobjectDesignator &A,
  2963. const SubobjectDesignator &B) {
  2964. if (A.Entries.size() != B.Entries.size())
  2965. return false;
  2966. bool IsArray = A.MostDerivedIsArrayElement;
  2967. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2968. // A is a subobject of the array element.
  2969. return false;
  2970. // If A (and B) designates an array element, the last entry will be the array
  2971. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2972. // of length 1' case, and the entire path must match.
  2973. bool WasArrayIndex;
  2974. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2975. return CommonLength >= A.Entries.size() - IsArray;
  2976. }
  2977. /// Find the complete object to which an LValue refers.
  2978. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2979. AccessKinds AK, const LValue &LVal,
  2980. QualType LValType) {
  2981. if (LVal.InvalidBase) {
  2982. Info.FFDiag(E);
  2983. return CompleteObject();
  2984. }
  2985. if (!LVal.Base) {
  2986. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2987. return CompleteObject();
  2988. }
  2989. CallStackFrame *Frame = nullptr;
  2990. unsigned Depth = 0;
  2991. if (LVal.getLValueCallIndex()) {
  2992. std::tie(Frame, Depth) =
  2993. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  2994. if (!Frame) {
  2995. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2996. << AK << LVal.Base.is<const ValueDecl*>();
  2997. NoteLValueLocation(Info, LVal.Base);
  2998. return CompleteObject();
  2999. }
  3000. }
  3001. bool IsAccess = isFormalAccess(AK);
  3002. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  3003. // is not a constant expression (even if the object is non-volatile). We also
  3004. // apply this rule to C++98, in order to conform to the expected 'volatile'
  3005. // semantics.
  3006. if (IsAccess && LValType.isVolatileQualified()) {
  3007. if (Info.getLangOpts().CPlusPlus)
  3008. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  3009. << AK << LValType;
  3010. else
  3011. Info.FFDiag(E);
  3012. return CompleteObject();
  3013. }
  3014. // Compute value storage location and type of base object.
  3015. APValue *BaseVal = nullptr;
  3016. QualType BaseType = getType(LVal.Base);
  3017. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  3018. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  3019. // In C++11, constexpr, non-volatile variables initialized with constant
  3020. // expressions are constant expressions too. Inside constexpr functions,
  3021. // parameters are constant expressions even if they're non-const.
  3022. // In C++1y, objects local to a constant expression (those with a Frame) are
  3023. // both readable and writable inside constant expressions.
  3024. // In C, such things can also be folded, although they are not ICEs.
  3025. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3026. if (VD) {
  3027. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3028. VD = VDef;
  3029. }
  3030. if (!VD || VD->isInvalidDecl()) {
  3031. Info.FFDiag(E);
  3032. return CompleteObject();
  3033. }
  3034. // Unless we're looking at a local variable or argument in a constexpr call,
  3035. // the variable we're reading must be const.
  3036. if (!Frame) {
  3037. if (Info.getLangOpts().CPlusPlus14 &&
  3038. declaresSameEntity(
  3039. VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
  3040. // OK, we can read and modify an object if we're in the process of
  3041. // evaluating its initializer, because its lifetime began in this
  3042. // evaluation.
  3043. } else if (isModification(AK)) {
  3044. // All the remaining cases do not permit modification of the object.
  3045. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3046. return CompleteObject();
  3047. } else if (VD->isConstexpr()) {
  3048. // OK, we can read this variable.
  3049. } else if (BaseType->isIntegralOrEnumerationType()) {
  3050. // In OpenCL if a variable is in constant address space it is a const
  3051. // value.
  3052. if (!(BaseType.isConstQualified() ||
  3053. (Info.getLangOpts().OpenCL &&
  3054. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  3055. if (!IsAccess)
  3056. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3057. if (Info.getLangOpts().CPlusPlus) {
  3058. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3059. Info.Note(VD->getLocation(), diag::note_declared_at);
  3060. } else {
  3061. Info.FFDiag(E);
  3062. }
  3063. return CompleteObject();
  3064. }
  3065. } else if (!IsAccess) {
  3066. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3067. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  3068. // We support folding of const floating-point types, in order to make
  3069. // static const data members of such types (supported as an extension)
  3070. // more useful.
  3071. if (Info.getLangOpts().CPlusPlus11) {
  3072. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3073. Info.Note(VD->getLocation(), diag::note_declared_at);
  3074. } else {
  3075. Info.CCEDiag(E);
  3076. }
  3077. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3078. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3079. // Keep evaluating to see what we can do.
  3080. } else {
  3081. // FIXME: Allow folding of values of any literal type in all languages.
  3082. if (Info.checkingPotentialConstantExpression() &&
  3083. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3084. // The definition of this variable could be constexpr. We can't
  3085. // access it right now, but may be able to in future.
  3086. } else if (Info.getLangOpts().CPlusPlus11) {
  3087. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3088. Info.Note(VD->getLocation(), diag::note_declared_at);
  3089. } else {
  3090. Info.FFDiag(E);
  3091. }
  3092. return CompleteObject();
  3093. }
  3094. }
  3095. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3096. return CompleteObject();
  3097. } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
  3098. Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  3099. if (!Alloc) {
  3100. Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
  3101. return CompleteObject();
  3102. }
  3103. return CompleteObject(LVal.Base, &(*Alloc)->Value,
  3104. LVal.Base.getDynamicAllocType());
  3105. } else {
  3106. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3107. if (!Frame) {
  3108. if (const MaterializeTemporaryExpr *MTE =
  3109. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3110. assert(MTE->getStorageDuration() == SD_Static &&
  3111. "should have a frame for a non-global materialized temporary");
  3112. // Per C++1y [expr.const]p2:
  3113. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3114. // - a [...] glvalue of integral or enumeration type that refers to
  3115. // a non-volatile const object [...]
  3116. // [...]
  3117. // - a [...] glvalue of literal type that refers to a non-volatile
  3118. // object whose lifetime began within the evaluation of e.
  3119. //
  3120. // C++11 misses the 'began within the evaluation of e' check and
  3121. // instead allows all temporaries, including things like:
  3122. // int &&r = 1;
  3123. // int x = ++r;
  3124. // constexpr int k = r;
  3125. // Therefore we use the C++14 rules in C++11 too.
  3126. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  3127. const ValueDecl *ED = MTE->getExtendingDecl();
  3128. if (!(BaseType.isConstQualified() &&
  3129. BaseType->isIntegralOrEnumerationType()) &&
  3130. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  3131. if (!IsAccess)
  3132. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3133. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3134. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3135. return CompleteObject();
  3136. }
  3137. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3138. assert(BaseVal && "got reference to unevaluated temporary");
  3139. } else {
  3140. if (!IsAccess)
  3141. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3142. APValue Val;
  3143. LVal.moveInto(Val);
  3144. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3145. << AK
  3146. << Val.getAsString(Info.Ctx,
  3147. Info.Ctx.getLValueReferenceType(LValType));
  3148. NoteLValueLocation(Info, LVal.Base);
  3149. return CompleteObject();
  3150. }
  3151. } else {
  3152. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3153. assert(BaseVal && "missing value for temporary");
  3154. }
  3155. }
  3156. // In C++14, we can't safely access any mutable state when we might be
  3157. // evaluating after an unmodeled side effect.
  3158. //
  3159. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3160. // to be read here (but take care with 'mutable' fields).
  3161. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3162. Info.EvalStatus.HasSideEffects) ||
  3163. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3164. return CompleteObject();
  3165. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3166. }
  3167. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3168. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3169. /// glvalue referred to by an entity of reference type.
  3170. ///
  3171. /// \param Info - Information about the ongoing evaluation.
  3172. /// \param Conv - The expression for which we are performing the conversion.
  3173. /// Used for diagnostics.
  3174. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3175. /// case of a non-class type).
  3176. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3177. /// \param RVal - The produced value will be placed here.
  3178. /// \param WantObjectRepresentation - If true, we're looking for the object
  3179. /// representation rather than the value, and in particular,
  3180. /// there is no requirement that the result be fully initialized.
  3181. static bool
  3182. handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
  3183. const LValue &LVal, APValue &RVal,
  3184. bool WantObjectRepresentation = false) {
  3185. if (LVal.Designator.Invalid)
  3186. return false;
  3187. // Check for special cases where there is no existing APValue to look at.
  3188. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3189. AccessKinds AK =
  3190. WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
  3191. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3192. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3193. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3194. // initializer until now for such expressions. Such an expression can't be
  3195. // an ICE in C, so this only matters for fold.
  3196. if (Type.isVolatileQualified()) {
  3197. Info.FFDiag(Conv);
  3198. return false;
  3199. }
  3200. APValue Lit;
  3201. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3202. return false;
  3203. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3204. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
  3205. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3206. // Special-case character extraction so we don't have to construct an
  3207. // APValue for the whole string.
  3208. assert(LVal.Designator.Entries.size() <= 1 &&
  3209. "Can only read characters from string literals");
  3210. if (LVal.Designator.Entries.empty()) {
  3211. // Fail for now for LValue to RValue conversion of an array.
  3212. // (This shouldn't show up in C/C++, but it could be triggered by a
  3213. // weird EvaluateAsRValue call from a tool.)
  3214. Info.FFDiag(Conv);
  3215. return false;
  3216. }
  3217. if (LVal.Designator.isOnePastTheEnd()) {
  3218. if (Info.getLangOpts().CPlusPlus11)
  3219. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
  3220. else
  3221. Info.FFDiag(Conv);
  3222. return false;
  3223. }
  3224. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3225. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3226. return true;
  3227. }
  3228. }
  3229. CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
  3230. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
  3231. }
  3232. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3233. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3234. QualType LValType, APValue &Val) {
  3235. if (LVal.Designator.Invalid)
  3236. return false;
  3237. if (!Info.getLangOpts().CPlusPlus14) {
  3238. Info.FFDiag(E);
  3239. return false;
  3240. }
  3241. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3242. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3243. }
  3244. namespace {
  3245. struct CompoundAssignSubobjectHandler {
  3246. EvalInfo &Info;
  3247. const Expr *E;
  3248. QualType PromotedLHSType;
  3249. BinaryOperatorKind Opcode;
  3250. const APValue &RHS;
  3251. static const AccessKinds AccessKind = AK_Assign;
  3252. typedef bool result_type;
  3253. bool checkConst(QualType QT) {
  3254. // Assigning to a const object has undefined behavior.
  3255. if (QT.isConstQualified()) {
  3256. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3257. return false;
  3258. }
  3259. return true;
  3260. }
  3261. bool failed() { return false; }
  3262. bool found(APValue &Subobj, QualType SubobjType) {
  3263. switch (Subobj.getKind()) {
  3264. case APValue::Int:
  3265. return found(Subobj.getInt(), SubobjType);
  3266. case APValue::Float:
  3267. return found(Subobj.getFloat(), SubobjType);
  3268. case APValue::ComplexInt:
  3269. case APValue::ComplexFloat:
  3270. // FIXME: Implement complex compound assignment.
  3271. Info.FFDiag(E);
  3272. return false;
  3273. case APValue::LValue:
  3274. return foundPointer(Subobj, SubobjType);
  3275. default:
  3276. // FIXME: can this happen?
  3277. Info.FFDiag(E);
  3278. return false;
  3279. }
  3280. }
  3281. bool found(APSInt &Value, QualType SubobjType) {
  3282. if (!checkConst(SubobjType))
  3283. return false;
  3284. if (!SubobjType->isIntegerType()) {
  3285. // We don't support compound assignment on integer-cast-to-pointer
  3286. // values.
  3287. Info.FFDiag(E);
  3288. return false;
  3289. }
  3290. if (RHS.isInt()) {
  3291. APSInt LHS =
  3292. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3293. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3294. return false;
  3295. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3296. return true;
  3297. } else if (RHS.isFloat()) {
  3298. APFloat FValue(0.0);
  3299. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3300. FValue) &&
  3301. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3302. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3303. Value);
  3304. }
  3305. Info.FFDiag(E);
  3306. return false;
  3307. }
  3308. bool found(APFloat &Value, QualType SubobjType) {
  3309. return checkConst(SubobjType) &&
  3310. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3311. Value) &&
  3312. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3313. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3314. }
  3315. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3316. if (!checkConst(SubobjType))
  3317. return false;
  3318. QualType PointeeType;
  3319. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3320. PointeeType = PT->getPointeeType();
  3321. if (PointeeType.isNull() || !RHS.isInt() ||
  3322. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3323. Info.FFDiag(E);
  3324. return false;
  3325. }
  3326. APSInt Offset = RHS.getInt();
  3327. if (Opcode == BO_Sub)
  3328. negateAsSigned(Offset);
  3329. LValue LVal;
  3330. LVal.setFrom(Info.Ctx, Subobj);
  3331. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3332. return false;
  3333. LVal.moveInto(Subobj);
  3334. return true;
  3335. }
  3336. };
  3337. } // end anonymous namespace
  3338. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3339. /// Perform a compound assignment of LVal <op>= RVal.
  3340. static bool handleCompoundAssignment(
  3341. EvalInfo &Info, const Expr *E,
  3342. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3343. BinaryOperatorKind Opcode, const APValue &RVal) {
  3344. if (LVal.Designator.Invalid)
  3345. return false;
  3346. if (!Info.getLangOpts().CPlusPlus14) {
  3347. Info.FFDiag(E);
  3348. return false;
  3349. }
  3350. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3351. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3352. RVal };
  3353. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3354. }
  3355. namespace {
  3356. struct IncDecSubobjectHandler {
  3357. EvalInfo &Info;
  3358. const UnaryOperator *E;
  3359. AccessKinds AccessKind;
  3360. APValue *Old;
  3361. typedef bool result_type;
  3362. bool checkConst(QualType QT) {
  3363. // Assigning to a const object has undefined behavior.
  3364. if (QT.isConstQualified()) {
  3365. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3366. return false;
  3367. }
  3368. return true;
  3369. }
  3370. bool failed() { return false; }
  3371. bool found(APValue &Subobj, QualType SubobjType) {
  3372. // Stash the old value. Also clear Old, so we don't clobber it later
  3373. // if we're post-incrementing a complex.
  3374. if (Old) {
  3375. *Old = Subobj;
  3376. Old = nullptr;
  3377. }
  3378. switch (Subobj.getKind()) {
  3379. case APValue::Int:
  3380. return found(Subobj.getInt(), SubobjType);
  3381. case APValue::Float:
  3382. return found(Subobj.getFloat(), SubobjType);
  3383. case APValue::ComplexInt:
  3384. return found(Subobj.getComplexIntReal(),
  3385. SubobjType->castAs<ComplexType>()->getElementType()
  3386. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3387. case APValue::ComplexFloat:
  3388. return found(Subobj.getComplexFloatReal(),
  3389. SubobjType->castAs<ComplexType>()->getElementType()
  3390. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3391. case APValue::LValue:
  3392. return foundPointer(Subobj, SubobjType);
  3393. default:
  3394. // FIXME: can this happen?
  3395. Info.FFDiag(E);
  3396. return false;
  3397. }
  3398. }
  3399. bool found(APSInt &Value, QualType SubobjType) {
  3400. if (!checkConst(SubobjType))
  3401. return false;
  3402. if (!SubobjType->isIntegerType()) {
  3403. // We don't support increment / decrement on integer-cast-to-pointer
  3404. // values.
  3405. Info.FFDiag(E);
  3406. return false;
  3407. }
  3408. if (Old) *Old = APValue(Value);
  3409. // bool arithmetic promotes to int, and the conversion back to bool
  3410. // doesn't reduce mod 2^n, so special-case it.
  3411. if (SubobjType->isBooleanType()) {
  3412. if (AccessKind == AK_Increment)
  3413. Value = 1;
  3414. else
  3415. Value = !Value;
  3416. return true;
  3417. }
  3418. bool WasNegative = Value.isNegative();
  3419. if (AccessKind == AK_Increment) {
  3420. ++Value;
  3421. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3422. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3423. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3424. }
  3425. } else {
  3426. --Value;
  3427. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3428. unsigned BitWidth = Value.getBitWidth();
  3429. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3430. ActualValue.setBit(BitWidth);
  3431. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3432. }
  3433. }
  3434. return true;
  3435. }
  3436. bool found(APFloat &Value, QualType SubobjType) {
  3437. if (!checkConst(SubobjType))
  3438. return false;
  3439. if (Old) *Old = APValue(Value);
  3440. APFloat One(Value.getSemantics(), 1);
  3441. if (AccessKind == AK_Increment)
  3442. Value.add(One, APFloat::rmNearestTiesToEven);
  3443. else
  3444. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3445. return true;
  3446. }
  3447. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3448. if (!checkConst(SubobjType))
  3449. return false;
  3450. QualType PointeeType;
  3451. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3452. PointeeType = PT->getPointeeType();
  3453. else {
  3454. Info.FFDiag(E);
  3455. return false;
  3456. }
  3457. LValue LVal;
  3458. LVal.setFrom(Info.Ctx, Subobj);
  3459. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3460. AccessKind == AK_Increment ? 1 : -1))
  3461. return false;
  3462. LVal.moveInto(Subobj);
  3463. return true;
  3464. }
  3465. };
  3466. } // end anonymous namespace
  3467. /// Perform an increment or decrement on LVal.
  3468. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3469. QualType LValType, bool IsIncrement, APValue *Old) {
  3470. if (LVal.Designator.Invalid)
  3471. return false;
  3472. if (!Info.getLangOpts().CPlusPlus14) {
  3473. Info.FFDiag(E);
  3474. return false;
  3475. }
  3476. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3477. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3478. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3479. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3480. }
  3481. /// Build an lvalue for the object argument of a member function call.
  3482. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3483. LValue &This) {
  3484. if (Object->getType()->isPointerType())
  3485. return EvaluatePointer(Object, This, Info);
  3486. if (Object->isGLValue())
  3487. return EvaluateLValue(Object, This, Info);
  3488. if (Object->getType()->isLiteralType(Info.Ctx))
  3489. return EvaluateTemporary(Object, This, Info);
  3490. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3491. return false;
  3492. }
  3493. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3494. /// lvalue referring to the result.
  3495. ///
  3496. /// \param Info - Information about the ongoing evaluation.
  3497. /// \param LV - An lvalue referring to the base of the member pointer.
  3498. /// \param RHS - The member pointer expression.
  3499. /// \param IncludeMember - Specifies whether the member itself is included in
  3500. /// the resulting LValue subobject designator. This is not possible when
  3501. /// creating a bound member function.
  3502. /// \return The field or method declaration to which the member pointer refers,
  3503. /// or 0 if evaluation fails.
  3504. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3505. QualType LVType,
  3506. LValue &LV,
  3507. const Expr *RHS,
  3508. bool IncludeMember = true) {
  3509. MemberPtr MemPtr;
  3510. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3511. return nullptr;
  3512. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3513. // member value, the behavior is undefined.
  3514. if (!MemPtr.getDecl()) {
  3515. // FIXME: Specific diagnostic.
  3516. Info.FFDiag(RHS);
  3517. return nullptr;
  3518. }
  3519. if (MemPtr.isDerivedMember()) {
  3520. // This is a member of some derived class. Truncate LV appropriately.
  3521. // The end of the derived-to-base path for the base object must match the
  3522. // derived-to-base path for the member pointer.
  3523. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3524. LV.Designator.Entries.size()) {
  3525. Info.FFDiag(RHS);
  3526. return nullptr;
  3527. }
  3528. unsigned PathLengthToMember =
  3529. LV.Designator.Entries.size() - MemPtr.Path.size();
  3530. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3531. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3532. LV.Designator.Entries[PathLengthToMember + I]);
  3533. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3534. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3535. Info.FFDiag(RHS);
  3536. return nullptr;
  3537. }
  3538. }
  3539. // Truncate the lvalue to the appropriate derived class.
  3540. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3541. PathLengthToMember))
  3542. return nullptr;
  3543. } else if (!MemPtr.Path.empty()) {
  3544. // Extend the LValue path with the member pointer's path.
  3545. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3546. MemPtr.Path.size() + IncludeMember);
  3547. // Walk down to the appropriate base class.
  3548. if (const PointerType *PT = LVType->getAs<PointerType>())
  3549. LVType = PT->getPointeeType();
  3550. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3551. assert(RD && "member pointer access on non-class-type expression");
  3552. // The first class in the path is that of the lvalue.
  3553. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3554. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3555. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3556. return nullptr;
  3557. RD = Base;
  3558. }
  3559. // Finally cast to the class containing the member.
  3560. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3561. MemPtr.getContainingRecord()))
  3562. return nullptr;
  3563. }
  3564. // Add the member. Note that we cannot build bound member functions here.
  3565. if (IncludeMember) {
  3566. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3567. if (!HandleLValueMember(Info, RHS, LV, FD))
  3568. return nullptr;
  3569. } else if (const IndirectFieldDecl *IFD =
  3570. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3571. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3572. return nullptr;
  3573. } else {
  3574. llvm_unreachable("can't construct reference to bound member function");
  3575. }
  3576. }
  3577. return MemPtr.getDecl();
  3578. }
  3579. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3580. const BinaryOperator *BO,
  3581. LValue &LV,
  3582. bool IncludeMember = true) {
  3583. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3584. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3585. if (Info.noteFailure()) {
  3586. MemberPtr MemPtr;
  3587. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3588. }
  3589. return nullptr;
  3590. }
  3591. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3592. BO->getRHS(), IncludeMember);
  3593. }
  3594. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3595. /// the provided lvalue, which currently refers to the base object.
  3596. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3597. LValue &Result) {
  3598. SubobjectDesignator &D = Result.Designator;
  3599. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3600. return false;
  3601. QualType TargetQT = E->getType();
  3602. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3603. TargetQT = PT->getPointeeType();
  3604. // Check this cast lands within the final derived-to-base subobject path.
  3605. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3606. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3607. << D.MostDerivedType << TargetQT;
  3608. return false;
  3609. }
  3610. // Check the type of the final cast. We don't need to check the path,
  3611. // since a cast can only be formed if the path is unique.
  3612. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3613. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3614. const CXXRecordDecl *FinalType;
  3615. if (NewEntriesSize == D.MostDerivedPathLength)
  3616. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3617. else
  3618. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3619. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3620. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3621. << D.MostDerivedType << TargetQT;
  3622. return false;
  3623. }
  3624. // Truncate the lvalue to the appropriate derived class.
  3625. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3626. }
  3627. /// Get the value to use for a default-initialized object of type T.
  3628. static APValue getDefaultInitValue(QualType T) {
  3629. if (auto *RD = T->getAsCXXRecordDecl()) {
  3630. if (RD->isUnion())
  3631. return APValue((const FieldDecl*)nullptr);
  3632. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  3633. std::distance(RD->field_begin(), RD->field_end()));
  3634. unsigned Index = 0;
  3635. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  3636. End = RD->bases_end(); I != End; ++I, ++Index)
  3637. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  3638. for (const auto *I : RD->fields()) {
  3639. if (I->isUnnamedBitfield())
  3640. continue;
  3641. Struct.getStructField(I->getFieldIndex()) =
  3642. getDefaultInitValue(I->getType());
  3643. }
  3644. return Struct;
  3645. }
  3646. if (auto *AT =
  3647. dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
  3648. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  3649. if (Array.hasArrayFiller())
  3650. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  3651. return Array;
  3652. }
  3653. return APValue::IndeterminateValue();
  3654. }
  3655. namespace {
  3656. enum EvalStmtResult {
  3657. /// Evaluation failed.
  3658. ESR_Failed,
  3659. /// Hit a 'return' statement.
  3660. ESR_Returned,
  3661. /// Evaluation succeeded.
  3662. ESR_Succeeded,
  3663. /// Hit a 'continue' statement.
  3664. ESR_Continue,
  3665. /// Hit a 'break' statement.
  3666. ESR_Break,
  3667. /// Still scanning for 'case' or 'default' statement.
  3668. ESR_CaseNotFound
  3669. };
  3670. }
  3671. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3672. // We don't need to evaluate the initializer for a static local.
  3673. if (!VD->hasLocalStorage())
  3674. return true;
  3675. LValue Result;
  3676. APValue &Val =
  3677. Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
  3678. const Expr *InitE = VD->getInit();
  3679. if (!InitE) {
  3680. Val = getDefaultInitValue(VD->getType());
  3681. return true;
  3682. }
  3683. if (InitE->isValueDependent())
  3684. return false;
  3685. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3686. // Wipe out any partially-computed value, to allow tracking that this
  3687. // evaluation failed.
  3688. Val = APValue();
  3689. return false;
  3690. }
  3691. return true;
  3692. }
  3693. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3694. bool OK = true;
  3695. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3696. OK &= EvaluateVarDecl(Info, VD);
  3697. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3698. for (auto *BD : DD->bindings())
  3699. if (auto *VD = BD->getHoldingVar())
  3700. OK &= EvaluateDecl(Info, VD);
  3701. return OK;
  3702. }
  3703. /// Evaluate a condition (either a variable declaration or an expression).
  3704. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3705. const Expr *Cond, bool &Result) {
  3706. FullExpressionRAII Scope(Info);
  3707. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3708. return false;
  3709. if (!EvaluateAsBooleanCondition(Cond, Result, Info))
  3710. return false;
  3711. return Scope.destroy();
  3712. }
  3713. namespace {
  3714. /// A location where the result (returned value) of evaluating a
  3715. /// statement should be stored.
  3716. struct StmtResult {
  3717. /// The APValue that should be filled in with the returned value.
  3718. APValue &Value;
  3719. /// The location containing the result, if any (used to support RVO).
  3720. const LValue *Slot;
  3721. };
  3722. struct TempVersionRAII {
  3723. CallStackFrame &Frame;
  3724. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3725. Frame.pushTempVersion();
  3726. }
  3727. ~TempVersionRAII() {
  3728. Frame.popTempVersion();
  3729. }
  3730. };
  3731. }
  3732. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3733. const Stmt *S,
  3734. const SwitchCase *SC = nullptr);
  3735. /// Evaluate the body of a loop, and translate the result as appropriate.
  3736. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3737. const Stmt *Body,
  3738. const SwitchCase *Case = nullptr) {
  3739. BlockScopeRAII Scope(Info);
  3740. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
  3741. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3742. ESR = ESR_Failed;
  3743. switch (ESR) {
  3744. case ESR_Break:
  3745. return ESR_Succeeded;
  3746. case ESR_Succeeded:
  3747. case ESR_Continue:
  3748. return ESR_Continue;
  3749. case ESR_Failed:
  3750. case ESR_Returned:
  3751. case ESR_CaseNotFound:
  3752. return ESR;
  3753. }
  3754. llvm_unreachable("Invalid EvalStmtResult!");
  3755. }
  3756. /// Evaluate a switch statement.
  3757. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3758. const SwitchStmt *SS) {
  3759. BlockScopeRAII Scope(Info);
  3760. // Evaluate the switch condition.
  3761. APSInt Value;
  3762. {
  3763. if (const Stmt *Init = SS->getInit()) {
  3764. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3765. if (ESR != ESR_Succeeded) {
  3766. if (ESR != ESR_Failed && !Scope.destroy())
  3767. ESR = ESR_Failed;
  3768. return ESR;
  3769. }
  3770. }
  3771. FullExpressionRAII CondScope(Info);
  3772. if (SS->getConditionVariable() &&
  3773. !EvaluateDecl(Info, SS->getConditionVariable()))
  3774. return ESR_Failed;
  3775. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3776. return ESR_Failed;
  3777. if (!CondScope.destroy())
  3778. return ESR_Failed;
  3779. }
  3780. // Find the switch case corresponding to the value of the condition.
  3781. // FIXME: Cache this lookup.
  3782. const SwitchCase *Found = nullptr;
  3783. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3784. SC = SC->getNextSwitchCase()) {
  3785. if (isa<DefaultStmt>(SC)) {
  3786. Found = SC;
  3787. continue;
  3788. }
  3789. const CaseStmt *CS = cast<CaseStmt>(SC);
  3790. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3791. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3792. : LHS;
  3793. if (LHS <= Value && Value <= RHS) {
  3794. Found = SC;
  3795. break;
  3796. }
  3797. }
  3798. if (!Found)
  3799. return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
  3800. // Search the switch body for the switch case and evaluate it from there.
  3801. EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
  3802. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3803. return ESR_Failed;
  3804. switch (ESR) {
  3805. case ESR_Break:
  3806. return ESR_Succeeded;
  3807. case ESR_Succeeded:
  3808. case ESR_Continue:
  3809. case ESR_Failed:
  3810. case ESR_Returned:
  3811. return ESR;
  3812. case ESR_CaseNotFound:
  3813. // This can only happen if the switch case is nested within a statement
  3814. // expression. We have no intention of supporting that.
  3815. Info.FFDiag(Found->getBeginLoc(),
  3816. diag::note_constexpr_stmt_expr_unsupported);
  3817. return ESR_Failed;
  3818. }
  3819. llvm_unreachable("Invalid EvalStmtResult!");
  3820. }
  3821. // Evaluate a statement.
  3822. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3823. const Stmt *S, const SwitchCase *Case) {
  3824. if (!Info.nextStep(S))
  3825. return ESR_Failed;
  3826. // If we're hunting down a 'case' or 'default' label, recurse through
  3827. // substatements until we hit the label.
  3828. if (Case) {
  3829. switch (S->getStmtClass()) {
  3830. case Stmt::CompoundStmtClass:
  3831. // FIXME: Precompute which substatement of a compound statement we
  3832. // would jump to, and go straight there rather than performing a
  3833. // linear scan each time.
  3834. case Stmt::LabelStmtClass:
  3835. case Stmt::AttributedStmtClass:
  3836. case Stmt::DoStmtClass:
  3837. break;
  3838. case Stmt::CaseStmtClass:
  3839. case Stmt::DefaultStmtClass:
  3840. if (Case == S)
  3841. Case = nullptr;
  3842. break;
  3843. case Stmt::IfStmtClass: {
  3844. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3845. // straight there rather than scanning both sides.
  3846. const IfStmt *IS = cast<IfStmt>(S);
  3847. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3848. // preceded by our switch label.
  3849. BlockScopeRAII Scope(Info);
  3850. // Step into the init statement in case it brings an (uninitialized)
  3851. // variable into scope.
  3852. if (const Stmt *Init = IS->getInit()) {
  3853. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3854. if (ESR != ESR_CaseNotFound) {
  3855. assert(ESR != ESR_Succeeded);
  3856. return ESR;
  3857. }
  3858. }
  3859. // Condition variable must be initialized if it exists.
  3860. // FIXME: We can skip evaluating the body if there's a condition
  3861. // variable, as there can't be any case labels within it.
  3862. // (The same is true for 'for' statements.)
  3863. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3864. if (ESR == ESR_Failed)
  3865. return ESR;
  3866. if (ESR != ESR_CaseNotFound)
  3867. return Scope.destroy() ? ESR : ESR_Failed;
  3868. if (!IS->getElse())
  3869. return ESR_CaseNotFound;
  3870. ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
  3871. if (ESR == ESR_Failed)
  3872. return ESR;
  3873. if (ESR != ESR_CaseNotFound)
  3874. return Scope.destroy() ? ESR : ESR_Failed;
  3875. return ESR_CaseNotFound;
  3876. }
  3877. case Stmt::WhileStmtClass: {
  3878. EvalStmtResult ESR =
  3879. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3880. if (ESR != ESR_Continue)
  3881. return ESR;
  3882. break;
  3883. }
  3884. case Stmt::ForStmtClass: {
  3885. const ForStmt *FS = cast<ForStmt>(S);
  3886. BlockScopeRAII Scope(Info);
  3887. // Step into the init statement in case it brings an (uninitialized)
  3888. // variable into scope.
  3889. if (const Stmt *Init = FS->getInit()) {
  3890. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3891. if (ESR != ESR_CaseNotFound) {
  3892. assert(ESR != ESR_Succeeded);
  3893. return ESR;
  3894. }
  3895. }
  3896. EvalStmtResult ESR =
  3897. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3898. if (ESR != ESR_Continue)
  3899. return ESR;
  3900. if (FS->getInc()) {
  3901. FullExpressionRAII IncScope(Info);
  3902. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  3903. return ESR_Failed;
  3904. }
  3905. break;
  3906. }
  3907. case Stmt::DeclStmtClass: {
  3908. // Start the lifetime of any uninitialized variables we encounter. They
  3909. // might be used by the selected branch of the switch.
  3910. const DeclStmt *DS = cast<DeclStmt>(S);
  3911. for (const auto *D : DS->decls()) {
  3912. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3913. if (VD->hasLocalStorage() && !VD->getInit())
  3914. if (!EvaluateVarDecl(Info, VD))
  3915. return ESR_Failed;
  3916. // FIXME: If the variable has initialization that can't be jumped
  3917. // over, bail out of any immediately-surrounding compound-statement
  3918. // too. There can't be any case labels here.
  3919. }
  3920. }
  3921. return ESR_CaseNotFound;
  3922. }
  3923. default:
  3924. return ESR_CaseNotFound;
  3925. }
  3926. }
  3927. switch (S->getStmtClass()) {
  3928. default:
  3929. if (const Expr *E = dyn_cast<Expr>(S)) {
  3930. // Don't bother evaluating beyond an expression-statement which couldn't
  3931. // be evaluated.
  3932. // FIXME: Do we need the FullExpressionRAII object here?
  3933. // VisitExprWithCleanups should create one when necessary.
  3934. FullExpressionRAII Scope(Info);
  3935. if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
  3936. return ESR_Failed;
  3937. return ESR_Succeeded;
  3938. }
  3939. Info.FFDiag(S->getBeginLoc());
  3940. return ESR_Failed;
  3941. case Stmt::NullStmtClass:
  3942. return ESR_Succeeded;
  3943. case Stmt::DeclStmtClass: {
  3944. const DeclStmt *DS = cast<DeclStmt>(S);
  3945. for (const auto *D : DS->decls()) {
  3946. // Each declaration initialization is its own full-expression.
  3947. FullExpressionRAII Scope(Info);
  3948. if (!EvaluateDecl(Info, D) && !Info.noteFailure())
  3949. return ESR_Failed;
  3950. if (!Scope.destroy())
  3951. return ESR_Failed;
  3952. }
  3953. return ESR_Succeeded;
  3954. }
  3955. case Stmt::ReturnStmtClass: {
  3956. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3957. FullExpressionRAII Scope(Info);
  3958. if (RetExpr &&
  3959. !(Result.Slot
  3960. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3961. : Evaluate(Result.Value, Info, RetExpr)))
  3962. return ESR_Failed;
  3963. return Scope.destroy() ? ESR_Returned : ESR_Failed;
  3964. }
  3965. case Stmt::CompoundStmtClass: {
  3966. BlockScopeRAII Scope(Info);
  3967. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3968. for (const auto *BI : CS->body()) {
  3969. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3970. if (ESR == ESR_Succeeded)
  3971. Case = nullptr;
  3972. else if (ESR != ESR_CaseNotFound) {
  3973. if (ESR != ESR_Failed && !Scope.destroy())
  3974. return ESR_Failed;
  3975. return ESR;
  3976. }
  3977. }
  3978. if (Case)
  3979. return ESR_CaseNotFound;
  3980. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  3981. }
  3982. case Stmt::IfStmtClass: {
  3983. const IfStmt *IS = cast<IfStmt>(S);
  3984. // Evaluate the condition, as either a var decl or as an expression.
  3985. BlockScopeRAII Scope(Info);
  3986. if (const Stmt *Init = IS->getInit()) {
  3987. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3988. if (ESR != ESR_Succeeded) {
  3989. if (ESR != ESR_Failed && !Scope.destroy())
  3990. return ESR_Failed;
  3991. return ESR;
  3992. }
  3993. }
  3994. bool Cond;
  3995. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3996. return ESR_Failed;
  3997. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3998. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3999. if (ESR != ESR_Succeeded) {
  4000. if (ESR != ESR_Failed && !Scope.destroy())
  4001. return ESR_Failed;
  4002. return ESR;
  4003. }
  4004. }
  4005. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4006. }
  4007. case Stmt::WhileStmtClass: {
  4008. const WhileStmt *WS = cast<WhileStmt>(S);
  4009. while (true) {
  4010. BlockScopeRAII Scope(Info);
  4011. bool Continue;
  4012. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  4013. Continue))
  4014. return ESR_Failed;
  4015. if (!Continue)
  4016. break;
  4017. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  4018. if (ESR != ESR_Continue) {
  4019. if (ESR != ESR_Failed && !Scope.destroy())
  4020. return ESR_Failed;
  4021. return ESR;
  4022. }
  4023. if (!Scope.destroy())
  4024. return ESR_Failed;
  4025. }
  4026. return ESR_Succeeded;
  4027. }
  4028. case Stmt::DoStmtClass: {
  4029. const DoStmt *DS = cast<DoStmt>(S);
  4030. bool Continue;
  4031. do {
  4032. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  4033. if (ESR != ESR_Continue)
  4034. return ESR;
  4035. Case = nullptr;
  4036. FullExpressionRAII CondScope(Info);
  4037. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
  4038. !CondScope.destroy())
  4039. return ESR_Failed;
  4040. } while (Continue);
  4041. return ESR_Succeeded;
  4042. }
  4043. case Stmt::ForStmtClass: {
  4044. const ForStmt *FS = cast<ForStmt>(S);
  4045. BlockScopeRAII ForScope(Info);
  4046. if (FS->getInit()) {
  4047. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4048. if (ESR != ESR_Succeeded) {
  4049. if (ESR != ESR_Failed && !ForScope.destroy())
  4050. return ESR_Failed;
  4051. return ESR;
  4052. }
  4053. }
  4054. while (true) {
  4055. BlockScopeRAII IterScope(Info);
  4056. bool Continue = true;
  4057. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  4058. FS->getCond(), Continue))
  4059. return ESR_Failed;
  4060. if (!Continue)
  4061. break;
  4062. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4063. if (ESR != ESR_Continue) {
  4064. if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
  4065. return ESR_Failed;
  4066. return ESR;
  4067. }
  4068. if (FS->getInc()) {
  4069. FullExpressionRAII IncScope(Info);
  4070. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  4071. return ESR_Failed;
  4072. }
  4073. if (!IterScope.destroy())
  4074. return ESR_Failed;
  4075. }
  4076. return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
  4077. }
  4078. case Stmt::CXXForRangeStmtClass: {
  4079. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  4080. BlockScopeRAII Scope(Info);
  4081. // Evaluate the init-statement if present.
  4082. if (FS->getInit()) {
  4083. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4084. if (ESR != ESR_Succeeded) {
  4085. if (ESR != ESR_Failed && !Scope.destroy())
  4086. return ESR_Failed;
  4087. return ESR;
  4088. }
  4089. }
  4090. // Initialize the __range variable.
  4091. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  4092. if (ESR != ESR_Succeeded) {
  4093. if (ESR != ESR_Failed && !Scope.destroy())
  4094. return ESR_Failed;
  4095. return ESR;
  4096. }
  4097. // Create the __begin and __end iterators.
  4098. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  4099. if (ESR != ESR_Succeeded) {
  4100. if (ESR != ESR_Failed && !Scope.destroy())
  4101. return ESR_Failed;
  4102. return ESR;
  4103. }
  4104. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  4105. if (ESR != ESR_Succeeded) {
  4106. if (ESR != ESR_Failed && !Scope.destroy())
  4107. return ESR_Failed;
  4108. return ESR;
  4109. }
  4110. while (true) {
  4111. // Condition: __begin != __end.
  4112. {
  4113. bool Continue = true;
  4114. FullExpressionRAII CondExpr(Info);
  4115. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  4116. return ESR_Failed;
  4117. if (!Continue)
  4118. break;
  4119. }
  4120. // User's variable declaration, initialized by *__begin.
  4121. BlockScopeRAII InnerScope(Info);
  4122. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  4123. if (ESR != ESR_Succeeded) {
  4124. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4125. return ESR_Failed;
  4126. return ESR;
  4127. }
  4128. // Loop body.
  4129. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4130. if (ESR != ESR_Continue) {
  4131. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4132. return ESR_Failed;
  4133. return ESR;
  4134. }
  4135. // Increment: ++__begin
  4136. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  4137. return ESR_Failed;
  4138. if (!InnerScope.destroy())
  4139. return ESR_Failed;
  4140. }
  4141. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4142. }
  4143. case Stmt::SwitchStmtClass:
  4144. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  4145. case Stmt::ContinueStmtClass:
  4146. return ESR_Continue;
  4147. case Stmt::BreakStmtClass:
  4148. return ESR_Break;
  4149. case Stmt::LabelStmtClass:
  4150. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  4151. case Stmt::AttributedStmtClass:
  4152. // As a general principle, C++11 attributes can be ignored without
  4153. // any semantic impact.
  4154. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  4155. Case);
  4156. case Stmt::CaseStmtClass:
  4157. case Stmt::DefaultStmtClass:
  4158. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  4159. case Stmt::CXXTryStmtClass:
  4160. // Evaluate try blocks by evaluating all sub statements.
  4161. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  4162. }
  4163. }
  4164. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  4165. /// default constructor. If so, we'll fold it whether or not it's marked as
  4166. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4167. /// so we need special handling.
  4168. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4169. const CXXConstructorDecl *CD,
  4170. bool IsValueInitialization) {
  4171. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4172. return false;
  4173. // Value-initialization does not call a trivial default constructor, so such a
  4174. // call is a core constant expression whether or not the constructor is
  4175. // constexpr.
  4176. if (!CD->isConstexpr() && !IsValueInitialization) {
  4177. if (Info.getLangOpts().CPlusPlus11) {
  4178. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4179. // we should be much more explicit about why it's not constexpr.
  4180. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4181. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4182. Info.Note(CD->getLocation(), diag::note_declared_at);
  4183. } else {
  4184. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4185. }
  4186. }
  4187. return true;
  4188. }
  4189. /// CheckConstexprFunction - Check that a function can be called in a constant
  4190. /// expression.
  4191. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4192. const FunctionDecl *Declaration,
  4193. const FunctionDecl *Definition,
  4194. const Stmt *Body) {
  4195. // Potential constant expressions can contain calls to declared, but not yet
  4196. // defined, constexpr functions.
  4197. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4198. Declaration->isConstexpr())
  4199. return false;
  4200. // Bail out if the function declaration itself is invalid. We will
  4201. // have produced a relevant diagnostic while parsing it, so just
  4202. // note the problematic sub-expression.
  4203. if (Declaration->isInvalidDecl()) {
  4204. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4205. return false;
  4206. }
  4207. // DR1872: An instantiated virtual constexpr function can't be called in a
  4208. // constant expression (prior to C++20). We can still constant-fold such a
  4209. // call.
  4210. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  4211. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4212. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4213. if (Definition && Definition->isInvalidDecl()) {
  4214. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4215. return false;
  4216. }
  4217. // Can we evaluate this function call?
  4218. if (Definition && Definition->isConstexpr() && Body)
  4219. return true;
  4220. if (Info.getLangOpts().CPlusPlus11) {
  4221. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4222. // If this function is not constexpr because it is an inherited
  4223. // non-constexpr constructor, diagnose that directly.
  4224. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4225. if (CD && CD->isInheritingConstructor()) {
  4226. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4227. if (!Inherited->isConstexpr())
  4228. DiagDecl = CD = Inherited;
  4229. }
  4230. // FIXME: If DiagDecl is an implicitly-declared special member function
  4231. // or an inheriting constructor, we should be much more explicit about why
  4232. // it's not constexpr.
  4233. if (CD && CD->isInheritingConstructor())
  4234. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4235. << CD->getInheritedConstructor().getConstructor()->getParent();
  4236. else
  4237. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4238. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4239. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4240. } else {
  4241. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4242. }
  4243. return false;
  4244. }
  4245. namespace {
  4246. struct CheckDynamicTypeHandler {
  4247. AccessKinds AccessKind;
  4248. typedef bool result_type;
  4249. bool failed() { return false; }
  4250. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4251. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4252. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4253. };
  4254. } // end anonymous namespace
  4255. /// Check that we can access the notional vptr of an object / determine its
  4256. /// dynamic type.
  4257. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4258. AccessKinds AK, bool Polymorphic) {
  4259. if (This.Designator.Invalid)
  4260. return false;
  4261. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4262. if (!Obj)
  4263. return false;
  4264. if (!Obj.Value) {
  4265. // The object is not usable in constant expressions, so we can't inspect
  4266. // its value to see if it's in-lifetime or what the active union members
  4267. // are. We can still check for a one-past-the-end lvalue.
  4268. if (This.Designator.isOnePastTheEnd() ||
  4269. This.Designator.isMostDerivedAnUnsizedArray()) {
  4270. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4271. ? diag::note_constexpr_access_past_end
  4272. : diag::note_constexpr_access_unsized_array)
  4273. << AK;
  4274. return false;
  4275. } else if (Polymorphic) {
  4276. // Conservatively refuse to perform a polymorphic operation if we would
  4277. // not be able to read a notional 'vptr' value.
  4278. APValue Val;
  4279. This.moveInto(Val);
  4280. QualType StarThisType =
  4281. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4282. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4283. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4284. return false;
  4285. }
  4286. return true;
  4287. }
  4288. CheckDynamicTypeHandler Handler{AK};
  4289. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4290. }
  4291. /// Check that the pointee of the 'this' pointer in a member function call is
  4292. /// either within its lifetime or in its period of construction or destruction.
  4293. static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4294. const LValue &This) {
  4295. return checkDynamicType(Info, E, This, AK_MemberCall, false);
  4296. }
  4297. struct DynamicType {
  4298. /// The dynamic class type of the object.
  4299. const CXXRecordDecl *Type;
  4300. /// The corresponding path length in the lvalue.
  4301. unsigned PathLength;
  4302. };
  4303. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4304. unsigned PathLength) {
  4305. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4306. Designator.Entries.size() && "invalid path length");
  4307. return (PathLength == Designator.MostDerivedPathLength)
  4308. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4309. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4310. }
  4311. /// Determine the dynamic type of an object.
  4312. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4313. LValue &This, AccessKinds AK) {
  4314. // If we don't have an lvalue denoting an object of class type, there is no
  4315. // meaningful dynamic type. (We consider objects of non-class type to have no
  4316. // dynamic type.)
  4317. if (!checkDynamicType(Info, E, This, AK, true))
  4318. return None;
  4319. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4320. // shouldn't happen other than in constant-folding situations, since literal
  4321. // types can't have virtual bases.
  4322. //
  4323. // Note that consumers of DynamicType assume that the type has no virtual
  4324. // bases, and will need modifications if this restriction is relaxed.
  4325. const CXXRecordDecl *Class =
  4326. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4327. if (!Class || Class->getNumVBases()) {
  4328. Info.FFDiag(E);
  4329. return None;
  4330. }
  4331. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4332. // binary search here instead. But the overwhelmingly common case is that
  4333. // we're not in the middle of a constructor, so it probably doesn't matter
  4334. // in practice.
  4335. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4336. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4337. PathLength <= Path.size(); ++PathLength) {
  4338. switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
  4339. Path.slice(0, PathLength))) {
  4340. case ConstructionPhase::Bases:
  4341. case ConstructionPhase::DestroyingBases:
  4342. // We're constructing or destroying a base class. This is not the dynamic
  4343. // type.
  4344. break;
  4345. case ConstructionPhase::None:
  4346. case ConstructionPhase::AfterBases:
  4347. case ConstructionPhase::Destroying:
  4348. // We've finished constructing the base classes and not yet started
  4349. // destroying them again, so this is the dynamic type.
  4350. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4351. PathLength};
  4352. }
  4353. }
  4354. // CWG issue 1517: we're constructing a base class of the object described by
  4355. // 'This', so that object has not yet begun its period of construction and
  4356. // any polymorphic operation on it results in undefined behavior.
  4357. Info.FFDiag(E);
  4358. return None;
  4359. }
  4360. /// Perform virtual dispatch.
  4361. static const CXXMethodDecl *HandleVirtualDispatch(
  4362. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4363. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4364. Optional<DynamicType> DynType =
  4365. ComputeDynamicType(Info, E, This, AK_MemberCall);
  4366. if (!DynType)
  4367. return nullptr;
  4368. // Find the final overrider. It must be declared in one of the classes on the
  4369. // path from the dynamic type to the static type.
  4370. // FIXME: If we ever allow literal types to have virtual base classes, that
  4371. // won't be true.
  4372. const CXXMethodDecl *Callee = Found;
  4373. unsigned PathLength = DynType->PathLength;
  4374. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4375. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4376. const CXXMethodDecl *Overrider =
  4377. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4378. if (Overrider) {
  4379. Callee = Overrider;
  4380. break;
  4381. }
  4382. }
  4383. // C++2a [class.abstract]p6:
  4384. // the effect of making a virtual call to a pure virtual function [...] is
  4385. // undefined
  4386. if (Callee->isPure()) {
  4387. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4388. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4389. return nullptr;
  4390. }
  4391. // If necessary, walk the rest of the path to determine the sequence of
  4392. // covariant adjustment steps to apply.
  4393. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4394. Found->getReturnType())) {
  4395. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4396. for (unsigned CovariantPathLength = PathLength + 1;
  4397. CovariantPathLength != This.Designator.Entries.size();
  4398. ++CovariantPathLength) {
  4399. const CXXRecordDecl *NextClass =
  4400. getBaseClassType(This.Designator, CovariantPathLength);
  4401. const CXXMethodDecl *Next =
  4402. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4403. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4404. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4405. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4406. }
  4407. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4408. CovariantAdjustmentPath.back()))
  4409. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4410. }
  4411. // Perform 'this' adjustment.
  4412. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4413. return nullptr;
  4414. return Callee;
  4415. }
  4416. /// Perform the adjustment from a value returned by a virtual function to
  4417. /// a value of the statically expected type, which may be a pointer or
  4418. /// reference to a base class of the returned type.
  4419. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4420. APValue &Result,
  4421. ArrayRef<QualType> Path) {
  4422. assert(Result.isLValue() &&
  4423. "unexpected kind of APValue for covariant return");
  4424. if (Result.isNullPointer())
  4425. return true;
  4426. LValue LVal;
  4427. LVal.setFrom(Info.Ctx, Result);
  4428. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4429. for (unsigned I = 1; I != Path.size(); ++I) {
  4430. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4431. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4432. if (OldClass != NewClass &&
  4433. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4434. return false;
  4435. OldClass = NewClass;
  4436. }
  4437. LVal.moveInto(Result);
  4438. return true;
  4439. }
  4440. /// Determine whether \p Base, which is known to be a direct base class of
  4441. /// \p Derived, is a public base class.
  4442. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4443. const CXXRecordDecl *Base) {
  4444. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4445. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4446. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4447. return BaseSpec.getAccessSpecifier() == AS_public;
  4448. }
  4449. llvm_unreachable("Base is not a direct base of Derived");
  4450. }
  4451. /// Apply the given dynamic cast operation on the provided lvalue.
  4452. ///
  4453. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4454. /// to find a suitable target subobject.
  4455. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4456. LValue &Ptr) {
  4457. // We can't do anything with a non-symbolic pointer value.
  4458. SubobjectDesignator &D = Ptr.Designator;
  4459. if (D.Invalid)
  4460. return false;
  4461. // C++ [expr.dynamic.cast]p6:
  4462. // If v is a null pointer value, the result is a null pointer value.
  4463. if (Ptr.isNullPointer() && !E->isGLValue())
  4464. return true;
  4465. // For all the other cases, we need the pointer to point to an object within
  4466. // its lifetime / period of construction / destruction, and we need to know
  4467. // its dynamic type.
  4468. Optional<DynamicType> DynType =
  4469. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4470. if (!DynType)
  4471. return false;
  4472. // C++ [expr.dynamic.cast]p7:
  4473. // If T is "pointer to cv void", then the result is a pointer to the most
  4474. // derived object
  4475. if (E->getType()->isVoidPointerType())
  4476. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4477. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4478. assert(C && "dynamic_cast target is not void pointer nor class");
  4479. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4480. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4481. // C++ [expr.dynamic.cast]p9:
  4482. if (!E->isGLValue()) {
  4483. // The value of a failed cast to pointer type is the null pointer value
  4484. // of the required result type.
  4485. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4486. Ptr.setNull(E->getType(), TargetVal);
  4487. return true;
  4488. }
  4489. // A failed cast to reference type throws [...] std::bad_cast.
  4490. unsigned DiagKind;
  4491. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4492. DynType->Type->isDerivedFrom(C)))
  4493. DiagKind = 0;
  4494. else if (!Paths || Paths->begin() == Paths->end())
  4495. DiagKind = 1;
  4496. else if (Paths->isAmbiguous(CQT))
  4497. DiagKind = 2;
  4498. else {
  4499. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4500. DiagKind = 3;
  4501. }
  4502. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4503. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4504. << Info.Ctx.getRecordType(DynType->Type)
  4505. << E->getType().getUnqualifiedType();
  4506. return false;
  4507. };
  4508. // Runtime check, phase 1:
  4509. // Walk from the base subobject towards the derived object looking for the
  4510. // target type.
  4511. for (int PathLength = Ptr.Designator.Entries.size();
  4512. PathLength >= (int)DynType->PathLength; --PathLength) {
  4513. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4514. if (declaresSameEntity(Class, C))
  4515. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4516. // We can only walk across public inheritance edges.
  4517. if (PathLength > (int)DynType->PathLength &&
  4518. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4519. Class))
  4520. return RuntimeCheckFailed(nullptr);
  4521. }
  4522. // Runtime check, phase 2:
  4523. // Search the dynamic type for an unambiguous public base of type C.
  4524. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4525. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4526. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4527. Paths.front().Access == AS_public) {
  4528. // Downcast to the dynamic type...
  4529. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4530. return false;
  4531. // ... then upcast to the chosen base class subobject.
  4532. for (CXXBasePathElement &Elem : Paths.front())
  4533. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4534. return false;
  4535. return true;
  4536. }
  4537. // Otherwise, the runtime check fails.
  4538. return RuntimeCheckFailed(&Paths);
  4539. }
  4540. namespace {
  4541. struct StartLifetimeOfUnionMemberHandler {
  4542. const FieldDecl *Field;
  4543. static const AccessKinds AccessKind = AK_Assign;
  4544. typedef bool result_type;
  4545. bool failed() { return false; }
  4546. bool found(APValue &Subobj, QualType SubobjType) {
  4547. // We are supposed to perform no initialization but begin the lifetime of
  4548. // the object. We interpret that as meaning to do what default
  4549. // initialization of the object would do if all constructors involved were
  4550. // trivial:
  4551. // * All base, non-variant member, and array element subobjects' lifetimes
  4552. // begin
  4553. // * No variant members' lifetimes begin
  4554. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4555. assert(SubobjType->isUnionType());
  4556. if (!declaresSameEntity(Subobj.getUnionField(), Field))
  4557. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4558. return true;
  4559. }
  4560. bool found(APSInt &Value, QualType SubobjType) {
  4561. llvm_unreachable("wrong value kind for union object");
  4562. }
  4563. bool found(APFloat &Value, QualType SubobjType) {
  4564. llvm_unreachable("wrong value kind for union object");
  4565. }
  4566. };
  4567. } // end anonymous namespace
  4568. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4569. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4570. /// operator whose left-hand side might involve a union member access. If it
  4571. /// does, implicitly start the lifetime of any accessed union elements per
  4572. /// C++20 [class.union]5.
  4573. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4574. const LValue &LHS) {
  4575. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4576. return false;
  4577. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4578. // C++ [class.union]p5:
  4579. // define the set S(E) of subexpressions of E as follows:
  4580. unsigned PathLength = LHS.Designator.Entries.size();
  4581. for (const Expr *E = LHSExpr; E != nullptr;) {
  4582. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4583. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4584. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4585. if (!FD)
  4586. break;
  4587. // ... and also contains A.B if B names a union member
  4588. if (FD->getParent()->isUnion())
  4589. UnionPathLengths.push_back({PathLength - 1, FD});
  4590. E = ME->getBase();
  4591. --PathLength;
  4592. assert(declaresSameEntity(FD,
  4593. LHS.Designator.Entries[PathLength]
  4594. .getAsBaseOrMember().getPointer()));
  4595. // -- If E is of the form A[B] and is interpreted as a built-in array
  4596. // subscripting operator, S(E) is [S(the array operand, if any)].
  4597. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4598. // Step over an ArrayToPointerDecay implicit cast.
  4599. auto *Base = ASE->getBase()->IgnoreImplicit();
  4600. if (!Base->getType()->isArrayType())
  4601. break;
  4602. E = Base;
  4603. --PathLength;
  4604. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4605. // Step over a derived-to-base conversion.
  4606. E = ICE->getSubExpr();
  4607. if (ICE->getCastKind() == CK_NoOp)
  4608. continue;
  4609. if (ICE->getCastKind() != CK_DerivedToBase &&
  4610. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4611. break;
  4612. // Walk path backwards as we walk up from the base to the derived class.
  4613. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4614. --PathLength;
  4615. (void)Elt;
  4616. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4617. LHS.Designator.Entries[PathLength]
  4618. .getAsBaseOrMember().getPointer()));
  4619. }
  4620. // -- Otherwise, S(E) is empty.
  4621. } else {
  4622. break;
  4623. }
  4624. }
  4625. // Common case: no unions' lifetimes are started.
  4626. if (UnionPathLengths.empty())
  4627. return true;
  4628. // if modification of X [would access an inactive union member], an object
  4629. // of the type of X is implicitly created
  4630. CompleteObject Obj =
  4631. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4632. if (!Obj)
  4633. return false;
  4634. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4635. llvm::reverse(UnionPathLengths)) {
  4636. // Form a designator for the union object.
  4637. SubobjectDesignator D = LHS.Designator;
  4638. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4639. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4640. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4641. return false;
  4642. }
  4643. return true;
  4644. }
  4645. /// Determine if a class has any fields that might need to be copied by a
  4646. /// trivial copy or move operation.
  4647. static bool hasFields(const CXXRecordDecl *RD) {
  4648. if (!RD || RD->isEmpty())
  4649. return false;
  4650. for (auto *FD : RD->fields()) {
  4651. if (FD->isUnnamedBitfield())
  4652. continue;
  4653. return true;
  4654. }
  4655. for (auto &Base : RD->bases())
  4656. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4657. return true;
  4658. return false;
  4659. }
  4660. namespace {
  4661. typedef SmallVector<APValue, 8> ArgVector;
  4662. }
  4663. /// EvaluateArgs - Evaluate the arguments to a function call.
  4664. static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
  4665. EvalInfo &Info, const FunctionDecl *Callee) {
  4666. bool Success = true;
  4667. llvm::SmallBitVector ForbiddenNullArgs;
  4668. if (Callee->hasAttr<NonNullAttr>()) {
  4669. ForbiddenNullArgs.resize(Args.size());
  4670. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  4671. if (!Attr->args_size()) {
  4672. ForbiddenNullArgs.set();
  4673. break;
  4674. } else
  4675. for (auto Idx : Attr->args()) {
  4676. unsigned ASTIdx = Idx.getASTIndex();
  4677. if (ASTIdx >= Args.size())
  4678. continue;
  4679. ForbiddenNullArgs[ASTIdx] = 1;
  4680. }
  4681. }
  4682. }
  4683. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4684. I != E; ++I) {
  4685. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4686. // If we're checking for a potential constant expression, evaluate all
  4687. // initializers even if some of them fail.
  4688. if (!Info.noteFailure())
  4689. return false;
  4690. Success = false;
  4691. } else if (!ForbiddenNullArgs.empty() &&
  4692. ForbiddenNullArgs[I - Args.begin()] &&
  4693. ArgValues[I - Args.begin()].isNullPointer()) {
  4694. Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
  4695. if (!Info.noteFailure())
  4696. return false;
  4697. Success = false;
  4698. }
  4699. }
  4700. return Success;
  4701. }
  4702. /// Evaluate a function call.
  4703. static bool HandleFunctionCall(SourceLocation CallLoc,
  4704. const FunctionDecl *Callee, const LValue *This,
  4705. ArrayRef<const Expr*> Args, const Stmt *Body,
  4706. EvalInfo &Info, APValue &Result,
  4707. const LValue *ResultSlot) {
  4708. ArgVector ArgValues(Args.size());
  4709. if (!EvaluateArgs(Args, ArgValues, Info, Callee))
  4710. return false;
  4711. if (!Info.CheckCallLimit(CallLoc))
  4712. return false;
  4713. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4714. // For a trivial copy or move assignment, perform an APValue copy. This is
  4715. // essential for unions, where the operations performed by the assignment
  4716. // operator cannot be represented as statements.
  4717. //
  4718. // Skip this for non-union classes with no fields; in that case, the defaulted
  4719. // copy/move does not actually read the object.
  4720. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4721. if (MD && MD->isDefaulted() &&
  4722. (MD->getParent()->isUnion() ||
  4723. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4724. assert(This &&
  4725. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4726. LValue RHS;
  4727. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4728. APValue RHSValue;
  4729. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
  4730. RHSValue, MD->getParent()->isUnion()))
  4731. return false;
  4732. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4733. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4734. return false;
  4735. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4736. RHSValue))
  4737. return false;
  4738. This->moveInto(Result);
  4739. return true;
  4740. } else if (MD && isLambdaCallOperator(MD)) {
  4741. // We're in a lambda; determine the lambda capture field maps unless we're
  4742. // just constexpr checking a lambda's call operator. constexpr checking is
  4743. // done before the captures have been added to the closure object (unless
  4744. // we're inferring constexpr-ness), so we don't have access to them in this
  4745. // case. But since we don't need the captures to constexpr check, we can
  4746. // just ignore them.
  4747. if (!Info.checkingPotentialConstantExpression())
  4748. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4749. Frame.LambdaThisCaptureField);
  4750. }
  4751. StmtResult Ret = {Result, ResultSlot};
  4752. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4753. if (ESR == ESR_Succeeded) {
  4754. if (Callee->getReturnType()->isVoidType())
  4755. return true;
  4756. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4757. }
  4758. return ESR == ESR_Returned;
  4759. }
  4760. /// Evaluate a constructor call.
  4761. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4762. APValue *ArgValues,
  4763. const CXXConstructorDecl *Definition,
  4764. EvalInfo &Info, APValue &Result) {
  4765. SourceLocation CallLoc = E->getExprLoc();
  4766. if (!Info.CheckCallLimit(CallLoc))
  4767. return false;
  4768. const CXXRecordDecl *RD = Definition->getParent();
  4769. if (RD->getNumVBases()) {
  4770. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4771. return false;
  4772. }
  4773. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4774. Info,
  4775. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4776. RD->getNumBases());
  4777. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4778. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4779. // wasteful.
  4780. APValue RetVal;
  4781. StmtResult Ret = {RetVal, nullptr};
  4782. // If it's a delegating constructor, delegate.
  4783. if (Definition->isDelegatingConstructor()) {
  4784. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4785. {
  4786. FullExpressionRAII InitScope(Info);
  4787. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
  4788. !InitScope.destroy())
  4789. return false;
  4790. }
  4791. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4792. }
  4793. // For a trivial copy or move constructor, perform an APValue copy. This is
  4794. // essential for unions (or classes with anonymous union members), where the
  4795. // operations performed by the constructor cannot be represented by
  4796. // ctor-initializers.
  4797. //
  4798. // Skip this for empty non-union classes; we should not perform an
  4799. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4800. // actually read them.
  4801. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4802. (Definition->getParent()->isUnion() ||
  4803. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4804. LValue RHS;
  4805. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4806. return handleLValueToRValueConversion(
  4807. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4808. RHS, Result, Definition->getParent()->isUnion());
  4809. }
  4810. // Reserve space for the struct members.
  4811. if (!RD->isUnion() && !Result.hasValue())
  4812. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4813. std::distance(RD->field_begin(), RD->field_end()));
  4814. if (RD->isInvalidDecl()) return false;
  4815. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4816. // A scope for temporaries lifetime-extended by reference members.
  4817. BlockScopeRAII LifetimeExtendedScope(Info);
  4818. bool Success = true;
  4819. unsigned BasesSeen = 0;
  4820. #ifndef NDEBUG
  4821. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4822. #endif
  4823. CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
  4824. auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
  4825. // We might be initializing the same field again if this is an indirect
  4826. // field initialization.
  4827. if (FieldIt == RD->field_end() ||
  4828. FieldIt->getFieldIndex() > FD->getFieldIndex()) {
  4829. assert(Indirect && "fields out of order?");
  4830. return;
  4831. }
  4832. // Default-initialize any fields with no explicit initializer.
  4833. for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
  4834. assert(FieldIt != RD->field_end() && "missing field?");
  4835. if (!FieldIt->isUnnamedBitfield())
  4836. Result.getStructField(FieldIt->getFieldIndex()) =
  4837. getDefaultInitValue(FieldIt->getType());
  4838. }
  4839. ++FieldIt;
  4840. };
  4841. for (const auto *I : Definition->inits()) {
  4842. LValue Subobject = This;
  4843. LValue SubobjectParent = This;
  4844. APValue *Value = &Result;
  4845. // Determine the subobject to initialize.
  4846. FieldDecl *FD = nullptr;
  4847. if (I->isBaseInitializer()) {
  4848. QualType BaseType(I->getBaseClass(), 0);
  4849. #ifndef NDEBUG
  4850. // Non-virtual base classes are initialized in the order in the class
  4851. // definition. We have already checked for virtual base classes.
  4852. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4853. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4854. "base class initializers not in expected order");
  4855. ++BaseIt;
  4856. #endif
  4857. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4858. BaseType->getAsCXXRecordDecl(), &Layout))
  4859. return false;
  4860. Value = &Result.getStructBase(BasesSeen++);
  4861. } else if ((FD = I->getMember())) {
  4862. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4863. return false;
  4864. if (RD->isUnion()) {
  4865. Result = APValue(FD);
  4866. Value = &Result.getUnionValue();
  4867. } else {
  4868. SkipToField(FD, false);
  4869. Value = &Result.getStructField(FD->getFieldIndex());
  4870. }
  4871. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4872. // Walk the indirect field decl's chain to find the object to initialize,
  4873. // and make sure we've initialized every step along it.
  4874. auto IndirectFieldChain = IFD->chain();
  4875. for (auto *C : IndirectFieldChain) {
  4876. FD = cast<FieldDecl>(C);
  4877. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4878. // Switch the union field if it differs. This happens if we had
  4879. // preceding zero-initialization, and we're now initializing a union
  4880. // subobject other than the first.
  4881. // FIXME: In this case, the values of the other subobjects are
  4882. // specified, since zero-initialization sets all padding bits to zero.
  4883. if (!Value->hasValue() ||
  4884. (Value->isUnion() && Value->getUnionField() != FD)) {
  4885. if (CD->isUnion())
  4886. *Value = APValue(FD);
  4887. else
  4888. // FIXME: This immediately starts the lifetime of all members of an
  4889. // anonymous struct. It would be preferable to strictly start member
  4890. // lifetime in initialization order.
  4891. *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
  4892. }
  4893. // Store Subobject as its parent before updating it for the last element
  4894. // in the chain.
  4895. if (C == IndirectFieldChain.back())
  4896. SubobjectParent = Subobject;
  4897. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4898. return false;
  4899. if (CD->isUnion())
  4900. Value = &Value->getUnionValue();
  4901. else {
  4902. if (C == IndirectFieldChain.front() && !RD->isUnion())
  4903. SkipToField(FD, true);
  4904. Value = &Value->getStructField(FD->getFieldIndex());
  4905. }
  4906. }
  4907. } else {
  4908. llvm_unreachable("unknown base initializer kind");
  4909. }
  4910. // Need to override This for implicit field initializers as in this case
  4911. // This refers to innermost anonymous struct/union containing initializer,
  4912. // not to currently constructed class.
  4913. const Expr *Init = I->getInit();
  4914. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4915. isa<CXXDefaultInitExpr>(Init));
  4916. FullExpressionRAII InitScope(Info);
  4917. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4918. (FD && FD->isBitField() &&
  4919. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4920. // If we're checking for a potential constant expression, evaluate all
  4921. // initializers even if some of them fail.
  4922. if (!Info.noteFailure())
  4923. return false;
  4924. Success = false;
  4925. }
  4926. // This is the point at which the dynamic type of the object becomes this
  4927. // class type.
  4928. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  4929. EvalObj.finishedConstructingBases();
  4930. }
  4931. // Default-initialize any remaining fields.
  4932. if (!RD->isUnion()) {
  4933. for (; FieldIt != RD->field_end(); ++FieldIt) {
  4934. if (!FieldIt->isUnnamedBitfield())
  4935. Result.getStructField(FieldIt->getFieldIndex()) =
  4936. getDefaultInitValue(FieldIt->getType());
  4937. }
  4938. }
  4939. return Success &&
  4940. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
  4941. LifetimeExtendedScope.destroy();
  4942. }
  4943. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4944. ArrayRef<const Expr*> Args,
  4945. const CXXConstructorDecl *Definition,
  4946. EvalInfo &Info, APValue &Result) {
  4947. ArgVector ArgValues(Args.size());
  4948. if (!EvaluateArgs(Args, ArgValues, Info, Definition))
  4949. return false;
  4950. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4951. Info, Result);
  4952. }
  4953. static bool HandleDestructorCallImpl(EvalInfo &Info, SourceLocation CallLoc,
  4954. const LValue &This, APValue &Value,
  4955. QualType T) {
  4956. // Objects can only be destroyed while they're within their lifetimes.
  4957. // FIXME: We have no representation for whether an object of type nullptr_t
  4958. // is in its lifetime; it usually doesn't matter. Perhaps we should model it
  4959. // as indeterminate instead?
  4960. if (Value.isAbsent() && !T->isNullPtrType()) {
  4961. APValue Printable;
  4962. This.moveInto(Printable);
  4963. Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
  4964. << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
  4965. return false;
  4966. }
  4967. // Invent an expression for location purposes.
  4968. // FIXME: We shouldn't need to do this.
  4969. OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
  4970. // For arrays, destroy elements right-to-left.
  4971. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
  4972. uint64_t Size = CAT->getSize().getZExtValue();
  4973. QualType ElemT = CAT->getElementType();
  4974. LValue ElemLV = This;
  4975. ElemLV.addArray(Info, &LocE, CAT);
  4976. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
  4977. return false;
  4978. // Ensure that we have actual array elements available to destroy; the
  4979. // destructors might mutate the value, so we can't run them on the array
  4980. // filler.
  4981. if (Size && Size > Value.getArrayInitializedElts())
  4982. expandArray(Value, Value.getArraySize() - 1);
  4983. for (; Size != 0; --Size) {
  4984. APValue &Elem = Value.getArrayInitializedElt(Size - 1);
  4985. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
  4986. !HandleDestructorCallImpl(Info, CallLoc, ElemLV, Elem, ElemT))
  4987. return false;
  4988. }
  4989. // End the lifetime of this array now.
  4990. Value = APValue();
  4991. return true;
  4992. }
  4993. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4994. if (!RD) {
  4995. if (T.isDestructedType()) {
  4996. Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
  4997. return false;
  4998. }
  4999. Value = APValue();
  5000. return true;
  5001. }
  5002. if (RD->getNumVBases()) {
  5003. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5004. return false;
  5005. }
  5006. const CXXDestructorDecl *DD = RD->getDestructor();
  5007. if (!DD && !RD->hasTrivialDestructor()) {
  5008. Info.FFDiag(CallLoc);
  5009. return false;
  5010. }
  5011. if (!DD || DD->isTrivial() ||
  5012. (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
  5013. // A trivial destructor just ends the lifetime of the object. Check for
  5014. // this case before checking for a body, because we might not bother
  5015. // building a body for a trivial destructor. Note that it doesn't matter
  5016. // whether the destructor is constexpr in this case; all trivial
  5017. // destructors are constexpr.
  5018. //
  5019. // If an anonymous union would be destroyed, some enclosing destructor must
  5020. // have been explicitly defined, and the anonymous union destruction should
  5021. // have no effect.
  5022. Value = APValue();
  5023. return true;
  5024. }
  5025. if (!Info.CheckCallLimit(CallLoc))
  5026. return false;
  5027. const FunctionDecl *Definition = nullptr;
  5028. const Stmt *Body = DD->getBody(Definition);
  5029. if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
  5030. return false;
  5031. CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
  5032. // We're now in the period of destruction of this object.
  5033. unsigned BasesLeft = RD->getNumBases();
  5034. EvalInfo::EvaluatingDestructorRAII EvalObj(
  5035. Info,
  5036. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
  5037. if (!EvalObj.DidInsert) {
  5038. // C++2a [class.dtor]p19:
  5039. // the behavior is undefined if the destructor is invoked for an object
  5040. // whose lifetime has ended
  5041. // (Note that formally the lifetime ends when the period of destruction
  5042. // begins, even though certain uses of the object remain valid until the
  5043. // period of destruction ends.)
  5044. Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
  5045. return false;
  5046. }
  5047. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5048. // wasteful.
  5049. APValue RetVal;
  5050. StmtResult Ret = {RetVal, nullptr};
  5051. if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
  5052. return false;
  5053. // A union destructor does not implicitly destroy its members.
  5054. if (RD->isUnion())
  5055. return true;
  5056. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5057. // We don't have a good way to iterate fields in reverse, so collect all the
  5058. // fields first and then walk them backwards.
  5059. SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
  5060. for (const FieldDecl *FD : llvm::reverse(Fields)) {
  5061. if (FD->isUnnamedBitfield())
  5062. continue;
  5063. LValue Subobject = This;
  5064. if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
  5065. return false;
  5066. APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
  5067. if (!HandleDestructorCallImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5068. FD->getType()))
  5069. return false;
  5070. }
  5071. if (BasesLeft != 0)
  5072. EvalObj.startedDestroyingBases();
  5073. // Destroy base classes in reverse order.
  5074. for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
  5075. --BasesLeft;
  5076. QualType BaseType = Base.getType();
  5077. LValue Subobject = This;
  5078. if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
  5079. BaseType->getAsCXXRecordDecl(), &Layout))
  5080. return false;
  5081. APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
  5082. if (!HandleDestructorCallImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5083. BaseType))
  5084. return false;
  5085. }
  5086. assert(BasesLeft == 0 && "NumBases was wrong?");
  5087. // The period of destruction ends now. The object is gone.
  5088. Value = APValue();
  5089. return true;
  5090. }
  5091. static bool HandleDestructorCall(EvalInfo &Info, SourceLocation Loc,
  5092. APValue::LValueBase LVBase, APValue &Value,
  5093. QualType T) {
  5094. // If we've had an unmodeled side-effect, we can't rely on mutable state
  5095. // (such as the object we're about to destroy) being correct.
  5096. if (Info.EvalStatus.HasSideEffects)
  5097. return false;
  5098. LValue LV;
  5099. LV.set({LVBase});
  5100. return HandleDestructorCallImpl(Info, Loc, LV, Value, T);
  5101. }
  5102. //===----------------------------------------------------------------------===//
  5103. // Generic Evaluation
  5104. //===----------------------------------------------------------------------===//
  5105. namespace {
  5106. class BitCastBuffer {
  5107. // FIXME: We're going to need bit-level granularity when we support
  5108. // bit-fields.
  5109. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  5110. // we don't support a host or target where that is the case. Still, we should
  5111. // use a more generic type in case we ever do.
  5112. SmallVector<Optional<unsigned char>, 32> Bytes;
  5113. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  5114. "Need at least 8 bit unsigned char");
  5115. bool TargetIsLittleEndian;
  5116. public:
  5117. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  5118. : Bytes(Width.getQuantity()),
  5119. TargetIsLittleEndian(TargetIsLittleEndian) {}
  5120. LLVM_NODISCARD
  5121. bool readObject(CharUnits Offset, CharUnits Width,
  5122. SmallVectorImpl<unsigned char> &Output) const {
  5123. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  5124. // If a byte of an integer is uninitialized, then the whole integer is
  5125. // uninitalized.
  5126. if (!Bytes[I.getQuantity()])
  5127. return false;
  5128. Output.push_back(*Bytes[I.getQuantity()]);
  5129. }
  5130. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5131. std::reverse(Output.begin(), Output.end());
  5132. return true;
  5133. }
  5134. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  5135. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5136. std::reverse(Input.begin(), Input.end());
  5137. size_t Index = 0;
  5138. for (unsigned char Byte : Input) {
  5139. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  5140. Bytes[Offset.getQuantity() + Index] = Byte;
  5141. ++Index;
  5142. }
  5143. }
  5144. size_t size() { return Bytes.size(); }
  5145. };
  5146. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  5147. /// target would represent the value at runtime.
  5148. class APValueToBufferConverter {
  5149. EvalInfo &Info;
  5150. BitCastBuffer Buffer;
  5151. const CastExpr *BCE;
  5152. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  5153. const CastExpr *BCE)
  5154. : Info(Info),
  5155. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  5156. BCE(BCE) {}
  5157. bool visit(const APValue &Val, QualType Ty) {
  5158. return visit(Val, Ty, CharUnits::fromQuantity(0));
  5159. }
  5160. // Write out Val with type Ty into Buffer starting at Offset.
  5161. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  5162. assert((size_t)Offset.getQuantity() <= Buffer.size());
  5163. // As a special case, nullptr_t has an indeterminate value.
  5164. if (Ty->isNullPtrType())
  5165. return true;
  5166. // Dig through Src to find the byte at SrcOffset.
  5167. switch (Val.getKind()) {
  5168. case APValue::Indeterminate:
  5169. case APValue::None:
  5170. return true;
  5171. case APValue::Int:
  5172. return visitInt(Val.getInt(), Ty, Offset);
  5173. case APValue::Float:
  5174. return visitFloat(Val.getFloat(), Ty, Offset);
  5175. case APValue::Array:
  5176. return visitArray(Val, Ty, Offset);
  5177. case APValue::Struct:
  5178. return visitRecord(Val, Ty, Offset);
  5179. case APValue::ComplexInt:
  5180. case APValue::ComplexFloat:
  5181. case APValue::Vector:
  5182. case APValue::FixedPoint:
  5183. // FIXME: We should support these.
  5184. case APValue::Union:
  5185. case APValue::MemberPointer:
  5186. case APValue::AddrLabelDiff: {
  5187. Info.FFDiag(BCE->getBeginLoc(),
  5188. diag::note_constexpr_bit_cast_unsupported_type)
  5189. << Ty;
  5190. return false;
  5191. }
  5192. case APValue::LValue:
  5193. llvm_unreachable("LValue subobject in bit_cast?");
  5194. }
  5195. llvm_unreachable("Unhandled APValue::ValueKind");
  5196. }
  5197. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  5198. const RecordDecl *RD = Ty->getAsRecordDecl();
  5199. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5200. // Visit the base classes.
  5201. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5202. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5203. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5204. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5205. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  5206. Layout.getBaseClassOffset(BaseDecl) + Offset))
  5207. return false;
  5208. }
  5209. }
  5210. // Visit the fields.
  5211. unsigned FieldIdx = 0;
  5212. for (FieldDecl *FD : RD->fields()) {
  5213. if (FD->isBitField()) {
  5214. Info.FFDiag(BCE->getBeginLoc(),
  5215. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5216. return false;
  5217. }
  5218. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5219. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  5220. "only bit-fields can have sub-char alignment");
  5221. CharUnits FieldOffset =
  5222. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  5223. QualType FieldTy = FD->getType();
  5224. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  5225. return false;
  5226. ++FieldIdx;
  5227. }
  5228. return true;
  5229. }
  5230. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  5231. const auto *CAT =
  5232. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  5233. if (!CAT)
  5234. return false;
  5235. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  5236. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  5237. unsigned ArraySize = Val.getArraySize();
  5238. // First, initialize the initialized elements.
  5239. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  5240. const APValue &SubObj = Val.getArrayInitializedElt(I);
  5241. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  5242. return false;
  5243. }
  5244. // Next, initialize the rest of the array using the filler.
  5245. if (Val.hasArrayFiller()) {
  5246. const APValue &Filler = Val.getArrayFiller();
  5247. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  5248. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  5249. return false;
  5250. }
  5251. }
  5252. return true;
  5253. }
  5254. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  5255. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  5256. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  5257. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  5258. Buffer.writeObject(Offset, Bytes);
  5259. return true;
  5260. }
  5261. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  5262. APSInt AsInt(Val.bitcastToAPInt());
  5263. return visitInt(AsInt, Ty, Offset);
  5264. }
  5265. public:
  5266. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  5267. const CastExpr *BCE) {
  5268. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  5269. APValueToBufferConverter Converter(Info, DstSize, BCE);
  5270. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  5271. return None;
  5272. return Converter.Buffer;
  5273. }
  5274. };
  5275. /// Write an BitCastBuffer into an APValue.
  5276. class BufferToAPValueConverter {
  5277. EvalInfo &Info;
  5278. const BitCastBuffer &Buffer;
  5279. const CastExpr *BCE;
  5280. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  5281. const CastExpr *BCE)
  5282. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  5283. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  5284. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  5285. // Ideally this will be unreachable.
  5286. llvm::NoneType unsupportedType(QualType Ty) {
  5287. Info.FFDiag(BCE->getBeginLoc(),
  5288. diag::note_constexpr_bit_cast_unsupported_type)
  5289. << Ty;
  5290. return None;
  5291. }
  5292. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  5293. const EnumType *EnumSugar = nullptr) {
  5294. if (T->isNullPtrType()) {
  5295. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  5296. return APValue((Expr *)nullptr,
  5297. /*Offset=*/CharUnits::fromQuantity(NullValue),
  5298. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  5299. }
  5300. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  5301. SmallVector<uint8_t, 8> Bytes;
  5302. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  5303. // If this is std::byte or unsigned char, then its okay to store an
  5304. // indeterminate value.
  5305. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  5306. bool IsUChar =
  5307. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  5308. T->isSpecificBuiltinType(BuiltinType::Char_U));
  5309. if (!IsStdByte && !IsUChar) {
  5310. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  5311. Info.FFDiag(BCE->getExprLoc(),
  5312. diag::note_constexpr_bit_cast_indet_dest)
  5313. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  5314. return None;
  5315. }
  5316. return APValue::IndeterminateValue();
  5317. }
  5318. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  5319. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  5320. if (T->isIntegralOrEnumerationType()) {
  5321. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  5322. return APValue(Val);
  5323. }
  5324. if (T->isRealFloatingType()) {
  5325. const llvm::fltSemantics &Semantics =
  5326. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  5327. return APValue(APFloat(Semantics, Val));
  5328. }
  5329. return unsupportedType(QualType(T, 0));
  5330. }
  5331. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  5332. const RecordDecl *RD = RTy->getAsRecordDecl();
  5333. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5334. unsigned NumBases = 0;
  5335. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5336. NumBases = CXXRD->getNumBases();
  5337. APValue ResultVal(APValue::UninitStruct(), NumBases,
  5338. std::distance(RD->field_begin(), RD->field_end()));
  5339. // Visit the base classes.
  5340. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5341. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5342. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5343. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5344. if (BaseDecl->isEmpty() ||
  5345. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  5346. continue;
  5347. Optional<APValue> SubObj = visitType(
  5348. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  5349. if (!SubObj)
  5350. return None;
  5351. ResultVal.getStructBase(I) = *SubObj;
  5352. }
  5353. }
  5354. // Visit the fields.
  5355. unsigned FieldIdx = 0;
  5356. for (FieldDecl *FD : RD->fields()) {
  5357. // FIXME: We don't currently support bit-fields. A lot of the logic for
  5358. // this is in CodeGen, so we need to factor it around.
  5359. if (FD->isBitField()) {
  5360. Info.FFDiag(BCE->getBeginLoc(),
  5361. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5362. return None;
  5363. }
  5364. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5365. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  5366. CharUnits FieldOffset =
  5367. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  5368. Offset;
  5369. QualType FieldTy = FD->getType();
  5370. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  5371. if (!SubObj)
  5372. return None;
  5373. ResultVal.getStructField(FieldIdx) = *SubObj;
  5374. ++FieldIdx;
  5375. }
  5376. return ResultVal;
  5377. }
  5378. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  5379. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  5380. assert(!RepresentationType.isNull() &&
  5381. "enum forward decl should be caught by Sema");
  5382. const BuiltinType *AsBuiltin =
  5383. RepresentationType.getCanonicalType()->getAs<BuiltinType>();
  5384. assert(AsBuiltin && "non-integral enum underlying type?");
  5385. // Recurse into the underlying type. Treat std::byte transparently as
  5386. // unsigned char.
  5387. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  5388. }
  5389. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  5390. size_t Size = Ty->getSize().getLimitedValue();
  5391. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  5392. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  5393. for (size_t I = 0; I != Size; ++I) {
  5394. Optional<APValue> ElementValue =
  5395. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  5396. if (!ElementValue)
  5397. return None;
  5398. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  5399. }
  5400. return ArrayValue;
  5401. }
  5402. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  5403. return unsupportedType(QualType(Ty, 0));
  5404. }
  5405. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  5406. QualType Can = Ty.getCanonicalType();
  5407. switch (Can->getTypeClass()) {
  5408. #define TYPE(Class, Base) \
  5409. case Type::Class: \
  5410. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  5411. #define ABSTRACT_TYPE(Class, Base)
  5412. #define NON_CANONICAL_TYPE(Class, Base) \
  5413. case Type::Class: \
  5414. llvm_unreachable("non-canonical type should be impossible!");
  5415. #define DEPENDENT_TYPE(Class, Base) \
  5416. case Type::Class: \
  5417. llvm_unreachable( \
  5418. "dependent types aren't supported in the constant evaluator!");
  5419. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  5420. case Type::Class: \
  5421. llvm_unreachable("either dependent or not canonical!");
  5422. #include "clang/AST/TypeNodes.def"
  5423. }
  5424. llvm_unreachable("Unhandled Type::TypeClass");
  5425. }
  5426. public:
  5427. // Pull out a full value of type DstType.
  5428. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  5429. const CastExpr *BCE) {
  5430. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  5431. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  5432. }
  5433. };
  5434. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  5435. QualType Ty, EvalInfo *Info,
  5436. const ASTContext &Ctx,
  5437. bool CheckingDest) {
  5438. Ty = Ty.getCanonicalType();
  5439. auto diag = [&](int Reason) {
  5440. if (Info)
  5441. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  5442. << CheckingDest << (Reason == 4) << Reason;
  5443. return false;
  5444. };
  5445. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  5446. if (Info)
  5447. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  5448. << NoteTy << Construct << Ty;
  5449. return false;
  5450. };
  5451. if (Ty->isUnionType())
  5452. return diag(0);
  5453. if (Ty->isPointerType())
  5454. return diag(1);
  5455. if (Ty->isMemberPointerType())
  5456. return diag(2);
  5457. if (Ty.isVolatileQualified())
  5458. return diag(3);
  5459. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  5460. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  5461. for (CXXBaseSpecifier &BS : CXXRD->bases())
  5462. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  5463. CheckingDest))
  5464. return note(1, BS.getType(), BS.getBeginLoc());
  5465. }
  5466. for (FieldDecl *FD : Record->fields()) {
  5467. if (FD->getType()->isReferenceType())
  5468. return diag(4);
  5469. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5470. CheckingDest))
  5471. return note(0, FD->getType(), FD->getBeginLoc());
  5472. }
  5473. }
  5474. if (Ty->isArrayType() &&
  5475. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5476. Info, Ctx, CheckingDest))
  5477. return false;
  5478. return true;
  5479. }
  5480. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5481. const ASTContext &Ctx,
  5482. const CastExpr *BCE) {
  5483. bool DestOK = checkBitCastConstexprEligibilityType(
  5484. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5485. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5486. BCE->getBeginLoc(),
  5487. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5488. return SourceOK;
  5489. }
  5490. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5491. APValue &SourceValue,
  5492. const CastExpr *BCE) {
  5493. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5494. "no host or target supports non 8-bit chars");
  5495. assert(SourceValue.isLValue() &&
  5496. "LValueToRValueBitcast requires an lvalue operand!");
  5497. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5498. return false;
  5499. LValue SourceLValue;
  5500. APValue SourceRValue;
  5501. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5502. if (!handleLValueToRValueConversion(
  5503. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  5504. SourceRValue, /*WantObjectRepresentation=*/true))
  5505. return false;
  5506. // Read out SourceValue into a char buffer.
  5507. Optional<BitCastBuffer> Buffer =
  5508. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5509. if (!Buffer)
  5510. return false;
  5511. // Write out the buffer into a new APValue.
  5512. Optional<APValue> MaybeDestValue =
  5513. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5514. if (!MaybeDestValue)
  5515. return false;
  5516. DestValue = std::move(*MaybeDestValue);
  5517. return true;
  5518. }
  5519. template <class Derived>
  5520. class ExprEvaluatorBase
  5521. : public ConstStmtVisitor<Derived, bool> {
  5522. private:
  5523. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5524. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5525. return getDerived().Success(V, E);
  5526. }
  5527. bool DerivedZeroInitialization(const Expr *E) {
  5528. return getDerived().ZeroInitialization(E);
  5529. }
  5530. // Check whether a conditional operator with a non-constant condition is a
  5531. // potential constant expression. If neither arm is a potential constant
  5532. // expression, then the conditional operator is not either.
  5533. template<typename ConditionalOperator>
  5534. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5535. assert(Info.checkingPotentialConstantExpression());
  5536. // Speculatively evaluate both arms.
  5537. SmallVector<PartialDiagnosticAt, 8> Diag;
  5538. {
  5539. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5540. StmtVisitorTy::Visit(E->getFalseExpr());
  5541. if (Diag.empty())
  5542. return;
  5543. }
  5544. {
  5545. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5546. Diag.clear();
  5547. StmtVisitorTy::Visit(E->getTrueExpr());
  5548. if (Diag.empty())
  5549. return;
  5550. }
  5551. Error(E, diag::note_constexpr_conditional_never_const);
  5552. }
  5553. template<typename ConditionalOperator>
  5554. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5555. bool BoolResult;
  5556. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5557. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5558. CheckPotentialConstantConditional(E);
  5559. return false;
  5560. }
  5561. if (Info.noteFailure()) {
  5562. StmtVisitorTy::Visit(E->getTrueExpr());
  5563. StmtVisitorTy::Visit(E->getFalseExpr());
  5564. }
  5565. return false;
  5566. }
  5567. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5568. return StmtVisitorTy::Visit(EvalExpr);
  5569. }
  5570. protected:
  5571. EvalInfo &Info;
  5572. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5573. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5574. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5575. return Info.CCEDiag(E, D);
  5576. }
  5577. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5578. public:
  5579. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5580. EvalInfo &getEvalInfo() { return Info; }
  5581. /// Report an evaluation error. This should only be called when an error is
  5582. /// first discovered. When propagating an error, just return false.
  5583. bool Error(const Expr *E, diag::kind D) {
  5584. Info.FFDiag(E, D);
  5585. return false;
  5586. }
  5587. bool Error(const Expr *E) {
  5588. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5589. }
  5590. bool VisitStmt(const Stmt *) {
  5591. llvm_unreachable("Expression evaluator should not be called on stmts");
  5592. }
  5593. bool VisitExpr(const Expr *E) {
  5594. return Error(E);
  5595. }
  5596. bool VisitConstantExpr(const ConstantExpr *E)
  5597. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5598. bool VisitParenExpr(const ParenExpr *E)
  5599. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5600. bool VisitUnaryExtension(const UnaryOperator *E)
  5601. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5602. bool VisitUnaryPlus(const UnaryOperator *E)
  5603. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5604. bool VisitChooseExpr(const ChooseExpr *E)
  5605. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5606. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5607. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5608. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5609. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5610. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5611. TempVersionRAII RAII(*Info.CurrentCall);
  5612. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5613. return StmtVisitorTy::Visit(E->getExpr());
  5614. }
  5615. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5616. TempVersionRAII RAII(*Info.CurrentCall);
  5617. // The initializer may not have been parsed yet, or might be erroneous.
  5618. if (!E->getExpr())
  5619. return Error(E);
  5620. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5621. return StmtVisitorTy::Visit(E->getExpr());
  5622. }
  5623. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  5624. FullExpressionRAII Scope(Info);
  5625. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  5626. }
  5627. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5628. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5629. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5630. }
  5631. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5632. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5633. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5634. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5635. }
  5636. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5637. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5638. }
  5639. bool VisitBinaryOperator(const BinaryOperator *E) {
  5640. switch (E->getOpcode()) {
  5641. default:
  5642. return Error(E);
  5643. case BO_Comma:
  5644. VisitIgnoredValue(E->getLHS());
  5645. return StmtVisitorTy::Visit(E->getRHS());
  5646. case BO_PtrMemD:
  5647. case BO_PtrMemI: {
  5648. LValue Obj;
  5649. if (!HandleMemberPointerAccess(Info, E, Obj))
  5650. return false;
  5651. APValue Result;
  5652. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5653. return false;
  5654. return DerivedSuccess(Result, E);
  5655. }
  5656. }
  5657. }
  5658. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5659. // Evaluate and cache the common expression. We treat it as a temporary,
  5660. // even though it's not quite the same thing.
  5661. LValue CommonLV;
  5662. if (!Evaluate(Info.CurrentCall->createTemporary(
  5663. E->getOpaqueValue(), getStorageType(Info.Ctx, E->getOpaqueValue()),
  5664. false, CommonLV),
  5665. Info, E->getCommon()))
  5666. return false;
  5667. return HandleConditionalOperator(E);
  5668. }
  5669. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5670. bool IsBcpCall = false;
  5671. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5672. // the result is a constant expression if it can be folded without
  5673. // side-effects. This is an important GNU extension. See GCC PR38377
  5674. // for discussion.
  5675. if (const CallExpr *CallCE =
  5676. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  5677. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  5678. IsBcpCall = true;
  5679. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  5680. // constant expression; we can't check whether it's potentially foldable.
  5681. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  5682. // it would return 'false' in this mode.
  5683. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  5684. return false;
  5685. FoldConstant Fold(Info, IsBcpCall);
  5686. if (!HandleConditionalOperator(E)) {
  5687. Fold.keepDiagnostics();
  5688. return false;
  5689. }
  5690. return true;
  5691. }
  5692. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  5693. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  5694. return DerivedSuccess(*Value, E);
  5695. const Expr *Source = E->getSourceExpr();
  5696. if (!Source)
  5697. return Error(E);
  5698. if (Source == E) { // sanity checking.
  5699. assert(0 && "OpaqueValueExpr recursively refers to itself");
  5700. return Error(E);
  5701. }
  5702. return StmtVisitorTy::Visit(Source);
  5703. }
  5704. bool VisitCallExpr(const CallExpr *E) {
  5705. APValue Result;
  5706. if (!handleCallExpr(E, Result, nullptr))
  5707. return false;
  5708. return DerivedSuccess(Result, E);
  5709. }
  5710. bool handleCallExpr(const CallExpr *E, APValue &Result,
  5711. const LValue *ResultSlot) {
  5712. const Expr *Callee = E->getCallee()->IgnoreParens();
  5713. QualType CalleeType = Callee->getType();
  5714. const FunctionDecl *FD = nullptr;
  5715. LValue *This = nullptr, ThisVal;
  5716. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5717. bool HasQualifier = false;
  5718. // Extract function decl and 'this' pointer from the callee.
  5719. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  5720. const CXXMethodDecl *Member = nullptr;
  5721. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  5722. // Explicit bound member calls, such as x.f() or p->g();
  5723. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  5724. return false;
  5725. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  5726. if (!Member)
  5727. return Error(Callee);
  5728. This = &ThisVal;
  5729. HasQualifier = ME->hasQualifier();
  5730. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  5731. // Indirect bound member calls ('.*' or '->*').
  5732. Member = dyn_cast_or_null<CXXMethodDecl>(
  5733. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  5734. if (!Member)
  5735. return Error(Callee);
  5736. This = &ThisVal;
  5737. } else
  5738. return Error(Callee);
  5739. FD = Member;
  5740. } else if (CalleeType->isFunctionPointerType()) {
  5741. LValue Call;
  5742. if (!EvaluatePointer(Callee, Call, Info))
  5743. return false;
  5744. if (!Call.getLValueOffset().isZero())
  5745. return Error(Callee);
  5746. FD = dyn_cast_or_null<FunctionDecl>(
  5747. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  5748. if (!FD)
  5749. return Error(Callee);
  5750. // Don't call function pointers which have been cast to some other type.
  5751. // Per DR (no number yet), the caller and callee can differ in noexcept.
  5752. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  5753. CalleeType->getPointeeType(), FD->getType())) {
  5754. return Error(E);
  5755. }
  5756. // Overloaded operator calls to member functions are represented as normal
  5757. // calls with '*this' as the first argument.
  5758. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5759. if (MD && !MD->isStatic()) {
  5760. // FIXME: When selecting an implicit conversion for an overloaded
  5761. // operator delete, we sometimes try to evaluate calls to conversion
  5762. // operators without a 'this' parameter!
  5763. if (Args.empty())
  5764. return Error(E);
  5765. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  5766. return false;
  5767. This = &ThisVal;
  5768. Args = Args.slice(1);
  5769. } else if (MD && MD->isLambdaStaticInvoker()) {
  5770. // Map the static invoker for the lambda back to the call operator.
  5771. // Conveniently, we don't have to slice out the 'this' argument (as is
  5772. // being done for the non-static case), since a static member function
  5773. // doesn't have an implicit argument passed in.
  5774. const CXXRecordDecl *ClosureClass = MD->getParent();
  5775. assert(
  5776. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  5777. "Number of captures must be zero for conversion to function-ptr");
  5778. const CXXMethodDecl *LambdaCallOp =
  5779. ClosureClass->getLambdaCallOperator();
  5780. // Set 'FD', the function that will be called below, to the call
  5781. // operator. If the closure object represents a generic lambda, find
  5782. // the corresponding specialization of the call operator.
  5783. if (ClosureClass->isGenericLambda()) {
  5784. assert(MD->isFunctionTemplateSpecialization() &&
  5785. "A generic lambda's static-invoker function must be a "
  5786. "template specialization");
  5787. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  5788. FunctionTemplateDecl *CallOpTemplate =
  5789. LambdaCallOp->getDescribedFunctionTemplate();
  5790. void *InsertPos = nullptr;
  5791. FunctionDecl *CorrespondingCallOpSpecialization =
  5792. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  5793. assert(CorrespondingCallOpSpecialization &&
  5794. "We must always have a function call operator specialization "
  5795. "that corresponds to our static invoker specialization");
  5796. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  5797. } else
  5798. FD = LambdaCallOp;
  5799. }
  5800. } else
  5801. return Error(E);
  5802. SmallVector<QualType, 4> CovariantAdjustmentPath;
  5803. if (This) {
  5804. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  5805. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  5806. // Perform virtual dispatch, if necessary.
  5807. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  5808. CovariantAdjustmentPath);
  5809. if (!FD)
  5810. return false;
  5811. } else {
  5812. // Check that the 'this' pointer points to an object of the right type.
  5813. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
  5814. return false;
  5815. }
  5816. }
  5817. const FunctionDecl *Definition = nullptr;
  5818. Stmt *Body = FD->getBody(Definition);
  5819. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  5820. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  5821. Result, ResultSlot))
  5822. return false;
  5823. if (!CovariantAdjustmentPath.empty() &&
  5824. !HandleCovariantReturnAdjustment(Info, E, Result,
  5825. CovariantAdjustmentPath))
  5826. return false;
  5827. return true;
  5828. }
  5829. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5830. return StmtVisitorTy::Visit(E->getInitializer());
  5831. }
  5832. bool VisitInitListExpr(const InitListExpr *E) {
  5833. if (E->getNumInits() == 0)
  5834. return DerivedZeroInitialization(E);
  5835. if (E->getNumInits() == 1)
  5836. return StmtVisitorTy::Visit(E->getInit(0));
  5837. return Error(E);
  5838. }
  5839. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  5840. return DerivedZeroInitialization(E);
  5841. }
  5842. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  5843. return DerivedZeroInitialization(E);
  5844. }
  5845. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  5846. return DerivedZeroInitialization(E);
  5847. }
  5848. /// A member expression where the object is a prvalue is itself a prvalue.
  5849. bool VisitMemberExpr(const MemberExpr *E) {
  5850. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  5851. "missing temporary materialization conversion");
  5852. assert(!E->isArrow() && "missing call to bound member function?");
  5853. APValue Val;
  5854. if (!Evaluate(Val, Info, E->getBase()))
  5855. return false;
  5856. QualType BaseTy = E->getBase()->getType();
  5857. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  5858. if (!FD) return Error(E);
  5859. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  5860. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5861. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5862. // Note: there is no lvalue base here. But this case should only ever
  5863. // happen in C or in C++98, where we cannot be evaluating a constexpr
  5864. // constructor, which is the only case the base matters.
  5865. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  5866. SubobjectDesignator Designator(BaseTy);
  5867. Designator.addDeclUnchecked(FD);
  5868. APValue Result;
  5869. return extractSubobject(Info, E, Obj, Designator, Result) &&
  5870. DerivedSuccess(Result, E);
  5871. }
  5872. bool VisitCastExpr(const CastExpr *E) {
  5873. switch (E->getCastKind()) {
  5874. default:
  5875. break;
  5876. case CK_AtomicToNonAtomic: {
  5877. APValue AtomicVal;
  5878. // This does not need to be done in place even for class/array types:
  5879. // atomic-to-non-atomic conversion implies copying the object
  5880. // representation.
  5881. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  5882. return false;
  5883. return DerivedSuccess(AtomicVal, E);
  5884. }
  5885. case CK_NoOp:
  5886. case CK_UserDefinedConversion:
  5887. return StmtVisitorTy::Visit(E->getSubExpr());
  5888. case CK_LValueToRValue: {
  5889. LValue LVal;
  5890. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  5891. return false;
  5892. APValue RVal;
  5893. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5894. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5895. LVal, RVal))
  5896. return false;
  5897. return DerivedSuccess(RVal, E);
  5898. }
  5899. case CK_LValueToRValueBitCast: {
  5900. APValue DestValue, SourceValue;
  5901. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  5902. return false;
  5903. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  5904. return false;
  5905. return DerivedSuccess(DestValue, E);
  5906. }
  5907. }
  5908. return Error(E);
  5909. }
  5910. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  5911. return VisitUnaryPostIncDec(UO);
  5912. }
  5913. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  5914. return VisitUnaryPostIncDec(UO);
  5915. }
  5916. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  5917. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5918. return Error(UO);
  5919. LValue LVal;
  5920. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  5921. return false;
  5922. APValue RVal;
  5923. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  5924. UO->isIncrementOp(), &RVal))
  5925. return false;
  5926. return DerivedSuccess(RVal, UO);
  5927. }
  5928. bool VisitStmtExpr(const StmtExpr *E) {
  5929. // We will have checked the full-expressions inside the statement expression
  5930. // when they were completed, and don't need to check them again now.
  5931. if (Info.checkingForUndefinedBehavior())
  5932. return Error(E);
  5933. const CompoundStmt *CS = E->getSubStmt();
  5934. if (CS->body_empty())
  5935. return true;
  5936. BlockScopeRAII Scope(Info);
  5937. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  5938. BE = CS->body_end();
  5939. /**/; ++BI) {
  5940. if (BI + 1 == BE) {
  5941. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  5942. if (!FinalExpr) {
  5943. Info.FFDiag((*BI)->getBeginLoc(),
  5944. diag::note_constexpr_stmt_expr_unsupported);
  5945. return false;
  5946. }
  5947. return this->Visit(FinalExpr) && Scope.destroy();
  5948. }
  5949. APValue ReturnValue;
  5950. StmtResult Result = { ReturnValue, nullptr };
  5951. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  5952. if (ESR != ESR_Succeeded) {
  5953. // FIXME: If the statement-expression terminated due to 'return',
  5954. // 'break', or 'continue', it would be nice to propagate that to
  5955. // the outer statement evaluation rather than bailing out.
  5956. if (ESR != ESR_Failed)
  5957. Info.FFDiag((*BI)->getBeginLoc(),
  5958. diag::note_constexpr_stmt_expr_unsupported);
  5959. return false;
  5960. }
  5961. }
  5962. llvm_unreachable("Return from function from the loop above.");
  5963. }
  5964. /// Visit a value which is evaluated, but whose value is ignored.
  5965. void VisitIgnoredValue(const Expr *E) {
  5966. EvaluateIgnoredValue(Info, E);
  5967. }
  5968. /// Potentially visit a MemberExpr's base expression.
  5969. void VisitIgnoredBaseExpression(const Expr *E) {
  5970. // While MSVC doesn't evaluate the base expression, it does diagnose the
  5971. // presence of side-effecting behavior.
  5972. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  5973. return;
  5974. VisitIgnoredValue(E);
  5975. }
  5976. };
  5977. } // namespace
  5978. //===----------------------------------------------------------------------===//
  5979. // Common base class for lvalue and temporary evaluation.
  5980. //===----------------------------------------------------------------------===//
  5981. namespace {
  5982. template<class Derived>
  5983. class LValueExprEvaluatorBase
  5984. : public ExprEvaluatorBase<Derived> {
  5985. protected:
  5986. LValue &Result;
  5987. bool InvalidBaseOK;
  5988. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  5989. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  5990. bool Success(APValue::LValueBase B) {
  5991. Result.set(B);
  5992. return true;
  5993. }
  5994. bool evaluatePointer(const Expr *E, LValue &Result) {
  5995. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  5996. }
  5997. public:
  5998. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  5999. : ExprEvaluatorBaseTy(Info), Result(Result),
  6000. InvalidBaseOK(InvalidBaseOK) {}
  6001. bool Success(const APValue &V, const Expr *E) {
  6002. Result.setFrom(this->Info.Ctx, V);
  6003. return true;
  6004. }
  6005. bool VisitMemberExpr(const MemberExpr *E) {
  6006. // Handle non-static data members.
  6007. QualType BaseTy;
  6008. bool EvalOK;
  6009. if (E->isArrow()) {
  6010. EvalOK = evaluatePointer(E->getBase(), Result);
  6011. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  6012. } else if (E->getBase()->isRValue()) {
  6013. assert(E->getBase()->getType()->isRecordType());
  6014. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  6015. BaseTy = E->getBase()->getType();
  6016. } else {
  6017. EvalOK = this->Visit(E->getBase());
  6018. BaseTy = E->getBase()->getType();
  6019. }
  6020. if (!EvalOK) {
  6021. if (!InvalidBaseOK)
  6022. return false;
  6023. Result.setInvalid(E);
  6024. return true;
  6025. }
  6026. const ValueDecl *MD = E->getMemberDecl();
  6027. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  6028. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6029. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6030. (void)BaseTy;
  6031. if (!HandleLValueMember(this->Info, E, Result, FD))
  6032. return false;
  6033. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  6034. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  6035. return false;
  6036. } else
  6037. return this->Error(E);
  6038. if (MD->getType()->isReferenceType()) {
  6039. APValue RefValue;
  6040. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  6041. RefValue))
  6042. return false;
  6043. return Success(RefValue, E);
  6044. }
  6045. return true;
  6046. }
  6047. bool VisitBinaryOperator(const BinaryOperator *E) {
  6048. switch (E->getOpcode()) {
  6049. default:
  6050. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6051. case BO_PtrMemD:
  6052. case BO_PtrMemI:
  6053. return HandleMemberPointerAccess(this->Info, E, Result);
  6054. }
  6055. }
  6056. bool VisitCastExpr(const CastExpr *E) {
  6057. switch (E->getCastKind()) {
  6058. default:
  6059. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6060. case CK_DerivedToBase:
  6061. case CK_UncheckedDerivedToBase:
  6062. if (!this->Visit(E->getSubExpr()))
  6063. return false;
  6064. // Now figure out the necessary offset to add to the base LV to get from
  6065. // the derived class to the base class.
  6066. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  6067. Result);
  6068. }
  6069. }
  6070. };
  6071. }
  6072. //===----------------------------------------------------------------------===//
  6073. // LValue Evaluation
  6074. //
  6075. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  6076. // function designators (in C), decl references to void objects (in C), and
  6077. // temporaries (if building with -Wno-address-of-temporary).
  6078. //
  6079. // LValue evaluation produces values comprising a base expression of one of the
  6080. // following types:
  6081. // - Declarations
  6082. // * VarDecl
  6083. // * FunctionDecl
  6084. // - Literals
  6085. // * CompoundLiteralExpr in C (and in global scope in C++)
  6086. // * StringLiteral
  6087. // * PredefinedExpr
  6088. // * ObjCStringLiteralExpr
  6089. // * ObjCEncodeExpr
  6090. // * AddrLabelExpr
  6091. // * BlockExpr
  6092. // * CallExpr for a MakeStringConstant builtin
  6093. // - typeid(T) expressions, as TypeInfoLValues
  6094. // - Locals and temporaries
  6095. // * MaterializeTemporaryExpr
  6096. // * Any Expr, with a CallIndex indicating the function in which the temporary
  6097. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  6098. // from the AST (FIXME).
  6099. // * A MaterializeTemporaryExpr that has static storage duration, with no
  6100. // CallIndex, for a lifetime-extended temporary.
  6101. // plus an offset in bytes.
  6102. //===----------------------------------------------------------------------===//
  6103. namespace {
  6104. class LValueExprEvaluator
  6105. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  6106. public:
  6107. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  6108. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  6109. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  6110. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  6111. bool VisitDeclRefExpr(const DeclRefExpr *E);
  6112. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  6113. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  6114. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  6115. bool VisitMemberExpr(const MemberExpr *E);
  6116. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  6117. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  6118. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  6119. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  6120. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  6121. bool VisitUnaryDeref(const UnaryOperator *E);
  6122. bool VisitUnaryReal(const UnaryOperator *E);
  6123. bool VisitUnaryImag(const UnaryOperator *E);
  6124. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  6125. return VisitUnaryPreIncDec(UO);
  6126. }
  6127. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  6128. return VisitUnaryPreIncDec(UO);
  6129. }
  6130. bool VisitBinAssign(const BinaryOperator *BO);
  6131. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  6132. bool VisitCastExpr(const CastExpr *E) {
  6133. switch (E->getCastKind()) {
  6134. default:
  6135. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6136. case CK_LValueBitCast:
  6137. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6138. if (!Visit(E->getSubExpr()))
  6139. return false;
  6140. Result.Designator.setInvalid();
  6141. return true;
  6142. case CK_BaseToDerived:
  6143. if (!Visit(E->getSubExpr()))
  6144. return false;
  6145. return HandleBaseToDerivedCast(Info, E, Result);
  6146. case CK_Dynamic:
  6147. if (!Visit(E->getSubExpr()))
  6148. return false;
  6149. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6150. }
  6151. }
  6152. };
  6153. } // end anonymous namespace
  6154. /// Evaluate an expression as an lvalue. This can be legitimately called on
  6155. /// expressions which are not glvalues, in three cases:
  6156. /// * function designators in C, and
  6157. /// * "extern void" objects
  6158. /// * @selector() expressions in Objective-C
  6159. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  6160. bool InvalidBaseOK) {
  6161. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  6162. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  6163. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6164. }
  6165. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  6166. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  6167. return Success(FD);
  6168. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  6169. return VisitVarDecl(E, VD);
  6170. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  6171. return Visit(BD->getBinding());
  6172. return Error(E);
  6173. }
  6174. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  6175. // If we are within a lambda's call operator, check whether the 'VD' referred
  6176. // to within 'E' actually represents a lambda-capture that maps to a
  6177. // data-member/field within the closure object, and if so, evaluate to the
  6178. // field or what the field refers to.
  6179. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  6180. isa<DeclRefExpr>(E) &&
  6181. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  6182. // We don't always have a complete capture-map when checking or inferring if
  6183. // the function call operator meets the requirements of a constexpr function
  6184. // - but we don't need to evaluate the captures to determine constexprness
  6185. // (dcl.constexpr C++17).
  6186. if (Info.checkingPotentialConstantExpression())
  6187. return false;
  6188. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  6189. // Start with 'Result' referring to the complete closure object...
  6190. Result = *Info.CurrentCall->This;
  6191. // ... then update it to refer to the field of the closure object
  6192. // that represents the capture.
  6193. if (!HandleLValueMember(Info, E, Result, FD))
  6194. return false;
  6195. // And if the field is of reference type, update 'Result' to refer to what
  6196. // the field refers to.
  6197. if (FD->getType()->isReferenceType()) {
  6198. APValue RVal;
  6199. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  6200. RVal))
  6201. return false;
  6202. Result.setFrom(Info.Ctx, RVal);
  6203. }
  6204. return true;
  6205. }
  6206. }
  6207. CallStackFrame *Frame = nullptr;
  6208. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  6209. // Only if a local variable was declared in the function currently being
  6210. // evaluated, do we expect to be able to find its value in the current
  6211. // frame. (Otherwise it was likely declared in an enclosing context and
  6212. // could either have a valid evaluatable value (for e.g. a constexpr
  6213. // variable) or be ill-formed (and trigger an appropriate evaluation
  6214. // diagnostic)).
  6215. if (Info.CurrentCall->Callee &&
  6216. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  6217. Frame = Info.CurrentCall;
  6218. }
  6219. }
  6220. if (!VD->getType()->isReferenceType()) {
  6221. if (Frame) {
  6222. Result.set({VD, Frame->Index,
  6223. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  6224. return true;
  6225. }
  6226. return Success(VD);
  6227. }
  6228. APValue *V;
  6229. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  6230. return false;
  6231. if (!V->hasValue()) {
  6232. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  6233. // adjust the diagnostic to say that.
  6234. if (!Info.checkingPotentialConstantExpression())
  6235. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  6236. return false;
  6237. }
  6238. return Success(*V, E);
  6239. }
  6240. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  6241. const MaterializeTemporaryExpr *E) {
  6242. // Walk through the expression to find the materialized temporary itself.
  6243. SmallVector<const Expr *, 2> CommaLHSs;
  6244. SmallVector<SubobjectAdjustment, 2> Adjustments;
  6245. const Expr *Inner = E->GetTemporaryExpr()->
  6246. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  6247. // If we passed any comma operators, evaluate their LHSs.
  6248. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  6249. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  6250. return false;
  6251. // A materialized temporary with static storage duration can appear within the
  6252. // result of a constant expression evaluation, so we need to preserve its
  6253. // value for use outside this evaluation.
  6254. APValue *Value;
  6255. if (E->getStorageDuration() == SD_Static) {
  6256. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  6257. *Value = APValue();
  6258. Result.set(E);
  6259. } else {
  6260. Value = &Info.CurrentCall->createTemporary(
  6261. E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
  6262. }
  6263. QualType Type = Inner->getType();
  6264. // Materialize the temporary itself.
  6265. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  6266. (E->getStorageDuration() == SD_Static &&
  6267. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  6268. *Value = APValue();
  6269. return false;
  6270. }
  6271. // Adjust our lvalue to refer to the desired subobject.
  6272. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  6273. --I;
  6274. switch (Adjustments[I].Kind) {
  6275. case SubobjectAdjustment::DerivedToBaseAdjustment:
  6276. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  6277. Type, Result))
  6278. return false;
  6279. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  6280. break;
  6281. case SubobjectAdjustment::FieldAdjustment:
  6282. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  6283. return false;
  6284. Type = Adjustments[I].Field->getType();
  6285. break;
  6286. case SubobjectAdjustment::MemberPointerAdjustment:
  6287. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  6288. Adjustments[I].Ptr.RHS))
  6289. return false;
  6290. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  6291. break;
  6292. }
  6293. }
  6294. return true;
  6295. }
  6296. bool
  6297. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6298. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  6299. "lvalue compound literal in c++?");
  6300. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  6301. // only see this when folding in C, so there's no standard to follow here.
  6302. return Success(E);
  6303. }
  6304. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  6305. TypeInfoLValue TypeInfo;
  6306. if (!E->isPotentiallyEvaluated()) {
  6307. if (E->isTypeOperand())
  6308. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  6309. else
  6310. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  6311. } else {
  6312. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  6313. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  6314. << E->getExprOperand()->getType()
  6315. << E->getExprOperand()->getSourceRange();
  6316. }
  6317. if (!Visit(E->getExprOperand()))
  6318. return false;
  6319. Optional<DynamicType> DynType =
  6320. ComputeDynamicType(Info, E, Result, AK_TypeId);
  6321. if (!DynType)
  6322. return false;
  6323. TypeInfo =
  6324. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  6325. }
  6326. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  6327. }
  6328. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  6329. return Success(E);
  6330. }
  6331. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  6332. // Handle static data members.
  6333. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  6334. VisitIgnoredBaseExpression(E->getBase());
  6335. return VisitVarDecl(E, VD);
  6336. }
  6337. // Handle static member functions.
  6338. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  6339. if (MD->isStatic()) {
  6340. VisitIgnoredBaseExpression(E->getBase());
  6341. return Success(MD);
  6342. }
  6343. }
  6344. // Handle non-static data members.
  6345. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  6346. }
  6347. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  6348. // FIXME: Deal with vectors as array subscript bases.
  6349. if (E->getBase()->getType()->isVectorType())
  6350. return Error(E);
  6351. bool Success = true;
  6352. if (!evaluatePointer(E->getBase(), Result)) {
  6353. if (!Info.noteFailure())
  6354. return false;
  6355. Success = false;
  6356. }
  6357. APSInt Index;
  6358. if (!EvaluateInteger(E->getIdx(), Index, Info))
  6359. return false;
  6360. return Success &&
  6361. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  6362. }
  6363. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  6364. return evaluatePointer(E->getSubExpr(), Result);
  6365. }
  6366. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6367. if (!Visit(E->getSubExpr()))
  6368. return false;
  6369. // __real is a no-op on scalar lvalues.
  6370. if (E->getSubExpr()->getType()->isAnyComplexType())
  6371. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  6372. return true;
  6373. }
  6374. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6375. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  6376. "lvalue __imag__ on scalar?");
  6377. if (!Visit(E->getSubExpr()))
  6378. return false;
  6379. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  6380. return true;
  6381. }
  6382. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  6383. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6384. return Error(UO);
  6385. if (!this->Visit(UO->getSubExpr()))
  6386. return false;
  6387. return handleIncDec(
  6388. this->Info, UO, Result, UO->getSubExpr()->getType(),
  6389. UO->isIncrementOp(), nullptr);
  6390. }
  6391. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  6392. const CompoundAssignOperator *CAO) {
  6393. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6394. return Error(CAO);
  6395. APValue RHS;
  6396. // The overall lvalue result is the result of evaluating the LHS.
  6397. if (!this->Visit(CAO->getLHS())) {
  6398. if (Info.noteFailure())
  6399. Evaluate(RHS, this->Info, CAO->getRHS());
  6400. return false;
  6401. }
  6402. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  6403. return false;
  6404. return handleCompoundAssignment(
  6405. this->Info, CAO,
  6406. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  6407. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  6408. }
  6409. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  6410. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6411. return Error(E);
  6412. APValue NewVal;
  6413. if (!this->Visit(E->getLHS())) {
  6414. if (Info.noteFailure())
  6415. Evaluate(NewVal, this->Info, E->getRHS());
  6416. return false;
  6417. }
  6418. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  6419. return false;
  6420. if (Info.getLangOpts().CPlusPlus2a &&
  6421. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  6422. return false;
  6423. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  6424. NewVal);
  6425. }
  6426. //===----------------------------------------------------------------------===//
  6427. // Pointer Evaluation
  6428. //===----------------------------------------------------------------------===//
  6429. /// Attempts to compute the number of bytes available at the pointer
  6430. /// returned by a function with the alloc_size attribute. Returns true if we
  6431. /// were successful. Places an unsigned number into `Result`.
  6432. ///
  6433. /// This expects the given CallExpr to be a call to a function with an
  6434. /// alloc_size attribute.
  6435. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6436. const CallExpr *Call,
  6437. llvm::APInt &Result) {
  6438. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  6439. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  6440. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  6441. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  6442. if (Call->getNumArgs() <= SizeArgNo)
  6443. return false;
  6444. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  6445. Expr::EvalResult ExprResult;
  6446. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  6447. return false;
  6448. Into = ExprResult.Val.getInt();
  6449. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  6450. return false;
  6451. Into = Into.zextOrSelf(BitsInSizeT);
  6452. return true;
  6453. };
  6454. APSInt SizeOfElem;
  6455. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  6456. return false;
  6457. if (!AllocSize->getNumElemsParam().isValid()) {
  6458. Result = std::move(SizeOfElem);
  6459. return true;
  6460. }
  6461. APSInt NumberOfElems;
  6462. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  6463. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  6464. return false;
  6465. bool Overflow;
  6466. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  6467. if (Overflow)
  6468. return false;
  6469. Result = std::move(BytesAvailable);
  6470. return true;
  6471. }
  6472. /// Convenience function. LVal's base must be a call to an alloc_size
  6473. /// function.
  6474. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6475. const LValue &LVal,
  6476. llvm::APInt &Result) {
  6477. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6478. "Can't get the size of a non alloc_size function");
  6479. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6480. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6481. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6482. }
  6483. /// Attempts to evaluate the given LValueBase as the result of a call to
  6484. /// a function with the alloc_size attribute. If it was possible to do so, this
  6485. /// function will return true, make Result's Base point to said function call,
  6486. /// and mark Result's Base as invalid.
  6487. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6488. LValue &Result) {
  6489. if (Base.isNull())
  6490. return false;
  6491. // Because we do no form of static analysis, we only support const variables.
  6492. //
  6493. // Additionally, we can't support parameters, nor can we support static
  6494. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6495. // we have no clue what they'll be assigned to).
  6496. const auto *VD =
  6497. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6498. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6499. return false;
  6500. const Expr *Init = VD->getAnyInitializer();
  6501. if (!Init)
  6502. return false;
  6503. const Expr *E = Init->IgnoreParens();
  6504. if (!tryUnwrapAllocSizeCall(E))
  6505. return false;
  6506. // Store E instead of E unwrapped so that the type of the LValue's base is
  6507. // what the user wanted.
  6508. Result.setInvalid(E);
  6509. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6510. Result.addUnsizedArray(Info, E, Pointee);
  6511. return true;
  6512. }
  6513. namespace {
  6514. class PointerExprEvaluator
  6515. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6516. LValue &Result;
  6517. bool InvalidBaseOK;
  6518. bool Success(const Expr *E) {
  6519. Result.set(E);
  6520. return true;
  6521. }
  6522. bool evaluateLValue(const Expr *E, LValue &Result) {
  6523. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6524. }
  6525. bool evaluatePointer(const Expr *E, LValue &Result) {
  6526. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6527. }
  6528. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6529. public:
  6530. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6531. : ExprEvaluatorBaseTy(info), Result(Result),
  6532. InvalidBaseOK(InvalidBaseOK) {}
  6533. bool Success(const APValue &V, const Expr *E) {
  6534. Result.setFrom(Info.Ctx, V);
  6535. return true;
  6536. }
  6537. bool ZeroInitialization(const Expr *E) {
  6538. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  6539. Result.setNull(E->getType(), TargetVal);
  6540. return true;
  6541. }
  6542. bool VisitBinaryOperator(const BinaryOperator *E);
  6543. bool VisitCastExpr(const CastExpr* E);
  6544. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6545. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6546. { return Success(E); }
  6547. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6548. if (E->isExpressibleAsConstantInitializer())
  6549. return Success(E);
  6550. if (Info.noteFailure())
  6551. EvaluateIgnoredValue(Info, E->getSubExpr());
  6552. return Error(E);
  6553. }
  6554. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6555. { return Success(E); }
  6556. bool VisitCallExpr(const CallExpr *E);
  6557. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6558. bool VisitBlockExpr(const BlockExpr *E) {
  6559. if (!E->getBlockDecl()->hasCaptures())
  6560. return Success(E);
  6561. return Error(E);
  6562. }
  6563. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6564. // Can't look at 'this' when checking a potential constant expression.
  6565. if (Info.checkingPotentialConstantExpression())
  6566. return false;
  6567. if (!Info.CurrentCall->This) {
  6568. if (Info.getLangOpts().CPlusPlus11)
  6569. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6570. else
  6571. Info.FFDiag(E);
  6572. return false;
  6573. }
  6574. Result = *Info.CurrentCall->This;
  6575. // If we are inside a lambda's call operator, the 'this' expression refers
  6576. // to the enclosing '*this' object (either by value or reference) which is
  6577. // either copied into the closure object's field that represents the '*this'
  6578. // or refers to '*this'.
  6579. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6580. // Update 'Result' to refer to the data member/field of the closure object
  6581. // that represents the '*this' capture.
  6582. if (!HandleLValueMember(Info, E, Result,
  6583. Info.CurrentCall->LambdaThisCaptureField))
  6584. return false;
  6585. // If we captured '*this' by reference, replace the field with its referent.
  6586. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6587. ->isPointerType()) {
  6588. APValue RVal;
  6589. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6590. RVal))
  6591. return false;
  6592. Result.setFrom(Info.Ctx, RVal);
  6593. }
  6594. }
  6595. return true;
  6596. }
  6597. bool VisitCXXNewExpr(const CXXNewExpr *E);
  6598. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6599. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6600. APValue LValResult = E->EvaluateInContext(
  6601. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6602. Result.setFrom(Info.Ctx, LValResult);
  6603. return true;
  6604. }
  6605. // FIXME: Missing: @protocol, @selector
  6606. };
  6607. } // end anonymous namespace
  6608. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6609. bool InvalidBaseOK) {
  6610. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6611. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6612. }
  6613. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6614. if (E->getOpcode() != BO_Add &&
  6615. E->getOpcode() != BO_Sub)
  6616. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6617. const Expr *PExp = E->getLHS();
  6618. const Expr *IExp = E->getRHS();
  6619. if (IExp->getType()->isPointerType())
  6620. std::swap(PExp, IExp);
  6621. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6622. if (!EvalPtrOK && !Info.noteFailure())
  6623. return false;
  6624. llvm::APSInt Offset;
  6625. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6626. return false;
  6627. if (E->getOpcode() == BO_Sub)
  6628. negateAsSigned(Offset);
  6629. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6630. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6631. }
  6632. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6633. return evaluateLValue(E->getSubExpr(), Result);
  6634. }
  6635. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6636. const Expr *SubExpr = E->getSubExpr();
  6637. switch (E->getCastKind()) {
  6638. default:
  6639. break;
  6640. case CK_BitCast:
  6641. case CK_CPointerToObjCPointerCast:
  6642. case CK_BlockPointerToObjCPointerCast:
  6643. case CK_AnyPointerToBlockPointerCast:
  6644. case CK_AddressSpaceConversion:
  6645. if (!Visit(SubExpr))
  6646. return false;
  6647. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  6648. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  6649. // also static_casts, but we disallow them as a resolution to DR1312.
  6650. if (!E->getType()->isVoidPointerType()) {
  6651. Result.Designator.setInvalid();
  6652. if (SubExpr->getType()->isVoidPointerType())
  6653. CCEDiag(E, diag::note_constexpr_invalid_cast)
  6654. << 3 << SubExpr->getType();
  6655. else
  6656. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6657. }
  6658. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  6659. ZeroInitialization(E);
  6660. return true;
  6661. case CK_DerivedToBase:
  6662. case CK_UncheckedDerivedToBase:
  6663. if (!evaluatePointer(E->getSubExpr(), Result))
  6664. return false;
  6665. if (!Result.Base && Result.Offset.isZero())
  6666. return true;
  6667. // Now figure out the necessary offset to add to the base LV to get from
  6668. // the derived class to the base class.
  6669. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  6670. castAs<PointerType>()->getPointeeType(),
  6671. Result);
  6672. case CK_BaseToDerived:
  6673. if (!Visit(E->getSubExpr()))
  6674. return false;
  6675. if (!Result.Base && Result.Offset.isZero())
  6676. return true;
  6677. return HandleBaseToDerivedCast(Info, E, Result);
  6678. case CK_Dynamic:
  6679. if (!Visit(E->getSubExpr()))
  6680. return false;
  6681. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6682. case CK_NullToPointer:
  6683. VisitIgnoredValue(E->getSubExpr());
  6684. return ZeroInitialization(E);
  6685. case CK_IntegralToPointer: {
  6686. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6687. APValue Value;
  6688. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  6689. break;
  6690. if (Value.isInt()) {
  6691. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  6692. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  6693. Result.Base = (Expr*)nullptr;
  6694. Result.InvalidBase = false;
  6695. Result.Offset = CharUnits::fromQuantity(N);
  6696. Result.Designator.setInvalid();
  6697. Result.IsNullPtr = false;
  6698. return true;
  6699. } else {
  6700. // Cast is of an lvalue, no need to change value.
  6701. Result.setFrom(Info.Ctx, Value);
  6702. return true;
  6703. }
  6704. }
  6705. case CK_ArrayToPointerDecay: {
  6706. if (SubExpr->isGLValue()) {
  6707. if (!evaluateLValue(SubExpr, Result))
  6708. return false;
  6709. } else {
  6710. APValue &Value = Info.CurrentCall->createTemporary(
  6711. SubExpr, SubExpr->getType(), false, Result);
  6712. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  6713. return false;
  6714. }
  6715. // The result is a pointer to the first element of the array.
  6716. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  6717. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  6718. Result.addArray(Info, E, CAT);
  6719. else
  6720. Result.addUnsizedArray(Info, E, AT->getElementType());
  6721. return true;
  6722. }
  6723. case CK_FunctionToPointerDecay:
  6724. return evaluateLValue(SubExpr, Result);
  6725. case CK_LValueToRValue: {
  6726. LValue LVal;
  6727. if (!evaluateLValue(E->getSubExpr(), LVal))
  6728. return false;
  6729. APValue RVal;
  6730. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6731. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6732. LVal, RVal))
  6733. return InvalidBaseOK &&
  6734. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  6735. return Success(RVal, E);
  6736. }
  6737. }
  6738. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6739. }
  6740. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  6741. UnaryExprOrTypeTrait ExprKind) {
  6742. // C++ [expr.alignof]p3:
  6743. // When alignof is applied to a reference type, the result is the
  6744. // alignment of the referenced type.
  6745. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  6746. T = Ref->getPointeeType();
  6747. if (T.getQualifiers().hasUnaligned())
  6748. return CharUnits::One();
  6749. const bool AlignOfReturnsPreferred =
  6750. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  6751. // __alignof is defined to return the preferred alignment.
  6752. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  6753. // as well.
  6754. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  6755. return Info.Ctx.toCharUnitsFromBits(
  6756. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  6757. // alignof and _Alignof are defined to return the ABI alignment.
  6758. else if (ExprKind == UETT_AlignOf)
  6759. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  6760. else
  6761. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  6762. }
  6763. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  6764. UnaryExprOrTypeTrait ExprKind) {
  6765. E = E->IgnoreParens();
  6766. // The kinds of expressions that we have special-case logic here for
  6767. // should be kept up to date with the special checks for those
  6768. // expressions in Sema.
  6769. // alignof decl is always accepted, even if it doesn't make sense: we default
  6770. // to 1 in those cases.
  6771. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6772. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  6773. /*RefAsPointee*/true);
  6774. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  6775. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  6776. /*RefAsPointee*/true);
  6777. return GetAlignOfType(Info, E->getType(), ExprKind);
  6778. }
  6779. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  6780. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  6781. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  6782. return true;
  6783. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  6784. return false;
  6785. Result.setInvalid(E);
  6786. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  6787. Result.addUnsizedArray(Info, E, PointeeTy);
  6788. return true;
  6789. }
  6790. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6791. if (IsStringLiteralCall(E))
  6792. return Success(E);
  6793. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6794. return VisitBuiltinCallExpr(E, BuiltinOp);
  6795. return visitNonBuiltinCallExpr(E);
  6796. }
  6797. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6798. unsigned BuiltinOp) {
  6799. switch (BuiltinOp) {
  6800. case Builtin::BI__builtin_addressof:
  6801. return evaluateLValue(E->getArg(0), Result);
  6802. case Builtin::BI__builtin_assume_aligned: {
  6803. // We need to be very careful here because: if the pointer does not have the
  6804. // asserted alignment, then the behavior is undefined, and undefined
  6805. // behavior is non-constant.
  6806. if (!evaluatePointer(E->getArg(0), Result))
  6807. return false;
  6808. LValue OffsetResult(Result);
  6809. APSInt Alignment;
  6810. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  6811. return false;
  6812. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  6813. if (E->getNumArgs() > 2) {
  6814. APSInt Offset;
  6815. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  6816. return false;
  6817. int64_t AdditionalOffset = -Offset.getZExtValue();
  6818. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  6819. }
  6820. // If there is a base object, then it must have the correct alignment.
  6821. if (OffsetResult.Base) {
  6822. CharUnits BaseAlignment;
  6823. if (const ValueDecl *VD =
  6824. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  6825. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  6826. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  6827. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  6828. } else {
  6829. BaseAlignment = GetAlignOfType(
  6830. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  6831. }
  6832. if (BaseAlignment < Align) {
  6833. Result.Designator.setInvalid();
  6834. // FIXME: Add support to Diagnostic for long / long long.
  6835. CCEDiag(E->getArg(0),
  6836. diag::note_constexpr_baa_insufficient_alignment) << 0
  6837. << (unsigned)BaseAlignment.getQuantity()
  6838. << (unsigned)Align.getQuantity();
  6839. return false;
  6840. }
  6841. }
  6842. // The offset must also have the correct alignment.
  6843. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  6844. Result.Designator.setInvalid();
  6845. (OffsetResult.Base
  6846. ? CCEDiag(E->getArg(0),
  6847. diag::note_constexpr_baa_insufficient_alignment) << 1
  6848. : CCEDiag(E->getArg(0),
  6849. diag::note_constexpr_baa_value_insufficient_alignment))
  6850. << (int)OffsetResult.Offset.getQuantity()
  6851. << (unsigned)Align.getQuantity();
  6852. return false;
  6853. }
  6854. return true;
  6855. }
  6856. case Builtin::BI__builtin_launder:
  6857. return evaluatePointer(E->getArg(0), Result);
  6858. case Builtin::BIstrchr:
  6859. case Builtin::BIwcschr:
  6860. case Builtin::BImemchr:
  6861. case Builtin::BIwmemchr:
  6862. if (Info.getLangOpts().CPlusPlus11)
  6863. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6864. << /*isConstexpr*/0 << /*isConstructor*/0
  6865. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6866. else
  6867. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6868. LLVM_FALLTHROUGH;
  6869. case Builtin::BI__builtin_strchr:
  6870. case Builtin::BI__builtin_wcschr:
  6871. case Builtin::BI__builtin_memchr:
  6872. case Builtin::BI__builtin_char_memchr:
  6873. case Builtin::BI__builtin_wmemchr: {
  6874. if (!Visit(E->getArg(0)))
  6875. return false;
  6876. APSInt Desired;
  6877. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  6878. return false;
  6879. uint64_t MaxLength = uint64_t(-1);
  6880. if (BuiltinOp != Builtin::BIstrchr &&
  6881. BuiltinOp != Builtin::BIwcschr &&
  6882. BuiltinOp != Builtin::BI__builtin_strchr &&
  6883. BuiltinOp != Builtin::BI__builtin_wcschr) {
  6884. APSInt N;
  6885. if (!EvaluateInteger(E->getArg(2), N, Info))
  6886. return false;
  6887. MaxLength = N.getExtValue();
  6888. }
  6889. // We cannot find the value if there are no candidates to match against.
  6890. if (MaxLength == 0u)
  6891. return ZeroInitialization(E);
  6892. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  6893. Result.Designator.Invalid)
  6894. return false;
  6895. QualType CharTy = Result.Designator.getType(Info.Ctx);
  6896. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  6897. BuiltinOp == Builtin::BI__builtin_memchr;
  6898. assert(IsRawByte ||
  6899. Info.Ctx.hasSameUnqualifiedType(
  6900. CharTy, E->getArg(0)->getType()->getPointeeType()));
  6901. // Pointers to const void may point to objects of incomplete type.
  6902. if (IsRawByte && CharTy->isIncompleteType()) {
  6903. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  6904. return false;
  6905. }
  6906. // Give up on byte-oriented matching against multibyte elements.
  6907. // FIXME: We can compare the bytes in the correct order.
  6908. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  6909. return false;
  6910. // Figure out what value we're actually looking for (after converting to
  6911. // the corresponding unsigned type if necessary).
  6912. uint64_t DesiredVal;
  6913. bool StopAtNull = false;
  6914. switch (BuiltinOp) {
  6915. case Builtin::BIstrchr:
  6916. case Builtin::BI__builtin_strchr:
  6917. // strchr compares directly to the passed integer, and therefore
  6918. // always fails if given an int that is not a char.
  6919. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  6920. E->getArg(1)->getType(),
  6921. Desired),
  6922. Desired))
  6923. return ZeroInitialization(E);
  6924. StopAtNull = true;
  6925. LLVM_FALLTHROUGH;
  6926. case Builtin::BImemchr:
  6927. case Builtin::BI__builtin_memchr:
  6928. case Builtin::BI__builtin_char_memchr:
  6929. // memchr compares by converting both sides to unsigned char. That's also
  6930. // correct for strchr if we get this far (to cope with plain char being
  6931. // unsigned in the strchr case).
  6932. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  6933. break;
  6934. case Builtin::BIwcschr:
  6935. case Builtin::BI__builtin_wcschr:
  6936. StopAtNull = true;
  6937. LLVM_FALLTHROUGH;
  6938. case Builtin::BIwmemchr:
  6939. case Builtin::BI__builtin_wmemchr:
  6940. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  6941. DesiredVal = Desired.getZExtValue();
  6942. break;
  6943. }
  6944. for (; MaxLength; --MaxLength) {
  6945. APValue Char;
  6946. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  6947. !Char.isInt())
  6948. return false;
  6949. if (Char.getInt().getZExtValue() == DesiredVal)
  6950. return true;
  6951. if (StopAtNull && !Char.getInt())
  6952. break;
  6953. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  6954. return false;
  6955. }
  6956. // Not found: return nullptr.
  6957. return ZeroInitialization(E);
  6958. }
  6959. case Builtin::BImemcpy:
  6960. case Builtin::BImemmove:
  6961. case Builtin::BIwmemcpy:
  6962. case Builtin::BIwmemmove:
  6963. if (Info.getLangOpts().CPlusPlus11)
  6964. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6965. << /*isConstexpr*/0 << /*isConstructor*/0
  6966. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6967. else
  6968. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6969. LLVM_FALLTHROUGH;
  6970. case Builtin::BI__builtin_memcpy:
  6971. case Builtin::BI__builtin_memmove:
  6972. case Builtin::BI__builtin_wmemcpy:
  6973. case Builtin::BI__builtin_wmemmove: {
  6974. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  6975. BuiltinOp == Builtin::BIwmemmove ||
  6976. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  6977. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6978. bool Move = BuiltinOp == Builtin::BImemmove ||
  6979. BuiltinOp == Builtin::BIwmemmove ||
  6980. BuiltinOp == Builtin::BI__builtin_memmove ||
  6981. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6982. // The result of mem* is the first argument.
  6983. if (!Visit(E->getArg(0)))
  6984. return false;
  6985. LValue Dest = Result;
  6986. LValue Src;
  6987. if (!EvaluatePointer(E->getArg(1), Src, Info))
  6988. return false;
  6989. APSInt N;
  6990. if (!EvaluateInteger(E->getArg(2), N, Info))
  6991. return false;
  6992. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  6993. // If the size is zero, we treat this as always being a valid no-op.
  6994. // (Even if one of the src and dest pointers is null.)
  6995. if (!N)
  6996. return true;
  6997. // Otherwise, if either of the operands is null, we can't proceed. Don't
  6998. // try to determine the type of the copied objects, because there aren't
  6999. // any.
  7000. if (!Src.Base || !Dest.Base) {
  7001. APValue Val;
  7002. (!Src.Base ? Src : Dest).moveInto(Val);
  7003. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  7004. << Move << WChar << !!Src.Base
  7005. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  7006. return false;
  7007. }
  7008. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  7009. return false;
  7010. // We require that Src and Dest are both pointers to arrays of
  7011. // trivially-copyable type. (For the wide version, the designator will be
  7012. // invalid if the designated object is not a wchar_t.)
  7013. QualType T = Dest.Designator.getType(Info.Ctx);
  7014. QualType SrcT = Src.Designator.getType(Info.Ctx);
  7015. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  7016. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  7017. return false;
  7018. }
  7019. if (T->isIncompleteType()) {
  7020. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  7021. return false;
  7022. }
  7023. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  7024. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  7025. return false;
  7026. }
  7027. // Figure out how many T's we're copying.
  7028. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  7029. if (!WChar) {
  7030. uint64_t Remainder;
  7031. llvm::APInt OrigN = N;
  7032. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  7033. if (Remainder) {
  7034. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7035. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  7036. << (unsigned)TSize;
  7037. return false;
  7038. }
  7039. }
  7040. // Check that the copying will remain within the arrays, just so that we
  7041. // can give a more meaningful diagnostic. This implicitly also checks that
  7042. // N fits into 64 bits.
  7043. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  7044. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  7045. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  7046. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7047. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  7048. << N.toString(10, /*Signed*/false);
  7049. return false;
  7050. }
  7051. uint64_t NElems = N.getZExtValue();
  7052. uint64_t NBytes = NElems * TSize;
  7053. // Check for overlap.
  7054. int Direction = 1;
  7055. if (HasSameBase(Src, Dest)) {
  7056. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  7057. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  7058. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  7059. // Dest is inside the source region.
  7060. if (!Move) {
  7061. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7062. return false;
  7063. }
  7064. // For memmove and friends, copy backwards.
  7065. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  7066. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  7067. return false;
  7068. Direction = -1;
  7069. } else if (!Move && SrcOffset >= DestOffset &&
  7070. SrcOffset - DestOffset < NBytes) {
  7071. // Src is inside the destination region for memcpy: invalid.
  7072. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7073. return false;
  7074. }
  7075. }
  7076. while (true) {
  7077. APValue Val;
  7078. // FIXME: Set WantObjectRepresentation to true if we're copying a
  7079. // char-like type?
  7080. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  7081. !handleAssignment(Info, E, Dest, T, Val))
  7082. return false;
  7083. // Do not iterate past the last element; if we're copying backwards, that
  7084. // might take us off the start of the array.
  7085. if (--NElems == 0)
  7086. return true;
  7087. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  7088. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  7089. return false;
  7090. }
  7091. }
  7092. default:
  7093. return visitNonBuiltinCallExpr(E);
  7094. }
  7095. }
  7096. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  7097. APValue &Result, const InitListExpr *ILE,
  7098. QualType AllocType);
  7099. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  7100. // We cannot speculatively evaluate a delete expression.
  7101. if (Info.SpeculativeEvaluationDepth)
  7102. return false;
  7103. FunctionDecl *OperatorNew = E->getOperatorNew();
  7104. if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  7105. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  7106. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  7107. return false;
  7108. }
  7109. // FIXME: There is no restriction on this, but it's not clear that it
  7110. // makes any sense. We get here for cases such as:
  7111. //
  7112. // new (std::align_val_t{N}) X(int)
  7113. //
  7114. // (which should presumably be valid only if N is a multiple of
  7115. // alignof(int).
  7116. if (E->getNumPlacementArgs())
  7117. return Error(E, diag::note_constexpr_new_placement);
  7118. if (!Info.getLangOpts().CPlusPlus2a)
  7119. Info.CCEDiag(E, diag::note_constexpr_new);
  7120. const Expr *Init = E->getInitializer();
  7121. const InitListExpr *ResizedArrayILE = nullptr;
  7122. QualType AllocType = E->getAllocatedType();
  7123. if (Optional<const Expr*> ArraySize = E->getArraySize()) {
  7124. const Expr *Stripped = *ArraySize;
  7125. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  7126. Stripped = ICE->getSubExpr())
  7127. if (ICE->getCastKind() != CK_NoOp &&
  7128. ICE->getCastKind() != CK_IntegralCast)
  7129. break;
  7130. llvm::APSInt ArrayBound;
  7131. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  7132. return false;
  7133. // C++ [expr.new]p9:
  7134. // The expression is erroneous if:
  7135. // -- [...] its value before converting to size_t [or] applying the
  7136. // second standard conversion sequence is less than zero
  7137. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  7138. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  7139. << ArrayBound << (*ArraySize)->getSourceRange();
  7140. return false;
  7141. }
  7142. // -- its value is such that the size of the allocated object would
  7143. // exceed the implementation-defined limit
  7144. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  7145. ArrayBound) >
  7146. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  7147. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  7148. << ArrayBound << (*ArraySize)->getSourceRange();
  7149. return false;
  7150. }
  7151. // -- the new-initializer is a braced-init-list and the number of
  7152. // array elements for which initializers are provided [...]
  7153. // exceeds the number of elements to initialize
  7154. if (Init) {
  7155. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  7156. assert(CAT && "unexpected type for array initializer");
  7157. unsigned Bits =
  7158. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  7159. llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
  7160. llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
  7161. if (InitBound.ugt(AllocBound)) {
  7162. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  7163. << AllocBound.toString(10, /*Signed=*/false)
  7164. << InitBound.toString(10, /*Signed=*/false)
  7165. << (*ArraySize)->getSourceRange();
  7166. return false;
  7167. }
  7168. // If the sizes differ, we must have an initializer list, and we need
  7169. // special handling for this case when we initialize.
  7170. if (InitBound != AllocBound)
  7171. ResizedArrayILE = cast<InitListExpr>(Init);
  7172. }
  7173. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound,
  7174. ArrayType::Normal, 0);
  7175. } else {
  7176. assert(!AllocType->isArrayType() &&
  7177. "array allocation with non-array new");
  7178. }
  7179. // Perform the allocation and obtain a pointer to the resulting object.
  7180. APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
  7181. if (!Val)
  7182. return false;
  7183. if (ResizedArrayILE) {
  7184. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  7185. AllocType))
  7186. return false;
  7187. } else if (Init) {
  7188. if (!EvaluateInPlace(*Val, Info, Result, Init))
  7189. return false;
  7190. } else {
  7191. *Val = getDefaultInitValue(AllocType);
  7192. }
  7193. // Array new returns a pointer to the first element, not a pointer to the
  7194. // array.
  7195. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  7196. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  7197. return true;
  7198. }
  7199. //===----------------------------------------------------------------------===//
  7200. // Member Pointer Evaluation
  7201. //===----------------------------------------------------------------------===//
  7202. namespace {
  7203. class MemberPointerExprEvaluator
  7204. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  7205. MemberPtr &Result;
  7206. bool Success(const ValueDecl *D) {
  7207. Result = MemberPtr(D);
  7208. return true;
  7209. }
  7210. public:
  7211. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  7212. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7213. bool Success(const APValue &V, const Expr *E) {
  7214. Result.setFrom(V);
  7215. return true;
  7216. }
  7217. bool ZeroInitialization(const Expr *E) {
  7218. return Success((const ValueDecl*)nullptr);
  7219. }
  7220. bool VisitCastExpr(const CastExpr *E);
  7221. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7222. };
  7223. } // end anonymous namespace
  7224. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  7225. EvalInfo &Info) {
  7226. assert(E->isRValue() && E->getType()->isMemberPointerType());
  7227. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  7228. }
  7229. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7230. switch (E->getCastKind()) {
  7231. default:
  7232. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7233. case CK_NullToMemberPointer:
  7234. VisitIgnoredValue(E->getSubExpr());
  7235. return ZeroInitialization(E);
  7236. case CK_BaseToDerivedMemberPointer: {
  7237. if (!Visit(E->getSubExpr()))
  7238. return false;
  7239. if (E->path_empty())
  7240. return true;
  7241. // Base-to-derived member pointer casts store the path in derived-to-base
  7242. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  7243. // the wrong end of the derived->base arc, so stagger the path by one class.
  7244. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  7245. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  7246. PathI != PathE; ++PathI) {
  7247. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7248. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  7249. if (!Result.castToDerived(Derived))
  7250. return Error(E);
  7251. }
  7252. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  7253. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  7254. return Error(E);
  7255. return true;
  7256. }
  7257. case CK_DerivedToBaseMemberPointer:
  7258. if (!Visit(E->getSubExpr()))
  7259. return false;
  7260. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7261. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7262. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7263. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7264. if (!Result.castToBase(Base))
  7265. return Error(E);
  7266. }
  7267. return true;
  7268. }
  7269. }
  7270. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7271. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  7272. // member can be formed.
  7273. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  7274. }
  7275. //===----------------------------------------------------------------------===//
  7276. // Record Evaluation
  7277. //===----------------------------------------------------------------------===//
  7278. namespace {
  7279. class RecordExprEvaluator
  7280. : public ExprEvaluatorBase<RecordExprEvaluator> {
  7281. const LValue &This;
  7282. APValue &Result;
  7283. public:
  7284. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  7285. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  7286. bool Success(const APValue &V, const Expr *E) {
  7287. Result = V;
  7288. return true;
  7289. }
  7290. bool ZeroInitialization(const Expr *E) {
  7291. return ZeroInitialization(E, E->getType());
  7292. }
  7293. bool ZeroInitialization(const Expr *E, QualType T);
  7294. bool VisitCallExpr(const CallExpr *E) {
  7295. return handleCallExpr(E, Result, &This);
  7296. }
  7297. bool VisitCastExpr(const CastExpr *E);
  7298. bool VisitInitListExpr(const InitListExpr *E);
  7299. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7300. return VisitCXXConstructExpr(E, E->getType());
  7301. }
  7302. bool VisitLambdaExpr(const LambdaExpr *E);
  7303. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  7304. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  7305. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  7306. // Temporaries are registered when created, so we don't care about
  7307. // CXXBindTemporaryExpr.
  7308. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  7309. return Visit(E->getSubExpr());
  7310. }
  7311. bool VisitBinCmp(const BinaryOperator *E);
  7312. };
  7313. }
  7314. /// Perform zero-initialization on an object of non-union class type.
  7315. /// C++11 [dcl.init]p5:
  7316. /// To zero-initialize an object or reference of type T means:
  7317. /// [...]
  7318. /// -- if T is a (possibly cv-qualified) non-union class type,
  7319. /// each non-static data member and each base-class subobject is
  7320. /// zero-initialized
  7321. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  7322. const RecordDecl *RD,
  7323. const LValue &This, APValue &Result) {
  7324. assert(!RD->isUnion() && "Expected non-union class type");
  7325. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  7326. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  7327. std::distance(RD->field_begin(), RD->field_end()));
  7328. if (RD->isInvalidDecl()) return false;
  7329. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7330. if (CD) {
  7331. unsigned Index = 0;
  7332. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  7333. End = CD->bases_end(); I != End; ++I, ++Index) {
  7334. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  7335. LValue Subobject = This;
  7336. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  7337. return false;
  7338. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  7339. Result.getStructBase(Index)))
  7340. return false;
  7341. }
  7342. }
  7343. for (const auto *I : RD->fields()) {
  7344. // -- if T is a reference type, no initialization is performed.
  7345. if (I->getType()->isReferenceType())
  7346. continue;
  7347. LValue Subobject = This;
  7348. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  7349. return false;
  7350. ImplicitValueInitExpr VIE(I->getType());
  7351. if (!EvaluateInPlace(
  7352. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  7353. return false;
  7354. }
  7355. return true;
  7356. }
  7357. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  7358. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  7359. if (RD->isInvalidDecl()) return false;
  7360. if (RD->isUnion()) {
  7361. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  7362. // object's first non-static named data member is zero-initialized
  7363. RecordDecl::field_iterator I = RD->field_begin();
  7364. if (I == RD->field_end()) {
  7365. Result = APValue((const FieldDecl*)nullptr);
  7366. return true;
  7367. }
  7368. LValue Subobject = This;
  7369. if (!HandleLValueMember(Info, E, Subobject, *I))
  7370. return false;
  7371. Result = APValue(*I);
  7372. ImplicitValueInitExpr VIE(I->getType());
  7373. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  7374. }
  7375. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  7376. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  7377. return false;
  7378. }
  7379. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  7380. }
  7381. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7382. switch (E->getCastKind()) {
  7383. default:
  7384. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7385. case CK_ConstructorConversion:
  7386. return Visit(E->getSubExpr());
  7387. case CK_DerivedToBase:
  7388. case CK_UncheckedDerivedToBase: {
  7389. APValue DerivedObject;
  7390. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  7391. return false;
  7392. if (!DerivedObject.isStruct())
  7393. return Error(E->getSubExpr());
  7394. // Derived-to-base rvalue conversion: just slice off the derived part.
  7395. APValue *Value = &DerivedObject;
  7396. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  7397. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7398. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7399. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  7400. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7401. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  7402. RD = Base;
  7403. }
  7404. Result = *Value;
  7405. return true;
  7406. }
  7407. }
  7408. }
  7409. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7410. if (E->isTransparent())
  7411. return Visit(E->getInit(0));
  7412. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  7413. if (RD->isInvalidDecl()) return false;
  7414. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7415. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  7416. EvalInfo::EvaluatingConstructorRAII EvalObj(
  7417. Info,
  7418. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  7419. CXXRD && CXXRD->getNumBases());
  7420. if (RD->isUnion()) {
  7421. const FieldDecl *Field = E->getInitializedFieldInUnion();
  7422. Result = APValue(Field);
  7423. if (!Field)
  7424. return true;
  7425. // If the initializer list for a union does not contain any elements, the
  7426. // first element of the union is value-initialized.
  7427. // FIXME: The element should be initialized from an initializer list.
  7428. // Is this difference ever observable for initializer lists which
  7429. // we don't build?
  7430. ImplicitValueInitExpr VIE(Field->getType());
  7431. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  7432. LValue Subobject = This;
  7433. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  7434. return false;
  7435. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7436. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7437. isa<CXXDefaultInitExpr>(InitExpr));
  7438. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  7439. }
  7440. if (!Result.hasValue())
  7441. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  7442. std::distance(RD->field_begin(), RD->field_end()));
  7443. unsigned ElementNo = 0;
  7444. bool Success = true;
  7445. // Initialize base classes.
  7446. if (CXXRD && CXXRD->getNumBases()) {
  7447. for (const auto &Base : CXXRD->bases()) {
  7448. assert(ElementNo < E->getNumInits() && "missing init for base class");
  7449. const Expr *Init = E->getInit(ElementNo);
  7450. LValue Subobject = This;
  7451. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  7452. return false;
  7453. APValue &FieldVal = Result.getStructBase(ElementNo);
  7454. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  7455. if (!Info.noteFailure())
  7456. return false;
  7457. Success = false;
  7458. }
  7459. ++ElementNo;
  7460. }
  7461. EvalObj.finishedConstructingBases();
  7462. }
  7463. // Initialize members.
  7464. for (const auto *Field : RD->fields()) {
  7465. // Anonymous bit-fields are not considered members of the class for
  7466. // purposes of aggregate initialization.
  7467. if (Field->isUnnamedBitfield())
  7468. continue;
  7469. LValue Subobject = This;
  7470. bool HaveInit = ElementNo < E->getNumInits();
  7471. // FIXME: Diagnostics here should point to the end of the initializer
  7472. // list, not the start.
  7473. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  7474. Subobject, Field, &Layout))
  7475. return false;
  7476. // Perform an implicit value-initialization for members beyond the end of
  7477. // the initializer list.
  7478. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  7479. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  7480. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7481. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7482. isa<CXXDefaultInitExpr>(Init));
  7483. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7484. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  7485. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  7486. FieldVal, Field))) {
  7487. if (!Info.noteFailure())
  7488. return false;
  7489. Success = false;
  7490. }
  7491. }
  7492. return Success;
  7493. }
  7494. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7495. QualType T) {
  7496. // Note that E's type is not necessarily the type of our class here; we might
  7497. // be initializing an array element instead.
  7498. const CXXConstructorDecl *FD = E->getConstructor();
  7499. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  7500. bool ZeroInit = E->requiresZeroInitialization();
  7501. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  7502. // If we've already performed zero-initialization, we're already done.
  7503. if (Result.hasValue())
  7504. return true;
  7505. if (ZeroInit)
  7506. return ZeroInitialization(E, T);
  7507. Result = getDefaultInitValue(T);
  7508. return true;
  7509. }
  7510. const FunctionDecl *Definition = nullptr;
  7511. auto Body = FD->getBody(Definition);
  7512. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7513. return false;
  7514. // Avoid materializing a temporary for an elidable copy/move constructor.
  7515. if (E->isElidable() && !ZeroInit)
  7516. if (const MaterializeTemporaryExpr *ME
  7517. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  7518. return Visit(ME->GetTemporaryExpr());
  7519. if (ZeroInit && !ZeroInitialization(E, T))
  7520. return false;
  7521. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  7522. return HandleConstructorCall(E, This, Args,
  7523. cast<CXXConstructorDecl>(Definition), Info,
  7524. Result);
  7525. }
  7526. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  7527. const CXXInheritedCtorInitExpr *E) {
  7528. if (!Info.CurrentCall) {
  7529. assert(Info.checkingPotentialConstantExpression());
  7530. return false;
  7531. }
  7532. const CXXConstructorDecl *FD = E->getConstructor();
  7533. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  7534. return false;
  7535. const FunctionDecl *Definition = nullptr;
  7536. auto Body = FD->getBody(Definition);
  7537. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7538. return false;
  7539. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  7540. cast<CXXConstructorDecl>(Definition), Info,
  7541. Result);
  7542. }
  7543. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  7544. const CXXStdInitializerListExpr *E) {
  7545. const ConstantArrayType *ArrayType =
  7546. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  7547. LValue Array;
  7548. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  7549. return false;
  7550. // Get a pointer to the first element of the array.
  7551. Array.addArray(Info, E, ArrayType);
  7552. // FIXME: Perform the checks on the field types in SemaInit.
  7553. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  7554. RecordDecl::field_iterator Field = Record->field_begin();
  7555. if (Field == Record->field_end())
  7556. return Error(E);
  7557. // Start pointer.
  7558. if (!Field->getType()->isPointerType() ||
  7559. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7560. ArrayType->getElementType()))
  7561. return Error(E);
  7562. // FIXME: What if the initializer_list type has base classes, etc?
  7563. Result = APValue(APValue::UninitStruct(), 0, 2);
  7564. Array.moveInto(Result.getStructField(0));
  7565. if (++Field == Record->field_end())
  7566. return Error(E);
  7567. if (Field->getType()->isPointerType() &&
  7568. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7569. ArrayType->getElementType())) {
  7570. // End pointer.
  7571. if (!HandleLValueArrayAdjustment(Info, E, Array,
  7572. ArrayType->getElementType(),
  7573. ArrayType->getSize().getZExtValue()))
  7574. return false;
  7575. Array.moveInto(Result.getStructField(1));
  7576. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  7577. // Length.
  7578. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  7579. else
  7580. return Error(E);
  7581. if (++Field != Record->field_end())
  7582. return Error(E);
  7583. return true;
  7584. }
  7585. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  7586. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  7587. if (ClosureClass->isInvalidDecl())
  7588. return false;
  7589. const size_t NumFields =
  7590. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  7591. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  7592. E->capture_init_end()) &&
  7593. "The number of lambda capture initializers should equal the number of "
  7594. "fields within the closure type");
  7595. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  7596. // Iterate through all the lambda's closure object's fields and initialize
  7597. // them.
  7598. auto *CaptureInitIt = E->capture_init_begin();
  7599. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  7600. bool Success = true;
  7601. for (const auto *Field : ClosureClass->fields()) {
  7602. assert(CaptureInitIt != E->capture_init_end());
  7603. // Get the initializer for this field
  7604. Expr *const CurFieldInit = *CaptureInitIt++;
  7605. // If there is no initializer, either this is a VLA or an error has
  7606. // occurred.
  7607. if (!CurFieldInit)
  7608. return Error(E);
  7609. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7610. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  7611. if (!Info.keepEvaluatingAfterFailure())
  7612. return false;
  7613. Success = false;
  7614. }
  7615. ++CaptureIt;
  7616. }
  7617. return Success;
  7618. }
  7619. static bool EvaluateRecord(const Expr *E, const LValue &This,
  7620. APValue &Result, EvalInfo &Info) {
  7621. assert(E->isRValue() && E->getType()->isRecordType() &&
  7622. "can't evaluate expression as a record rvalue");
  7623. return RecordExprEvaluator(Info, This, Result).Visit(E);
  7624. }
  7625. //===----------------------------------------------------------------------===//
  7626. // Temporary Evaluation
  7627. //
  7628. // Temporaries are represented in the AST as rvalues, but generally behave like
  7629. // lvalues. The full-object of which the temporary is a subobject is implicitly
  7630. // materialized so that a reference can bind to it.
  7631. //===----------------------------------------------------------------------===//
  7632. namespace {
  7633. class TemporaryExprEvaluator
  7634. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  7635. public:
  7636. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  7637. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  7638. /// Visit an expression which constructs the value of this temporary.
  7639. bool VisitConstructExpr(const Expr *E) {
  7640. APValue &Value =
  7641. Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
  7642. return EvaluateInPlace(Value, Info, Result, E);
  7643. }
  7644. bool VisitCastExpr(const CastExpr *E) {
  7645. switch (E->getCastKind()) {
  7646. default:
  7647. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7648. case CK_ConstructorConversion:
  7649. return VisitConstructExpr(E->getSubExpr());
  7650. }
  7651. }
  7652. bool VisitInitListExpr(const InitListExpr *E) {
  7653. return VisitConstructExpr(E);
  7654. }
  7655. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7656. return VisitConstructExpr(E);
  7657. }
  7658. bool VisitCallExpr(const CallExpr *E) {
  7659. return VisitConstructExpr(E);
  7660. }
  7661. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  7662. return VisitConstructExpr(E);
  7663. }
  7664. bool VisitLambdaExpr(const LambdaExpr *E) {
  7665. return VisitConstructExpr(E);
  7666. }
  7667. };
  7668. } // end anonymous namespace
  7669. /// Evaluate an expression of record type as a temporary.
  7670. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  7671. assert(E->isRValue() && E->getType()->isRecordType());
  7672. return TemporaryExprEvaluator(Info, Result).Visit(E);
  7673. }
  7674. //===----------------------------------------------------------------------===//
  7675. // Vector Evaluation
  7676. //===----------------------------------------------------------------------===//
  7677. namespace {
  7678. class VectorExprEvaluator
  7679. : public ExprEvaluatorBase<VectorExprEvaluator> {
  7680. APValue &Result;
  7681. public:
  7682. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  7683. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7684. bool Success(ArrayRef<APValue> V, const Expr *E) {
  7685. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  7686. // FIXME: remove this APValue copy.
  7687. Result = APValue(V.data(), V.size());
  7688. return true;
  7689. }
  7690. bool Success(const APValue &V, const Expr *E) {
  7691. assert(V.isVector());
  7692. Result = V;
  7693. return true;
  7694. }
  7695. bool ZeroInitialization(const Expr *E);
  7696. bool VisitUnaryReal(const UnaryOperator *E)
  7697. { return Visit(E->getSubExpr()); }
  7698. bool VisitCastExpr(const CastExpr* E);
  7699. bool VisitInitListExpr(const InitListExpr *E);
  7700. bool VisitUnaryImag(const UnaryOperator *E);
  7701. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  7702. // binary comparisons, binary and/or/xor,
  7703. // shufflevector, ExtVectorElementExpr
  7704. };
  7705. } // end anonymous namespace
  7706. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  7707. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  7708. return VectorExprEvaluator(Info, Result).Visit(E);
  7709. }
  7710. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7711. const VectorType *VTy = E->getType()->castAs<VectorType>();
  7712. unsigned NElts = VTy->getNumElements();
  7713. const Expr *SE = E->getSubExpr();
  7714. QualType SETy = SE->getType();
  7715. switch (E->getCastKind()) {
  7716. case CK_VectorSplat: {
  7717. APValue Val = APValue();
  7718. if (SETy->isIntegerType()) {
  7719. APSInt IntResult;
  7720. if (!EvaluateInteger(SE, IntResult, Info))
  7721. return false;
  7722. Val = APValue(std::move(IntResult));
  7723. } else if (SETy->isRealFloatingType()) {
  7724. APFloat FloatResult(0.0);
  7725. if (!EvaluateFloat(SE, FloatResult, Info))
  7726. return false;
  7727. Val = APValue(std::move(FloatResult));
  7728. } else {
  7729. return Error(E);
  7730. }
  7731. // Splat and create vector APValue.
  7732. SmallVector<APValue, 4> Elts(NElts, Val);
  7733. return Success(Elts, E);
  7734. }
  7735. case CK_BitCast: {
  7736. // Evaluate the operand into an APInt we can extract from.
  7737. llvm::APInt SValInt;
  7738. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  7739. return false;
  7740. // Extract the elements
  7741. QualType EltTy = VTy->getElementType();
  7742. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  7743. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  7744. SmallVector<APValue, 4> Elts;
  7745. if (EltTy->isRealFloatingType()) {
  7746. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  7747. unsigned FloatEltSize = EltSize;
  7748. if (&Sem == &APFloat::x87DoubleExtended())
  7749. FloatEltSize = 80;
  7750. for (unsigned i = 0; i < NElts; i++) {
  7751. llvm::APInt Elt;
  7752. if (BigEndian)
  7753. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  7754. else
  7755. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  7756. Elts.push_back(APValue(APFloat(Sem, Elt)));
  7757. }
  7758. } else if (EltTy->isIntegerType()) {
  7759. for (unsigned i = 0; i < NElts; i++) {
  7760. llvm::APInt Elt;
  7761. if (BigEndian)
  7762. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  7763. else
  7764. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  7765. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  7766. }
  7767. } else {
  7768. return Error(E);
  7769. }
  7770. return Success(Elts, E);
  7771. }
  7772. default:
  7773. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7774. }
  7775. }
  7776. bool
  7777. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7778. const VectorType *VT = E->getType()->castAs<VectorType>();
  7779. unsigned NumInits = E->getNumInits();
  7780. unsigned NumElements = VT->getNumElements();
  7781. QualType EltTy = VT->getElementType();
  7782. SmallVector<APValue, 4> Elements;
  7783. // The number of initializers can be less than the number of
  7784. // vector elements. For OpenCL, this can be due to nested vector
  7785. // initialization. For GCC compatibility, missing trailing elements
  7786. // should be initialized with zeroes.
  7787. unsigned CountInits = 0, CountElts = 0;
  7788. while (CountElts < NumElements) {
  7789. // Handle nested vector initialization.
  7790. if (CountInits < NumInits
  7791. && E->getInit(CountInits)->getType()->isVectorType()) {
  7792. APValue v;
  7793. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  7794. return Error(E);
  7795. unsigned vlen = v.getVectorLength();
  7796. for (unsigned j = 0; j < vlen; j++)
  7797. Elements.push_back(v.getVectorElt(j));
  7798. CountElts += vlen;
  7799. } else if (EltTy->isIntegerType()) {
  7800. llvm::APSInt sInt(32);
  7801. if (CountInits < NumInits) {
  7802. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  7803. return false;
  7804. } else // trailing integer zero.
  7805. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  7806. Elements.push_back(APValue(sInt));
  7807. CountElts++;
  7808. } else {
  7809. llvm::APFloat f(0.0);
  7810. if (CountInits < NumInits) {
  7811. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  7812. return false;
  7813. } else // trailing float zero.
  7814. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  7815. Elements.push_back(APValue(f));
  7816. CountElts++;
  7817. }
  7818. CountInits++;
  7819. }
  7820. return Success(Elements, E);
  7821. }
  7822. bool
  7823. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  7824. const VectorType *VT = E->getType()->getAs<VectorType>();
  7825. QualType EltTy = VT->getElementType();
  7826. APValue ZeroElement;
  7827. if (EltTy->isIntegerType())
  7828. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  7829. else
  7830. ZeroElement =
  7831. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  7832. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  7833. return Success(Elements, E);
  7834. }
  7835. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7836. VisitIgnoredValue(E->getSubExpr());
  7837. return ZeroInitialization(E);
  7838. }
  7839. //===----------------------------------------------------------------------===//
  7840. // Array Evaluation
  7841. //===----------------------------------------------------------------------===//
  7842. namespace {
  7843. class ArrayExprEvaluator
  7844. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  7845. const LValue &This;
  7846. APValue &Result;
  7847. public:
  7848. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  7849. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  7850. bool Success(const APValue &V, const Expr *E) {
  7851. assert(V.isArray() && "expected array");
  7852. Result = V;
  7853. return true;
  7854. }
  7855. bool ZeroInitialization(const Expr *E) {
  7856. const ConstantArrayType *CAT =
  7857. Info.Ctx.getAsConstantArrayType(E->getType());
  7858. if (!CAT)
  7859. return Error(E);
  7860. Result = APValue(APValue::UninitArray(), 0,
  7861. CAT->getSize().getZExtValue());
  7862. if (!Result.hasArrayFiller()) return true;
  7863. // Zero-initialize all elements.
  7864. LValue Subobject = This;
  7865. Subobject.addArray(Info, E, CAT);
  7866. ImplicitValueInitExpr VIE(CAT->getElementType());
  7867. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  7868. }
  7869. bool VisitCallExpr(const CallExpr *E) {
  7870. return handleCallExpr(E, Result, &This);
  7871. }
  7872. bool VisitInitListExpr(const InitListExpr *E,
  7873. QualType AllocType = QualType());
  7874. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  7875. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  7876. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  7877. const LValue &Subobject,
  7878. APValue *Value, QualType Type);
  7879. bool VisitStringLiteral(const StringLiteral *E,
  7880. QualType AllocType = QualType()) {
  7881. expandStringLiteral(Info, E, Result, AllocType);
  7882. return true;
  7883. }
  7884. };
  7885. } // end anonymous namespace
  7886. static bool EvaluateArray(const Expr *E, const LValue &This,
  7887. APValue &Result, EvalInfo &Info) {
  7888. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  7889. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  7890. }
  7891. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  7892. APValue &Result, const InitListExpr *ILE,
  7893. QualType AllocType) {
  7894. assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
  7895. "not an array rvalue");
  7896. return ArrayExprEvaluator(Info, This, Result)
  7897. .VisitInitListExpr(ILE, AllocType);
  7898. }
  7899. // Return true iff the given array filler may depend on the element index.
  7900. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  7901. // For now, just whitelist non-class value-initialization and initialization
  7902. // lists comprised of them.
  7903. if (isa<ImplicitValueInitExpr>(FillerExpr))
  7904. return false;
  7905. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  7906. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  7907. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  7908. return true;
  7909. }
  7910. return false;
  7911. }
  7912. return true;
  7913. }
  7914. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  7915. QualType AllocType) {
  7916. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  7917. AllocType.isNull() ? E->getType() : AllocType);
  7918. if (!CAT)
  7919. return Error(E);
  7920. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  7921. // an appropriately-typed string literal enclosed in braces.
  7922. if (E->isStringLiteralInit()) {
  7923. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
  7924. // FIXME: Support ObjCEncodeExpr here once we support it in
  7925. // ArrayExprEvaluator generally.
  7926. if (!SL)
  7927. return Error(E);
  7928. return VisitStringLiteral(SL, AllocType);
  7929. }
  7930. bool Success = true;
  7931. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  7932. "zero-initialized array shouldn't have any initialized elts");
  7933. APValue Filler;
  7934. if (Result.isArray() && Result.hasArrayFiller())
  7935. Filler = Result.getArrayFiller();
  7936. unsigned NumEltsToInit = E->getNumInits();
  7937. unsigned NumElts = CAT->getSize().getZExtValue();
  7938. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  7939. // If the initializer might depend on the array index, run it for each
  7940. // array element.
  7941. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  7942. NumEltsToInit = NumElts;
  7943. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  7944. << NumEltsToInit << ".\n");
  7945. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  7946. // If the array was previously zero-initialized, preserve the
  7947. // zero-initialized values.
  7948. if (Filler.hasValue()) {
  7949. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  7950. Result.getArrayInitializedElt(I) = Filler;
  7951. if (Result.hasArrayFiller())
  7952. Result.getArrayFiller() = Filler;
  7953. }
  7954. LValue Subobject = This;
  7955. Subobject.addArray(Info, E, CAT);
  7956. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  7957. const Expr *Init =
  7958. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  7959. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7960. Info, Subobject, Init) ||
  7961. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  7962. CAT->getElementType(), 1)) {
  7963. if (!Info.noteFailure())
  7964. return false;
  7965. Success = false;
  7966. }
  7967. }
  7968. if (!Result.hasArrayFiller())
  7969. return Success;
  7970. // If we get here, we have a trivial filler, which we can just evaluate
  7971. // once and splat over the rest of the array elements.
  7972. assert(FillerExpr && "no array filler for incomplete init list");
  7973. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  7974. FillerExpr) && Success;
  7975. }
  7976. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  7977. LValue CommonLV;
  7978. if (E->getCommonExpr() &&
  7979. !Evaluate(Info.CurrentCall->createTemporary(
  7980. E->getCommonExpr(),
  7981. getStorageType(Info.Ctx, E->getCommonExpr()), false,
  7982. CommonLV),
  7983. Info, E->getCommonExpr()->getSourceExpr()))
  7984. return false;
  7985. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  7986. uint64_t Elements = CAT->getSize().getZExtValue();
  7987. Result = APValue(APValue::UninitArray(), Elements, Elements);
  7988. LValue Subobject = This;
  7989. Subobject.addArray(Info, E, CAT);
  7990. bool Success = true;
  7991. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  7992. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7993. Info, Subobject, E->getSubExpr()) ||
  7994. !HandleLValueArrayAdjustment(Info, E, Subobject,
  7995. CAT->getElementType(), 1)) {
  7996. if (!Info.noteFailure())
  7997. return false;
  7998. Success = false;
  7999. }
  8000. }
  8001. return Success;
  8002. }
  8003. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8004. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  8005. }
  8006. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8007. const LValue &Subobject,
  8008. APValue *Value,
  8009. QualType Type) {
  8010. bool HadZeroInit = Value->hasValue();
  8011. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  8012. unsigned N = CAT->getSize().getZExtValue();
  8013. // Preserve the array filler if we had prior zero-initialization.
  8014. APValue Filler =
  8015. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  8016. : APValue();
  8017. *Value = APValue(APValue::UninitArray(), N, N);
  8018. if (HadZeroInit)
  8019. for (unsigned I = 0; I != N; ++I)
  8020. Value->getArrayInitializedElt(I) = Filler;
  8021. // Initialize the elements.
  8022. LValue ArrayElt = Subobject;
  8023. ArrayElt.addArray(Info, E, CAT);
  8024. for (unsigned I = 0; I != N; ++I)
  8025. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  8026. CAT->getElementType()) ||
  8027. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  8028. CAT->getElementType(), 1))
  8029. return false;
  8030. return true;
  8031. }
  8032. if (!Type->isRecordType())
  8033. return Error(E);
  8034. return RecordExprEvaluator(Info, Subobject, *Value)
  8035. .VisitCXXConstructExpr(E, Type);
  8036. }
  8037. //===----------------------------------------------------------------------===//
  8038. // Integer Evaluation
  8039. //
  8040. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  8041. // types and back in constant folding. Integer values are thus represented
  8042. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  8043. //===----------------------------------------------------------------------===//
  8044. namespace {
  8045. class IntExprEvaluator
  8046. : public ExprEvaluatorBase<IntExprEvaluator> {
  8047. APValue &Result;
  8048. public:
  8049. IntExprEvaluator(EvalInfo &info, APValue &result)
  8050. : ExprEvaluatorBaseTy(info), Result(result) {}
  8051. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  8052. assert(E->getType()->isIntegralOrEnumerationType() &&
  8053. "Invalid evaluation result.");
  8054. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  8055. "Invalid evaluation result.");
  8056. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8057. "Invalid evaluation result.");
  8058. Result = APValue(SI);
  8059. return true;
  8060. }
  8061. bool Success(const llvm::APSInt &SI, const Expr *E) {
  8062. return Success(SI, E, Result);
  8063. }
  8064. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  8065. assert(E->getType()->isIntegralOrEnumerationType() &&
  8066. "Invalid evaluation result.");
  8067. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8068. "Invalid evaluation result.");
  8069. Result = APValue(APSInt(I));
  8070. Result.getInt().setIsUnsigned(
  8071. E->getType()->isUnsignedIntegerOrEnumerationType());
  8072. return true;
  8073. }
  8074. bool Success(const llvm::APInt &I, const Expr *E) {
  8075. return Success(I, E, Result);
  8076. }
  8077. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8078. assert(E->getType()->isIntegralOrEnumerationType() &&
  8079. "Invalid evaluation result.");
  8080. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  8081. return true;
  8082. }
  8083. bool Success(uint64_t Value, const Expr *E) {
  8084. return Success(Value, E, Result);
  8085. }
  8086. bool Success(CharUnits Size, const Expr *E) {
  8087. return Success(Size.getQuantity(), E);
  8088. }
  8089. bool Success(const APValue &V, const Expr *E) {
  8090. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  8091. Result = V;
  8092. return true;
  8093. }
  8094. return Success(V.getInt(), E);
  8095. }
  8096. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  8097. //===--------------------------------------------------------------------===//
  8098. // Visitor Methods
  8099. //===--------------------------------------------------------------------===//
  8100. bool VisitConstantExpr(const ConstantExpr *E);
  8101. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  8102. return Success(E->getValue(), E);
  8103. }
  8104. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  8105. return Success(E->getValue(), E);
  8106. }
  8107. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  8108. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  8109. if (CheckReferencedDecl(E, E->getDecl()))
  8110. return true;
  8111. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  8112. }
  8113. bool VisitMemberExpr(const MemberExpr *E) {
  8114. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  8115. VisitIgnoredBaseExpression(E->getBase());
  8116. return true;
  8117. }
  8118. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  8119. }
  8120. bool VisitCallExpr(const CallExpr *E);
  8121. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  8122. bool VisitBinaryOperator(const BinaryOperator *E);
  8123. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  8124. bool VisitUnaryOperator(const UnaryOperator *E);
  8125. bool VisitCastExpr(const CastExpr* E);
  8126. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  8127. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  8128. return Success(E->getValue(), E);
  8129. }
  8130. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  8131. return Success(E->getValue(), E);
  8132. }
  8133. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  8134. if (Info.ArrayInitIndex == uint64_t(-1)) {
  8135. // We were asked to evaluate this subexpression independent of the
  8136. // enclosing ArrayInitLoopExpr. We can't do that.
  8137. Info.FFDiag(E);
  8138. return false;
  8139. }
  8140. return Success(Info.ArrayInitIndex, E);
  8141. }
  8142. // Note, GNU defines __null as an integer, not a pointer.
  8143. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  8144. return ZeroInitialization(E);
  8145. }
  8146. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  8147. return Success(E->getValue(), E);
  8148. }
  8149. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  8150. return Success(E->getValue(), E);
  8151. }
  8152. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  8153. return Success(E->getValue(), E);
  8154. }
  8155. bool VisitUnaryReal(const UnaryOperator *E);
  8156. bool VisitUnaryImag(const UnaryOperator *E);
  8157. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  8158. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  8159. bool VisitSourceLocExpr(const SourceLocExpr *E);
  8160. // FIXME: Missing: array subscript of vector, member of vector
  8161. };
  8162. class FixedPointExprEvaluator
  8163. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  8164. APValue &Result;
  8165. public:
  8166. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  8167. : ExprEvaluatorBaseTy(info), Result(result) {}
  8168. bool Success(const llvm::APInt &I, const Expr *E) {
  8169. return Success(
  8170. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8171. }
  8172. bool Success(uint64_t Value, const Expr *E) {
  8173. return Success(
  8174. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8175. }
  8176. bool Success(const APValue &V, const Expr *E) {
  8177. return Success(V.getFixedPoint(), E);
  8178. }
  8179. bool Success(const APFixedPoint &V, const Expr *E) {
  8180. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  8181. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8182. "Invalid evaluation result.");
  8183. Result = APValue(V);
  8184. return true;
  8185. }
  8186. //===--------------------------------------------------------------------===//
  8187. // Visitor Methods
  8188. //===--------------------------------------------------------------------===//
  8189. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  8190. return Success(E->getValue(), E);
  8191. }
  8192. bool VisitCastExpr(const CastExpr *E);
  8193. bool VisitUnaryOperator(const UnaryOperator *E);
  8194. bool VisitBinaryOperator(const BinaryOperator *E);
  8195. };
  8196. } // end anonymous namespace
  8197. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  8198. /// produce either the integer value or a pointer.
  8199. ///
  8200. /// GCC has a heinous extension which folds casts between pointer types and
  8201. /// pointer-sized integral types. We support this by allowing the evaluation of
  8202. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  8203. /// Some simple arithmetic on such values is supported (they are treated much
  8204. /// like char*).
  8205. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  8206. EvalInfo &Info) {
  8207. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  8208. return IntExprEvaluator(Info, Result).Visit(E);
  8209. }
  8210. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  8211. APValue Val;
  8212. if (!EvaluateIntegerOrLValue(E, Val, Info))
  8213. return false;
  8214. if (!Val.isInt()) {
  8215. // FIXME: It would be better to produce the diagnostic for casting
  8216. // a pointer to an integer.
  8217. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8218. return false;
  8219. }
  8220. Result = Val.getInt();
  8221. return true;
  8222. }
  8223. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  8224. APValue Evaluated = E->EvaluateInContext(
  8225. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  8226. return Success(Evaluated, E);
  8227. }
  8228. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  8229. EvalInfo &Info) {
  8230. if (E->getType()->isFixedPointType()) {
  8231. APValue Val;
  8232. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  8233. return false;
  8234. if (!Val.isFixedPoint())
  8235. return false;
  8236. Result = Val.getFixedPoint();
  8237. return true;
  8238. }
  8239. return false;
  8240. }
  8241. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  8242. EvalInfo &Info) {
  8243. if (E->getType()->isIntegerType()) {
  8244. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  8245. APSInt Val;
  8246. if (!EvaluateInteger(E, Val, Info))
  8247. return false;
  8248. Result = APFixedPoint(Val, FXSema);
  8249. return true;
  8250. } else if (E->getType()->isFixedPointType()) {
  8251. return EvaluateFixedPoint(E, Result, Info);
  8252. }
  8253. return false;
  8254. }
  8255. /// Check whether the given declaration can be directly converted to an integral
  8256. /// rvalue. If not, no diagnostic is produced; there are other things we can
  8257. /// try.
  8258. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  8259. // Enums are integer constant exprs.
  8260. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  8261. // Check for signedness/width mismatches between E type and ECD value.
  8262. bool SameSign = (ECD->getInitVal().isSigned()
  8263. == E->getType()->isSignedIntegerOrEnumerationType());
  8264. bool SameWidth = (ECD->getInitVal().getBitWidth()
  8265. == Info.Ctx.getIntWidth(E->getType()));
  8266. if (SameSign && SameWidth)
  8267. return Success(ECD->getInitVal(), E);
  8268. else {
  8269. // Get rid of mismatch (otherwise Success assertions will fail)
  8270. // by computing a new value matching the type of E.
  8271. llvm::APSInt Val = ECD->getInitVal();
  8272. if (!SameSign)
  8273. Val.setIsSigned(!ECD->getInitVal().isSigned());
  8274. if (!SameWidth)
  8275. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  8276. return Success(Val, E);
  8277. }
  8278. }
  8279. return false;
  8280. }
  8281. /// Values returned by __builtin_classify_type, chosen to match the values
  8282. /// produced by GCC's builtin.
  8283. enum class GCCTypeClass {
  8284. None = -1,
  8285. Void = 0,
  8286. Integer = 1,
  8287. // GCC reserves 2 for character types, but instead classifies them as
  8288. // integers.
  8289. Enum = 3,
  8290. Bool = 4,
  8291. Pointer = 5,
  8292. // GCC reserves 6 for references, but appears to never use it (because
  8293. // expressions never have reference type, presumably).
  8294. PointerToDataMember = 7,
  8295. RealFloat = 8,
  8296. Complex = 9,
  8297. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  8298. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8299. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  8300. // uses 12 for that purpose, same as for a class or struct. Maybe it
  8301. // internally implements a pointer to member as a struct? Who knows.
  8302. PointerToMemberFunction = 12, // Not a bug, see above.
  8303. ClassOrStruct = 12,
  8304. Union = 13,
  8305. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  8306. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8307. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  8308. // literals.
  8309. };
  8310. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8311. /// as GCC.
  8312. static GCCTypeClass
  8313. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  8314. assert(!T->isDependentType() && "unexpected dependent type");
  8315. QualType CanTy = T.getCanonicalType();
  8316. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  8317. switch (CanTy->getTypeClass()) {
  8318. #define TYPE(ID, BASE)
  8319. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8320. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  8321. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8322. #include "clang/AST/TypeNodes.def"
  8323. case Type::Auto:
  8324. case Type::DeducedTemplateSpecialization:
  8325. llvm_unreachable("unexpected non-canonical or dependent type");
  8326. case Type::Builtin:
  8327. switch (BT->getKind()) {
  8328. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  8329. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  8330. case BuiltinType::ID: return GCCTypeClass::Integer;
  8331. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  8332. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  8333. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  8334. case BuiltinType::ID: break;
  8335. #include "clang/AST/BuiltinTypes.def"
  8336. case BuiltinType::Void:
  8337. return GCCTypeClass::Void;
  8338. case BuiltinType::Bool:
  8339. return GCCTypeClass::Bool;
  8340. case BuiltinType::Char_U:
  8341. case BuiltinType::UChar:
  8342. case BuiltinType::WChar_U:
  8343. case BuiltinType::Char8:
  8344. case BuiltinType::Char16:
  8345. case BuiltinType::Char32:
  8346. case BuiltinType::UShort:
  8347. case BuiltinType::UInt:
  8348. case BuiltinType::ULong:
  8349. case BuiltinType::ULongLong:
  8350. case BuiltinType::UInt128:
  8351. return GCCTypeClass::Integer;
  8352. case BuiltinType::UShortAccum:
  8353. case BuiltinType::UAccum:
  8354. case BuiltinType::ULongAccum:
  8355. case BuiltinType::UShortFract:
  8356. case BuiltinType::UFract:
  8357. case BuiltinType::ULongFract:
  8358. case BuiltinType::SatUShortAccum:
  8359. case BuiltinType::SatUAccum:
  8360. case BuiltinType::SatULongAccum:
  8361. case BuiltinType::SatUShortFract:
  8362. case BuiltinType::SatUFract:
  8363. case BuiltinType::SatULongFract:
  8364. return GCCTypeClass::None;
  8365. case BuiltinType::NullPtr:
  8366. case BuiltinType::ObjCId:
  8367. case BuiltinType::ObjCClass:
  8368. case BuiltinType::ObjCSel:
  8369. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  8370. case BuiltinType::Id:
  8371. #include "clang/Basic/OpenCLImageTypes.def"
  8372. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  8373. case BuiltinType::Id:
  8374. #include "clang/Basic/OpenCLExtensionTypes.def"
  8375. case BuiltinType::OCLSampler:
  8376. case BuiltinType::OCLEvent:
  8377. case BuiltinType::OCLClkEvent:
  8378. case BuiltinType::OCLQueue:
  8379. case BuiltinType::OCLReserveID:
  8380. #define SVE_TYPE(Name, Id, SingletonId) \
  8381. case BuiltinType::Id:
  8382. #include "clang/Basic/AArch64SVEACLETypes.def"
  8383. return GCCTypeClass::None;
  8384. case BuiltinType::Dependent:
  8385. llvm_unreachable("unexpected dependent type");
  8386. };
  8387. llvm_unreachable("unexpected placeholder type");
  8388. case Type::Enum:
  8389. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  8390. case Type::Pointer:
  8391. case Type::ConstantArray:
  8392. case Type::VariableArray:
  8393. case Type::IncompleteArray:
  8394. case Type::FunctionNoProto:
  8395. case Type::FunctionProto:
  8396. return GCCTypeClass::Pointer;
  8397. case Type::MemberPointer:
  8398. return CanTy->isMemberDataPointerType()
  8399. ? GCCTypeClass::PointerToDataMember
  8400. : GCCTypeClass::PointerToMemberFunction;
  8401. case Type::Complex:
  8402. return GCCTypeClass::Complex;
  8403. case Type::Record:
  8404. return CanTy->isUnionType() ? GCCTypeClass::Union
  8405. : GCCTypeClass::ClassOrStruct;
  8406. case Type::Atomic:
  8407. // GCC classifies _Atomic T the same as T.
  8408. return EvaluateBuiltinClassifyType(
  8409. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  8410. case Type::BlockPointer:
  8411. case Type::Vector:
  8412. case Type::ExtVector:
  8413. case Type::ObjCObject:
  8414. case Type::ObjCInterface:
  8415. case Type::ObjCObjectPointer:
  8416. case Type::Pipe:
  8417. // GCC classifies vectors as None. We follow its lead and classify all
  8418. // other types that don't fit into the regular classification the same way.
  8419. return GCCTypeClass::None;
  8420. case Type::LValueReference:
  8421. case Type::RValueReference:
  8422. llvm_unreachable("invalid type for expression");
  8423. }
  8424. llvm_unreachable("unexpected type class");
  8425. }
  8426. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8427. /// as GCC.
  8428. static GCCTypeClass
  8429. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  8430. // If no argument was supplied, default to None. This isn't
  8431. // ideal, however it is what gcc does.
  8432. if (E->getNumArgs() == 0)
  8433. return GCCTypeClass::None;
  8434. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  8435. // being an ICE, but still folds it to a constant using the type of the first
  8436. // argument.
  8437. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  8438. }
  8439. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  8440. /// __builtin_constant_p when applied to the given pointer.
  8441. ///
  8442. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  8443. /// or it points to the first character of a string literal.
  8444. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  8445. APValue::LValueBase Base = LV.getLValueBase();
  8446. if (Base.isNull()) {
  8447. // A null base is acceptable.
  8448. return true;
  8449. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  8450. if (!isa<StringLiteral>(E))
  8451. return false;
  8452. return LV.getLValueOffset().isZero();
  8453. } else if (Base.is<TypeInfoLValue>()) {
  8454. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  8455. // evaluate to true.
  8456. return true;
  8457. } else {
  8458. // Any other base is not constant enough for GCC.
  8459. return false;
  8460. }
  8461. }
  8462. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  8463. /// GCC as we can manage.
  8464. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  8465. // This evaluation is not permitted to have side-effects, so evaluate it in
  8466. // a speculative evaluation context.
  8467. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8468. // Constant-folding is always enabled for the operand of __builtin_constant_p
  8469. // (even when the enclosing evaluation context otherwise requires a strict
  8470. // language-specific constant expression).
  8471. FoldConstant Fold(Info, true);
  8472. QualType ArgType = Arg->getType();
  8473. // __builtin_constant_p always has one operand. The rules which gcc follows
  8474. // are not precisely documented, but are as follows:
  8475. //
  8476. // - If the operand is of integral, floating, complex or enumeration type,
  8477. // and can be folded to a known value of that type, it returns 1.
  8478. // - If the operand can be folded to a pointer to the first character
  8479. // of a string literal (or such a pointer cast to an integral type)
  8480. // or to a null pointer or an integer cast to a pointer, it returns 1.
  8481. //
  8482. // Otherwise, it returns 0.
  8483. //
  8484. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  8485. // its support for this did not work prior to GCC 9 and is not yet well
  8486. // understood.
  8487. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  8488. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  8489. ArgType->isNullPtrType()) {
  8490. APValue V;
  8491. if (!::EvaluateAsRValue(Info, Arg, V)) {
  8492. Fold.keepDiagnostics();
  8493. return false;
  8494. }
  8495. // For a pointer (possibly cast to integer), there are special rules.
  8496. if (V.getKind() == APValue::LValue)
  8497. return EvaluateBuiltinConstantPForLValue(V);
  8498. // Otherwise, any constant value is good enough.
  8499. return V.hasValue();
  8500. }
  8501. // Anything else isn't considered to be sufficiently constant.
  8502. return false;
  8503. }
  8504. /// Retrieves the "underlying object type" of the given expression,
  8505. /// as used by __builtin_object_size.
  8506. static QualType getObjectType(APValue::LValueBase B) {
  8507. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  8508. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  8509. return VD->getType();
  8510. } else if (const Expr *E = B.get<const Expr*>()) {
  8511. if (isa<CompoundLiteralExpr>(E))
  8512. return E->getType();
  8513. } else if (B.is<TypeInfoLValue>()) {
  8514. return B.getTypeInfoType();
  8515. } else if (B.is<DynamicAllocLValue>()) {
  8516. return B.getDynamicAllocType();
  8517. }
  8518. return QualType();
  8519. }
  8520. /// A more selective version of E->IgnoreParenCasts for
  8521. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  8522. /// to change the type of E.
  8523. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  8524. ///
  8525. /// Always returns an RValue with a pointer representation.
  8526. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  8527. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  8528. auto *NoParens = E->IgnoreParens();
  8529. auto *Cast = dyn_cast<CastExpr>(NoParens);
  8530. if (Cast == nullptr)
  8531. return NoParens;
  8532. // We only conservatively allow a few kinds of casts, because this code is
  8533. // inherently a simple solution that seeks to support the common case.
  8534. auto CastKind = Cast->getCastKind();
  8535. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  8536. CastKind != CK_AddressSpaceConversion)
  8537. return NoParens;
  8538. auto *SubExpr = Cast->getSubExpr();
  8539. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  8540. return NoParens;
  8541. return ignorePointerCastsAndParens(SubExpr);
  8542. }
  8543. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  8544. /// record layout. e.g.
  8545. /// struct { struct { int a, b; } fst, snd; } obj;
  8546. /// obj.fst // no
  8547. /// obj.snd // yes
  8548. /// obj.fst.a // no
  8549. /// obj.fst.b // no
  8550. /// obj.snd.a // no
  8551. /// obj.snd.b // yes
  8552. ///
  8553. /// Please note: this function is specialized for how __builtin_object_size
  8554. /// views "objects".
  8555. ///
  8556. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  8557. /// correct result, it will always return true.
  8558. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  8559. assert(!LVal.Designator.Invalid);
  8560. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  8561. const RecordDecl *Parent = FD->getParent();
  8562. Invalid = Parent->isInvalidDecl();
  8563. if (Invalid || Parent->isUnion())
  8564. return true;
  8565. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  8566. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  8567. };
  8568. auto &Base = LVal.getLValueBase();
  8569. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  8570. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  8571. bool Invalid;
  8572. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8573. return Invalid;
  8574. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  8575. for (auto *FD : IFD->chain()) {
  8576. bool Invalid;
  8577. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  8578. return Invalid;
  8579. }
  8580. }
  8581. }
  8582. unsigned I = 0;
  8583. QualType BaseType = getType(Base);
  8584. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  8585. // If we don't know the array bound, conservatively assume we're looking at
  8586. // the final array element.
  8587. ++I;
  8588. if (BaseType->isIncompleteArrayType())
  8589. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  8590. else
  8591. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  8592. }
  8593. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  8594. const auto &Entry = LVal.Designator.Entries[I];
  8595. if (BaseType->isArrayType()) {
  8596. // Because __builtin_object_size treats arrays as objects, we can ignore
  8597. // the index iff this is the last array in the Designator.
  8598. if (I + 1 == E)
  8599. return true;
  8600. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  8601. uint64_t Index = Entry.getAsArrayIndex();
  8602. if (Index + 1 != CAT->getSize())
  8603. return false;
  8604. BaseType = CAT->getElementType();
  8605. } else if (BaseType->isAnyComplexType()) {
  8606. const auto *CT = BaseType->castAs<ComplexType>();
  8607. uint64_t Index = Entry.getAsArrayIndex();
  8608. if (Index != 1)
  8609. return false;
  8610. BaseType = CT->getElementType();
  8611. } else if (auto *FD = getAsField(Entry)) {
  8612. bool Invalid;
  8613. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8614. return Invalid;
  8615. BaseType = FD->getType();
  8616. } else {
  8617. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  8618. return false;
  8619. }
  8620. }
  8621. return true;
  8622. }
  8623. /// Tests to see if the LValue has a user-specified designator (that isn't
  8624. /// necessarily valid). Note that this always returns 'true' if the LValue has
  8625. /// an unsized array as its first designator entry, because there's currently no
  8626. /// way to tell if the user typed *foo or foo[0].
  8627. static bool refersToCompleteObject(const LValue &LVal) {
  8628. if (LVal.Designator.Invalid)
  8629. return false;
  8630. if (!LVal.Designator.Entries.empty())
  8631. return LVal.Designator.isMostDerivedAnUnsizedArray();
  8632. if (!LVal.InvalidBase)
  8633. return true;
  8634. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  8635. // the LValueBase.
  8636. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  8637. return !E || !isa<MemberExpr>(E);
  8638. }
  8639. /// Attempts to detect a user writing into a piece of memory that's impossible
  8640. /// to figure out the size of by just using types.
  8641. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  8642. const SubobjectDesignator &Designator = LVal.Designator;
  8643. // Notes:
  8644. // - Users can only write off of the end when we have an invalid base. Invalid
  8645. // bases imply we don't know where the memory came from.
  8646. // - We used to be a bit more aggressive here; we'd only be conservative if
  8647. // the array at the end was flexible, or if it had 0 or 1 elements. This
  8648. // broke some common standard library extensions (PR30346), but was
  8649. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  8650. // with some sort of whitelist. OTOH, it seems that GCC is always
  8651. // conservative with the last element in structs (if it's an array), so our
  8652. // current behavior is more compatible than a whitelisting approach would
  8653. // be.
  8654. return LVal.InvalidBase &&
  8655. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  8656. Designator.MostDerivedIsArrayElement &&
  8657. isDesignatorAtObjectEnd(Ctx, LVal);
  8658. }
  8659. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  8660. /// Fails if the conversion would cause loss of precision.
  8661. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  8662. CharUnits &Result) {
  8663. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  8664. if (Int.ugt(CharUnitsMax))
  8665. return false;
  8666. Result = CharUnits::fromQuantity(Int.getZExtValue());
  8667. return true;
  8668. }
  8669. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  8670. /// determine how many bytes exist from the beginning of the object to either
  8671. /// the end of the current subobject, or the end of the object itself, depending
  8672. /// on what the LValue looks like + the value of Type.
  8673. ///
  8674. /// If this returns false, the value of Result is undefined.
  8675. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  8676. unsigned Type, const LValue &LVal,
  8677. CharUnits &EndOffset) {
  8678. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  8679. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  8680. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  8681. return false;
  8682. return HandleSizeof(Info, ExprLoc, Ty, Result);
  8683. };
  8684. // We want to evaluate the size of the entire object. This is a valid fallback
  8685. // for when Type=1 and the designator is invalid, because we're asked for an
  8686. // upper-bound.
  8687. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  8688. // Type=3 wants a lower bound, so we can't fall back to this.
  8689. if (Type == 3 && !DetermineForCompleteObject)
  8690. return false;
  8691. llvm::APInt APEndOffset;
  8692. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8693. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8694. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8695. if (LVal.InvalidBase)
  8696. return false;
  8697. QualType BaseTy = getObjectType(LVal.getLValueBase());
  8698. return CheckedHandleSizeof(BaseTy, EndOffset);
  8699. }
  8700. // We want to evaluate the size of a subobject.
  8701. const SubobjectDesignator &Designator = LVal.Designator;
  8702. // The following is a moderately common idiom in C:
  8703. //
  8704. // struct Foo { int a; char c[1]; };
  8705. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  8706. // strcpy(&F->c[0], Bar);
  8707. //
  8708. // In order to not break too much legacy code, we need to support it.
  8709. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  8710. // If we can resolve this to an alloc_size call, we can hand that back,
  8711. // because we know for certain how many bytes there are to write to.
  8712. llvm::APInt APEndOffset;
  8713. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8714. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8715. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8716. // If we cannot determine the size of the initial allocation, then we can't
  8717. // given an accurate upper-bound. However, we are still able to give
  8718. // conservative lower-bounds for Type=3.
  8719. if (Type == 1)
  8720. return false;
  8721. }
  8722. CharUnits BytesPerElem;
  8723. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  8724. return false;
  8725. // According to the GCC documentation, we want the size of the subobject
  8726. // denoted by the pointer. But that's not quite right -- what we actually
  8727. // want is the size of the immediately-enclosing array, if there is one.
  8728. int64_t ElemsRemaining;
  8729. if (Designator.MostDerivedIsArrayElement &&
  8730. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  8731. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  8732. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  8733. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  8734. } else {
  8735. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  8736. }
  8737. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  8738. return true;
  8739. }
  8740. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  8741. /// returns true and stores the result in @p Size.
  8742. ///
  8743. /// If @p WasError is non-null, this will report whether the failure to evaluate
  8744. /// is to be treated as an Error in IntExprEvaluator.
  8745. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  8746. EvalInfo &Info, uint64_t &Size) {
  8747. // Determine the denoted object.
  8748. LValue LVal;
  8749. {
  8750. // The operand of __builtin_object_size is never evaluated for side-effects.
  8751. // If there are any, but we can determine the pointed-to object anyway, then
  8752. // ignore the side-effects.
  8753. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8754. IgnoreSideEffectsRAII Fold(Info);
  8755. if (E->isGLValue()) {
  8756. // It's possible for us to be given GLValues if we're called via
  8757. // Expr::tryEvaluateObjectSize.
  8758. APValue RVal;
  8759. if (!EvaluateAsRValue(Info, E, RVal))
  8760. return false;
  8761. LVal.setFrom(Info.Ctx, RVal);
  8762. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  8763. /*InvalidBaseOK=*/true))
  8764. return false;
  8765. }
  8766. // If we point to before the start of the object, there are no accessible
  8767. // bytes.
  8768. if (LVal.getLValueOffset().isNegative()) {
  8769. Size = 0;
  8770. return true;
  8771. }
  8772. CharUnits EndOffset;
  8773. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  8774. return false;
  8775. // If we've fallen outside of the end offset, just pretend there's nothing to
  8776. // write to/read from.
  8777. if (EndOffset <= LVal.getLValueOffset())
  8778. Size = 0;
  8779. else
  8780. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  8781. return true;
  8782. }
  8783. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  8784. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  8785. if (E->getResultAPValueKind() != APValue::None)
  8786. return Success(E->getAPValueResult(), E);
  8787. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  8788. }
  8789. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8790. if (unsigned BuiltinOp = E->getBuiltinCallee())
  8791. return VisitBuiltinCallExpr(E, BuiltinOp);
  8792. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8793. }
  8794. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  8795. unsigned BuiltinOp) {
  8796. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  8797. default:
  8798. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8799. case Builtin::BI__builtin_dynamic_object_size:
  8800. case Builtin::BI__builtin_object_size: {
  8801. // The type was checked when we built the expression.
  8802. unsigned Type =
  8803. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8804. assert(Type <= 3 && "unexpected type");
  8805. uint64_t Size;
  8806. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  8807. return Success(Size, E);
  8808. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  8809. return Success((Type & 2) ? 0 : -1, E);
  8810. // Expression had no side effects, but we couldn't statically determine the
  8811. // size of the referenced object.
  8812. switch (Info.EvalMode) {
  8813. case EvalInfo::EM_ConstantExpression:
  8814. case EvalInfo::EM_ConstantFold:
  8815. case EvalInfo::EM_IgnoreSideEffects:
  8816. // Leave it to IR generation.
  8817. return Error(E);
  8818. case EvalInfo::EM_ConstantExpressionUnevaluated:
  8819. // Reduce it to a constant now.
  8820. return Success((Type & 2) ? 0 : -1, E);
  8821. }
  8822. llvm_unreachable("unexpected EvalMode");
  8823. }
  8824. case Builtin::BI__builtin_os_log_format_buffer_size: {
  8825. analyze_os_log::OSLogBufferLayout Layout;
  8826. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  8827. return Success(Layout.size().getQuantity(), E);
  8828. }
  8829. case Builtin::BI__builtin_bswap16:
  8830. case Builtin::BI__builtin_bswap32:
  8831. case Builtin::BI__builtin_bswap64: {
  8832. APSInt Val;
  8833. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8834. return false;
  8835. return Success(Val.byteSwap(), E);
  8836. }
  8837. case Builtin::BI__builtin_classify_type:
  8838. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  8839. case Builtin::BI__builtin_clrsb:
  8840. case Builtin::BI__builtin_clrsbl:
  8841. case Builtin::BI__builtin_clrsbll: {
  8842. APSInt Val;
  8843. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8844. return false;
  8845. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  8846. }
  8847. case Builtin::BI__builtin_clz:
  8848. case Builtin::BI__builtin_clzl:
  8849. case Builtin::BI__builtin_clzll:
  8850. case Builtin::BI__builtin_clzs: {
  8851. APSInt Val;
  8852. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8853. return false;
  8854. if (!Val)
  8855. return Error(E);
  8856. return Success(Val.countLeadingZeros(), E);
  8857. }
  8858. case Builtin::BI__builtin_constant_p: {
  8859. const Expr *Arg = E->getArg(0);
  8860. if (EvaluateBuiltinConstantP(Info, Arg))
  8861. return Success(true, E);
  8862. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  8863. // Outside a constant context, eagerly evaluate to false in the presence
  8864. // of side-effects in order to avoid -Wunsequenced false-positives in
  8865. // a branch on __builtin_constant_p(expr).
  8866. return Success(false, E);
  8867. }
  8868. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8869. return false;
  8870. }
  8871. case Builtin::BI__builtin_is_constant_evaluated:
  8872. return Success(Info.InConstantContext, E);
  8873. case Builtin::BI__builtin_ctz:
  8874. case Builtin::BI__builtin_ctzl:
  8875. case Builtin::BI__builtin_ctzll:
  8876. case Builtin::BI__builtin_ctzs: {
  8877. APSInt Val;
  8878. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8879. return false;
  8880. if (!Val)
  8881. return Error(E);
  8882. return Success(Val.countTrailingZeros(), E);
  8883. }
  8884. case Builtin::BI__builtin_eh_return_data_regno: {
  8885. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8886. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  8887. return Success(Operand, E);
  8888. }
  8889. case Builtin::BI__builtin_expect:
  8890. return Visit(E->getArg(0));
  8891. case Builtin::BI__builtin_ffs:
  8892. case Builtin::BI__builtin_ffsl:
  8893. case Builtin::BI__builtin_ffsll: {
  8894. APSInt Val;
  8895. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8896. return false;
  8897. unsigned N = Val.countTrailingZeros();
  8898. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  8899. }
  8900. case Builtin::BI__builtin_fpclassify: {
  8901. APFloat Val(0.0);
  8902. if (!EvaluateFloat(E->getArg(5), Val, Info))
  8903. return false;
  8904. unsigned Arg;
  8905. switch (Val.getCategory()) {
  8906. case APFloat::fcNaN: Arg = 0; break;
  8907. case APFloat::fcInfinity: Arg = 1; break;
  8908. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  8909. case APFloat::fcZero: Arg = 4; break;
  8910. }
  8911. return Visit(E->getArg(Arg));
  8912. }
  8913. case Builtin::BI__builtin_isinf_sign: {
  8914. APFloat Val(0.0);
  8915. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8916. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  8917. }
  8918. case Builtin::BI__builtin_isinf: {
  8919. APFloat Val(0.0);
  8920. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8921. Success(Val.isInfinity() ? 1 : 0, E);
  8922. }
  8923. case Builtin::BI__builtin_isfinite: {
  8924. APFloat Val(0.0);
  8925. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8926. Success(Val.isFinite() ? 1 : 0, E);
  8927. }
  8928. case Builtin::BI__builtin_isnan: {
  8929. APFloat Val(0.0);
  8930. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8931. Success(Val.isNaN() ? 1 : 0, E);
  8932. }
  8933. case Builtin::BI__builtin_isnormal: {
  8934. APFloat Val(0.0);
  8935. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8936. Success(Val.isNormal() ? 1 : 0, E);
  8937. }
  8938. case Builtin::BI__builtin_parity:
  8939. case Builtin::BI__builtin_parityl:
  8940. case Builtin::BI__builtin_parityll: {
  8941. APSInt Val;
  8942. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8943. return false;
  8944. return Success(Val.countPopulation() % 2, E);
  8945. }
  8946. case Builtin::BI__builtin_popcount:
  8947. case Builtin::BI__builtin_popcountl:
  8948. case Builtin::BI__builtin_popcountll: {
  8949. APSInt Val;
  8950. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8951. return false;
  8952. return Success(Val.countPopulation(), E);
  8953. }
  8954. case Builtin::BIstrlen:
  8955. case Builtin::BIwcslen:
  8956. // A call to strlen is not a constant expression.
  8957. if (Info.getLangOpts().CPlusPlus11)
  8958. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8959. << /*isConstexpr*/0 << /*isConstructor*/0
  8960. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8961. else
  8962. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8963. LLVM_FALLTHROUGH;
  8964. case Builtin::BI__builtin_strlen:
  8965. case Builtin::BI__builtin_wcslen: {
  8966. // As an extension, we support __builtin_strlen() as a constant expression,
  8967. // and support folding strlen() to a constant.
  8968. LValue String;
  8969. if (!EvaluatePointer(E->getArg(0), String, Info))
  8970. return false;
  8971. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  8972. // Fast path: if it's a string literal, search the string value.
  8973. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  8974. String.getLValueBase().dyn_cast<const Expr *>())) {
  8975. // The string literal may have embedded null characters. Find the first
  8976. // one and truncate there.
  8977. StringRef Str = S->getBytes();
  8978. int64_t Off = String.Offset.getQuantity();
  8979. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  8980. S->getCharByteWidth() == 1 &&
  8981. // FIXME: Add fast-path for wchar_t too.
  8982. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  8983. Str = Str.substr(Off);
  8984. StringRef::size_type Pos = Str.find(0);
  8985. if (Pos != StringRef::npos)
  8986. Str = Str.substr(0, Pos);
  8987. return Success(Str.size(), E);
  8988. }
  8989. // Fall through to slow path to issue appropriate diagnostic.
  8990. }
  8991. // Slow path: scan the bytes of the string looking for the terminating 0.
  8992. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  8993. APValue Char;
  8994. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  8995. !Char.isInt())
  8996. return false;
  8997. if (!Char.getInt())
  8998. return Success(Strlen, E);
  8999. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  9000. return false;
  9001. }
  9002. }
  9003. case Builtin::BIstrcmp:
  9004. case Builtin::BIwcscmp:
  9005. case Builtin::BIstrncmp:
  9006. case Builtin::BIwcsncmp:
  9007. case Builtin::BImemcmp:
  9008. case Builtin::BIbcmp:
  9009. case Builtin::BIwmemcmp:
  9010. // A call to strlen is not a constant expression.
  9011. if (Info.getLangOpts().CPlusPlus11)
  9012. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9013. << /*isConstexpr*/0 << /*isConstructor*/0
  9014. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9015. else
  9016. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9017. LLVM_FALLTHROUGH;
  9018. case Builtin::BI__builtin_strcmp:
  9019. case Builtin::BI__builtin_wcscmp:
  9020. case Builtin::BI__builtin_strncmp:
  9021. case Builtin::BI__builtin_wcsncmp:
  9022. case Builtin::BI__builtin_memcmp:
  9023. case Builtin::BI__builtin_bcmp:
  9024. case Builtin::BI__builtin_wmemcmp: {
  9025. LValue String1, String2;
  9026. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  9027. !EvaluatePointer(E->getArg(1), String2, Info))
  9028. return false;
  9029. uint64_t MaxLength = uint64_t(-1);
  9030. if (BuiltinOp != Builtin::BIstrcmp &&
  9031. BuiltinOp != Builtin::BIwcscmp &&
  9032. BuiltinOp != Builtin::BI__builtin_strcmp &&
  9033. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  9034. APSInt N;
  9035. if (!EvaluateInteger(E->getArg(2), N, Info))
  9036. return false;
  9037. MaxLength = N.getExtValue();
  9038. }
  9039. // Empty substrings compare equal by definition.
  9040. if (MaxLength == 0u)
  9041. return Success(0, E);
  9042. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9043. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9044. String1.Designator.Invalid || String2.Designator.Invalid)
  9045. return false;
  9046. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  9047. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  9048. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  9049. BuiltinOp == Builtin::BIbcmp ||
  9050. BuiltinOp == Builtin::BI__builtin_memcmp ||
  9051. BuiltinOp == Builtin::BI__builtin_bcmp;
  9052. assert(IsRawByte ||
  9053. (Info.Ctx.hasSameUnqualifiedType(
  9054. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  9055. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  9056. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  9057. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  9058. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  9059. Char1.isInt() && Char2.isInt();
  9060. };
  9061. const auto &AdvanceElems = [&] {
  9062. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  9063. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  9064. };
  9065. if (IsRawByte) {
  9066. uint64_t BytesRemaining = MaxLength;
  9067. // Pointers to const void may point to objects of incomplete type.
  9068. if (CharTy1->isIncompleteType()) {
  9069. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  9070. return false;
  9071. }
  9072. if (CharTy2->isIncompleteType()) {
  9073. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  9074. return false;
  9075. }
  9076. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  9077. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  9078. // Give up on comparing between elements with disparate widths.
  9079. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  9080. return false;
  9081. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  9082. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  9083. "following loop considers at least one element");
  9084. while (true) {
  9085. APValue Char1, Char2;
  9086. if (!ReadCurElems(Char1, Char2))
  9087. return false;
  9088. // We have compatible in-memory widths, but a possible type and
  9089. // (for `bool`) internal representation mismatch.
  9090. // Assuming two's complement representation, including 0 for `false` and
  9091. // 1 for `true`, we can check an appropriate number of elements for
  9092. // equality even if they are not byte-sized.
  9093. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  9094. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  9095. if (Char1InMem.ne(Char2InMem)) {
  9096. // If the elements are byte-sized, then we can produce a three-way
  9097. // comparison result in a straightforward manner.
  9098. if (BytesPerElement == 1u) {
  9099. // memcmp always compares unsigned chars.
  9100. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  9101. }
  9102. // The result is byte-order sensitive, and we have multibyte elements.
  9103. // FIXME: We can compare the remaining bytes in the correct order.
  9104. return false;
  9105. }
  9106. if (!AdvanceElems())
  9107. return false;
  9108. if (BytesRemaining <= BytesPerElement)
  9109. break;
  9110. BytesRemaining -= BytesPerElement;
  9111. }
  9112. // Enough elements are equal to account for the memcmp limit.
  9113. return Success(0, E);
  9114. }
  9115. bool StopAtNull =
  9116. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  9117. BuiltinOp != Builtin::BIwmemcmp &&
  9118. BuiltinOp != Builtin::BI__builtin_memcmp &&
  9119. BuiltinOp != Builtin::BI__builtin_bcmp &&
  9120. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  9121. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  9122. BuiltinOp == Builtin::BIwcsncmp ||
  9123. BuiltinOp == Builtin::BIwmemcmp ||
  9124. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  9125. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  9126. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  9127. for (; MaxLength; --MaxLength) {
  9128. APValue Char1, Char2;
  9129. if (!ReadCurElems(Char1, Char2))
  9130. return false;
  9131. if (Char1.getInt() != Char2.getInt()) {
  9132. if (IsWide) // wmemcmp compares with wchar_t signedness.
  9133. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  9134. // memcmp always compares unsigned chars.
  9135. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  9136. }
  9137. if (StopAtNull && !Char1.getInt())
  9138. return Success(0, E);
  9139. assert(!(StopAtNull && !Char2.getInt()));
  9140. if (!AdvanceElems())
  9141. return false;
  9142. }
  9143. // We hit the strncmp / memcmp limit.
  9144. return Success(0, E);
  9145. }
  9146. case Builtin::BI__atomic_always_lock_free:
  9147. case Builtin::BI__atomic_is_lock_free:
  9148. case Builtin::BI__c11_atomic_is_lock_free: {
  9149. APSInt SizeVal;
  9150. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  9151. return false;
  9152. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  9153. // of two less than the maximum inline atomic width, we know it is
  9154. // lock-free. If the size isn't a power of two, or greater than the
  9155. // maximum alignment where we promote atomics, we know it is not lock-free
  9156. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  9157. // the answer can only be determined at runtime; for example, 16-byte
  9158. // atomics have lock-free implementations on some, but not all,
  9159. // x86-64 processors.
  9160. // Check power-of-two.
  9161. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  9162. if (Size.isPowerOfTwo()) {
  9163. // Check against inlining width.
  9164. unsigned InlineWidthBits =
  9165. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  9166. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  9167. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  9168. Size == CharUnits::One() ||
  9169. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  9170. Expr::NPC_NeverValueDependent))
  9171. // OK, we will inline appropriately-aligned operations of this size,
  9172. // and _Atomic(T) is appropriately-aligned.
  9173. return Success(1, E);
  9174. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  9175. castAs<PointerType>()->getPointeeType();
  9176. if (!PointeeType->isIncompleteType() &&
  9177. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  9178. // OK, we will inline operations on this object.
  9179. return Success(1, E);
  9180. }
  9181. }
  9182. }
  9183. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  9184. Success(0, E) : Error(E);
  9185. }
  9186. case Builtin::BIomp_is_initial_device:
  9187. // We can decide statically which value the runtime would return if called.
  9188. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  9189. case Builtin::BI__builtin_add_overflow:
  9190. case Builtin::BI__builtin_sub_overflow:
  9191. case Builtin::BI__builtin_mul_overflow:
  9192. case Builtin::BI__builtin_sadd_overflow:
  9193. case Builtin::BI__builtin_uadd_overflow:
  9194. case Builtin::BI__builtin_uaddl_overflow:
  9195. case Builtin::BI__builtin_uaddll_overflow:
  9196. case Builtin::BI__builtin_usub_overflow:
  9197. case Builtin::BI__builtin_usubl_overflow:
  9198. case Builtin::BI__builtin_usubll_overflow:
  9199. case Builtin::BI__builtin_umul_overflow:
  9200. case Builtin::BI__builtin_umull_overflow:
  9201. case Builtin::BI__builtin_umulll_overflow:
  9202. case Builtin::BI__builtin_saddl_overflow:
  9203. case Builtin::BI__builtin_saddll_overflow:
  9204. case Builtin::BI__builtin_ssub_overflow:
  9205. case Builtin::BI__builtin_ssubl_overflow:
  9206. case Builtin::BI__builtin_ssubll_overflow:
  9207. case Builtin::BI__builtin_smul_overflow:
  9208. case Builtin::BI__builtin_smull_overflow:
  9209. case Builtin::BI__builtin_smulll_overflow: {
  9210. LValue ResultLValue;
  9211. APSInt LHS, RHS;
  9212. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  9213. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  9214. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  9215. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  9216. return false;
  9217. APSInt Result;
  9218. bool DidOverflow = false;
  9219. // If the types don't have to match, enlarge all 3 to the largest of them.
  9220. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9221. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9222. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9223. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  9224. ResultType->isSignedIntegerOrEnumerationType();
  9225. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  9226. ResultType->isSignedIntegerOrEnumerationType();
  9227. uint64_t LHSSize = LHS.getBitWidth();
  9228. uint64_t RHSSize = RHS.getBitWidth();
  9229. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  9230. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  9231. // Add an additional bit if the signedness isn't uniformly agreed to. We
  9232. // could do this ONLY if there is a signed and an unsigned that both have
  9233. // MaxBits, but the code to check that is pretty nasty. The issue will be
  9234. // caught in the shrink-to-result later anyway.
  9235. if (IsSigned && !AllSigned)
  9236. ++MaxBits;
  9237. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  9238. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  9239. Result = APSInt(MaxBits, !IsSigned);
  9240. }
  9241. // Find largest int.
  9242. switch (BuiltinOp) {
  9243. default:
  9244. llvm_unreachable("Invalid value for BuiltinOp");
  9245. case Builtin::BI__builtin_add_overflow:
  9246. case Builtin::BI__builtin_sadd_overflow:
  9247. case Builtin::BI__builtin_saddl_overflow:
  9248. case Builtin::BI__builtin_saddll_overflow:
  9249. case Builtin::BI__builtin_uadd_overflow:
  9250. case Builtin::BI__builtin_uaddl_overflow:
  9251. case Builtin::BI__builtin_uaddll_overflow:
  9252. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  9253. : LHS.uadd_ov(RHS, DidOverflow);
  9254. break;
  9255. case Builtin::BI__builtin_sub_overflow:
  9256. case Builtin::BI__builtin_ssub_overflow:
  9257. case Builtin::BI__builtin_ssubl_overflow:
  9258. case Builtin::BI__builtin_ssubll_overflow:
  9259. case Builtin::BI__builtin_usub_overflow:
  9260. case Builtin::BI__builtin_usubl_overflow:
  9261. case Builtin::BI__builtin_usubll_overflow:
  9262. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  9263. : LHS.usub_ov(RHS, DidOverflow);
  9264. break;
  9265. case Builtin::BI__builtin_mul_overflow:
  9266. case Builtin::BI__builtin_smul_overflow:
  9267. case Builtin::BI__builtin_smull_overflow:
  9268. case Builtin::BI__builtin_smulll_overflow:
  9269. case Builtin::BI__builtin_umul_overflow:
  9270. case Builtin::BI__builtin_umull_overflow:
  9271. case Builtin::BI__builtin_umulll_overflow:
  9272. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  9273. : LHS.umul_ov(RHS, DidOverflow);
  9274. break;
  9275. }
  9276. // In the case where multiple sizes are allowed, truncate and see if
  9277. // the values are the same.
  9278. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9279. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9280. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9281. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  9282. // since it will give us the behavior of a TruncOrSelf in the case where
  9283. // its parameter <= its size. We previously set Result to be at least the
  9284. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  9285. // will work exactly like TruncOrSelf.
  9286. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  9287. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  9288. if (!APSInt::isSameValue(Temp, Result))
  9289. DidOverflow = true;
  9290. Result = Temp;
  9291. }
  9292. APValue APV{Result};
  9293. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  9294. return false;
  9295. return Success(DidOverflow, E);
  9296. }
  9297. }
  9298. }
  9299. /// Determine whether this is a pointer past the end of the complete
  9300. /// object referred to by the lvalue.
  9301. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  9302. const LValue &LV) {
  9303. // A null pointer can be viewed as being "past the end" but we don't
  9304. // choose to look at it that way here.
  9305. if (!LV.getLValueBase())
  9306. return false;
  9307. // If the designator is valid and refers to a subobject, we're not pointing
  9308. // past the end.
  9309. if (!LV.getLValueDesignator().Invalid &&
  9310. !LV.getLValueDesignator().isOnePastTheEnd())
  9311. return false;
  9312. // A pointer to an incomplete type might be past-the-end if the type's size is
  9313. // zero. We cannot tell because the type is incomplete.
  9314. QualType Ty = getType(LV.getLValueBase());
  9315. if (Ty->isIncompleteType())
  9316. return true;
  9317. // We're a past-the-end pointer if we point to the byte after the object,
  9318. // no matter what our type or path is.
  9319. auto Size = Ctx.getTypeSizeInChars(Ty);
  9320. return LV.getLValueOffset() == Size;
  9321. }
  9322. namespace {
  9323. /// Data recursive integer evaluator of certain binary operators.
  9324. ///
  9325. /// We use a data recursive algorithm for binary operators so that we are able
  9326. /// to handle extreme cases of chained binary operators without causing stack
  9327. /// overflow.
  9328. class DataRecursiveIntBinOpEvaluator {
  9329. struct EvalResult {
  9330. APValue Val;
  9331. bool Failed;
  9332. EvalResult() : Failed(false) { }
  9333. void swap(EvalResult &RHS) {
  9334. Val.swap(RHS.Val);
  9335. Failed = RHS.Failed;
  9336. RHS.Failed = false;
  9337. }
  9338. };
  9339. struct Job {
  9340. const Expr *E;
  9341. EvalResult LHSResult; // meaningful only for binary operator expression.
  9342. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  9343. Job() = default;
  9344. Job(Job &&) = default;
  9345. void startSpeculativeEval(EvalInfo &Info) {
  9346. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  9347. }
  9348. private:
  9349. SpeculativeEvaluationRAII SpecEvalRAII;
  9350. };
  9351. SmallVector<Job, 16> Queue;
  9352. IntExprEvaluator &IntEval;
  9353. EvalInfo &Info;
  9354. APValue &FinalResult;
  9355. public:
  9356. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  9357. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  9358. /// True if \param E is a binary operator that we are going to handle
  9359. /// data recursively.
  9360. /// We handle binary operators that are comma, logical, or that have operands
  9361. /// with integral or enumeration type.
  9362. static bool shouldEnqueue(const BinaryOperator *E) {
  9363. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  9364. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  9365. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9366. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9367. }
  9368. bool Traverse(const BinaryOperator *E) {
  9369. enqueue(E);
  9370. EvalResult PrevResult;
  9371. while (!Queue.empty())
  9372. process(PrevResult);
  9373. if (PrevResult.Failed) return false;
  9374. FinalResult.swap(PrevResult.Val);
  9375. return true;
  9376. }
  9377. private:
  9378. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9379. return IntEval.Success(Value, E, Result);
  9380. }
  9381. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  9382. return IntEval.Success(Value, E, Result);
  9383. }
  9384. bool Error(const Expr *E) {
  9385. return IntEval.Error(E);
  9386. }
  9387. bool Error(const Expr *E, diag::kind D) {
  9388. return IntEval.Error(E, D);
  9389. }
  9390. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  9391. return Info.CCEDiag(E, D);
  9392. }
  9393. // Returns true if visiting the RHS is necessary, false otherwise.
  9394. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9395. bool &SuppressRHSDiags);
  9396. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9397. const BinaryOperator *E, APValue &Result);
  9398. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  9399. Result.Failed = !Evaluate(Result.Val, Info, E);
  9400. if (Result.Failed)
  9401. Result.Val = APValue();
  9402. }
  9403. void process(EvalResult &Result);
  9404. void enqueue(const Expr *E) {
  9405. E = E->IgnoreParens();
  9406. Queue.resize(Queue.size()+1);
  9407. Queue.back().E = E;
  9408. Queue.back().Kind = Job::AnyExprKind;
  9409. }
  9410. };
  9411. }
  9412. bool DataRecursiveIntBinOpEvaluator::
  9413. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9414. bool &SuppressRHSDiags) {
  9415. if (E->getOpcode() == BO_Comma) {
  9416. // Ignore LHS but note if we could not evaluate it.
  9417. if (LHSResult.Failed)
  9418. return Info.noteSideEffect();
  9419. return true;
  9420. }
  9421. if (E->isLogicalOp()) {
  9422. bool LHSAsBool;
  9423. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  9424. // We were able to evaluate the LHS, see if we can get away with not
  9425. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  9426. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  9427. Success(LHSAsBool, E, LHSResult.Val);
  9428. return false; // Ignore RHS
  9429. }
  9430. } else {
  9431. LHSResult.Failed = true;
  9432. // Since we weren't able to evaluate the left hand side, it
  9433. // might have had side effects.
  9434. if (!Info.noteSideEffect())
  9435. return false;
  9436. // We can't evaluate the LHS; however, sometimes the result
  9437. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9438. // Don't ignore RHS and suppress diagnostics from this arm.
  9439. SuppressRHSDiags = true;
  9440. }
  9441. return true;
  9442. }
  9443. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9444. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9445. if (LHSResult.Failed && !Info.noteFailure())
  9446. return false; // Ignore RHS;
  9447. return true;
  9448. }
  9449. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  9450. bool IsSub) {
  9451. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  9452. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  9453. // offsets.
  9454. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  9455. CharUnits &Offset = LVal.getLValueOffset();
  9456. uint64_t Offset64 = Offset.getQuantity();
  9457. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  9458. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  9459. : Offset64 + Index64);
  9460. }
  9461. bool DataRecursiveIntBinOpEvaluator::
  9462. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9463. const BinaryOperator *E, APValue &Result) {
  9464. if (E->getOpcode() == BO_Comma) {
  9465. if (RHSResult.Failed)
  9466. return false;
  9467. Result = RHSResult.Val;
  9468. return true;
  9469. }
  9470. if (E->isLogicalOp()) {
  9471. bool lhsResult, rhsResult;
  9472. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  9473. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  9474. if (LHSIsOK) {
  9475. if (RHSIsOK) {
  9476. if (E->getOpcode() == BO_LOr)
  9477. return Success(lhsResult || rhsResult, E, Result);
  9478. else
  9479. return Success(lhsResult && rhsResult, E, Result);
  9480. }
  9481. } else {
  9482. if (RHSIsOK) {
  9483. // We can't evaluate the LHS; however, sometimes the result
  9484. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9485. if (rhsResult == (E->getOpcode() == BO_LOr))
  9486. return Success(rhsResult, E, Result);
  9487. }
  9488. }
  9489. return false;
  9490. }
  9491. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9492. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9493. if (LHSResult.Failed || RHSResult.Failed)
  9494. return false;
  9495. const APValue &LHSVal = LHSResult.Val;
  9496. const APValue &RHSVal = RHSResult.Val;
  9497. // Handle cases like (unsigned long)&a + 4.
  9498. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  9499. Result = LHSVal;
  9500. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  9501. return true;
  9502. }
  9503. // Handle cases like 4 + (unsigned long)&a
  9504. if (E->getOpcode() == BO_Add &&
  9505. RHSVal.isLValue() && LHSVal.isInt()) {
  9506. Result = RHSVal;
  9507. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  9508. return true;
  9509. }
  9510. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  9511. // Handle (intptr_t)&&A - (intptr_t)&&B.
  9512. if (!LHSVal.getLValueOffset().isZero() ||
  9513. !RHSVal.getLValueOffset().isZero())
  9514. return false;
  9515. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  9516. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  9517. if (!LHSExpr || !RHSExpr)
  9518. return false;
  9519. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9520. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9521. if (!LHSAddrExpr || !RHSAddrExpr)
  9522. return false;
  9523. // Make sure both labels come from the same function.
  9524. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9525. RHSAddrExpr->getLabel()->getDeclContext())
  9526. return false;
  9527. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  9528. return true;
  9529. }
  9530. // All the remaining cases expect both operands to be an integer
  9531. if (!LHSVal.isInt() || !RHSVal.isInt())
  9532. return Error(E);
  9533. // Set up the width and signedness manually, in case it can't be deduced
  9534. // from the operation we're performing.
  9535. // FIXME: Don't do this in the cases where we can deduce it.
  9536. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  9537. E->getType()->isUnsignedIntegerOrEnumerationType());
  9538. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  9539. RHSVal.getInt(), Value))
  9540. return false;
  9541. return Success(Value, E, Result);
  9542. }
  9543. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  9544. Job &job = Queue.back();
  9545. switch (job.Kind) {
  9546. case Job::AnyExprKind: {
  9547. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  9548. if (shouldEnqueue(Bop)) {
  9549. job.Kind = Job::BinOpKind;
  9550. enqueue(Bop->getLHS());
  9551. return;
  9552. }
  9553. }
  9554. EvaluateExpr(job.E, Result);
  9555. Queue.pop_back();
  9556. return;
  9557. }
  9558. case Job::BinOpKind: {
  9559. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9560. bool SuppressRHSDiags = false;
  9561. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  9562. Queue.pop_back();
  9563. return;
  9564. }
  9565. if (SuppressRHSDiags)
  9566. job.startSpeculativeEval(Info);
  9567. job.LHSResult.swap(Result);
  9568. job.Kind = Job::BinOpVisitedLHSKind;
  9569. enqueue(Bop->getRHS());
  9570. return;
  9571. }
  9572. case Job::BinOpVisitedLHSKind: {
  9573. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9574. EvalResult RHS;
  9575. RHS.swap(Result);
  9576. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  9577. Queue.pop_back();
  9578. return;
  9579. }
  9580. }
  9581. llvm_unreachable("Invalid Job::Kind!");
  9582. }
  9583. namespace {
  9584. /// Used when we determine that we should fail, but can keep evaluating prior to
  9585. /// noting that we had a failure.
  9586. class DelayedNoteFailureRAII {
  9587. EvalInfo &Info;
  9588. bool NoteFailure;
  9589. public:
  9590. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  9591. : Info(Info), NoteFailure(NoteFailure) {}
  9592. ~DelayedNoteFailureRAII() {
  9593. if (NoteFailure) {
  9594. bool ContinueAfterFailure = Info.noteFailure();
  9595. (void)ContinueAfterFailure;
  9596. assert(ContinueAfterFailure &&
  9597. "Shouldn't have kept evaluating on failure.");
  9598. }
  9599. }
  9600. };
  9601. }
  9602. template <class SuccessCB, class AfterCB>
  9603. static bool
  9604. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  9605. SuccessCB &&Success, AfterCB &&DoAfter) {
  9606. assert(E->isComparisonOp() && "expected comparison operator");
  9607. assert((E->getOpcode() == BO_Cmp ||
  9608. E->getType()->isIntegralOrEnumerationType()) &&
  9609. "unsupported binary expression evaluation");
  9610. auto Error = [&](const Expr *E) {
  9611. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9612. return false;
  9613. };
  9614. using CCR = ComparisonCategoryResult;
  9615. bool IsRelational = E->isRelationalOp();
  9616. bool IsEquality = E->isEqualityOp();
  9617. if (E->getOpcode() == BO_Cmp) {
  9618. const ComparisonCategoryInfo &CmpInfo =
  9619. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9620. IsRelational = CmpInfo.isOrdered();
  9621. IsEquality = CmpInfo.isEquality();
  9622. }
  9623. QualType LHSTy = E->getLHS()->getType();
  9624. QualType RHSTy = E->getRHS()->getType();
  9625. if (LHSTy->isIntegralOrEnumerationType() &&
  9626. RHSTy->isIntegralOrEnumerationType()) {
  9627. APSInt LHS, RHS;
  9628. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  9629. if (!LHSOK && !Info.noteFailure())
  9630. return false;
  9631. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  9632. return false;
  9633. if (LHS < RHS)
  9634. return Success(CCR::Less, E);
  9635. if (LHS > RHS)
  9636. return Success(CCR::Greater, E);
  9637. return Success(CCR::Equal, E);
  9638. }
  9639. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  9640. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  9641. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  9642. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  9643. if (!LHSOK && !Info.noteFailure())
  9644. return false;
  9645. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  9646. return false;
  9647. if (LHSFX < RHSFX)
  9648. return Success(CCR::Less, E);
  9649. if (LHSFX > RHSFX)
  9650. return Success(CCR::Greater, E);
  9651. return Success(CCR::Equal, E);
  9652. }
  9653. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  9654. ComplexValue LHS, RHS;
  9655. bool LHSOK;
  9656. if (E->isAssignmentOp()) {
  9657. LValue LV;
  9658. EvaluateLValue(E->getLHS(), LV, Info);
  9659. LHSOK = false;
  9660. } else if (LHSTy->isRealFloatingType()) {
  9661. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  9662. if (LHSOK) {
  9663. LHS.makeComplexFloat();
  9664. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  9665. }
  9666. } else {
  9667. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  9668. }
  9669. if (!LHSOK && !Info.noteFailure())
  9670. return false;
  9671. if (E->getRHS()->getType()->isRealFloatingType()) {
  9672. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  9673. return false;
  9674. RHS.makeComplexFloat();
  9675. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  9676. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9677. return false;
  9678. if (LHS.isComplexFloat()) {
  9679. APFloat::cmpResult CR_r =
  9680. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  9681. APFloat::cmpResult CR_i =
  9682. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  9683. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  9684. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9685. } else {
  9686. assert(IsEquality && "invalid complex comparison");
  9687. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  9688. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  9689. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9690. }
  9691. }
  9692. if (LHSTy->isRealFloatingType() &&
  9693. RHSTy->isRealFloatingType()) {
  9694. APFloat RHS(0.0), LHS(0.0);
  9695. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  9696. if (!LHSOK && !Info.noteFailure())
  9697. return false;
  9698. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  9699. return false;
  9700. assert(E->isComparisonOp() && "Invalid binary operator!");
  9701. auto GetCmpRes = [&]() {
  9702. switch (LHS.compare(RHS)) {
  9703. case APFloat::cmpEqual:
  9704. return CCR::Equal;
  9705. case APFloat::cmpLessThan:
  9706. return CCR::Less;
  9707. case APFloat::cmpGreaterThan:
  9708. return CCR::Greater;
  9709. case APFloat::cmpUnordered:
  9710. return CCR::Unordered;
  9711. }
  9712. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  9713. };
  9714. return Success(GetCmpRes(), E);
  9715. }
  9716. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  9717. LValue LHSValue, RHSValue;
  9718. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9719. if (!LHSOK && !Info.noteFailure())
  9720. return false;
  9721. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9722. return false;
  9723. // Reject differing bases from the normal codepath; we special-case
  9724. // comparisons to null.
  9725. if (!HasSameBase(LHSValue, RHSValue)) {
  9726. // Inequalities and subtractions between unrelated pointers have
  9727. // unspecified or undefined behavior.
  9728. if (!IsEquality)
  9729. return Error(E);
  9730. // A constant address may compare equal to the address of a symbol.
  9731. // The one exception is that address of an object cannot compare equal
  9732. // to a null pointer constant.
  9733. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  9734. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  9735. return Error(E);
  9736. // It's implementation-defined whether distinct literals will have
  9737. // distinct addresses. In clang, the result of such a comparison is
  9738. // unspecified, so it is not a constant expression. However, we do know
  9739. // that the address of a literal will be non-null.
  9740. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  9741. LHSValue.Base && RHSValue.Base)
  9742. return Error(E);
  9743. // We can't tell whether weak symbols will end up pointing to the same
  9744. // object.
  9745. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  9746. return Error(E);
  9747. // We can't compare the address of the start of one object with the
  9748. // past-the-end address of another object, per C++ DR1652.
  9749. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  9750. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  9751. (RHSValue.Base && RHSValue.Offset.isZero() &&
  9752. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  9753. return Error(E);
  9754. // We can't tell whether an object is at the same address as another
  9755. // zero sized object.
  9756. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  9757. (LHSValue.Base && isZeroSized(RHSValue)))
  9758. return Error(E);
  9759. return Success(CCR::Nonequal, E);
  9760. }
  9761. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9762. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9763. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9764. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9765. // C++11 [expr.rel]p3:
  9766. // Pointers to void (after pointer conversions) can be compared, with a
  9767. // result defined as follows: If both pointers represent the same
  9768. // address or are both the null pointer value, the result is true if the
  9769. // operator is <= or >= and false otherwise; otherwise the result is
  9770. // unspecified.
  9771. // We interpret this as applying to pointers to *cv* void.
  9772. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  9773. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  9774. // C++11 [expr.rel]p2:
  9775. // - If two pointers point to non-static data members of the same object,
  9776. // or to subobjects or array elements fo such members, recursively, the
  9777. // pointer to the later declared member compares greater provided the
  9778. // two members have the same access control and provided their class is
  9779. // not a union.
  9780. // [...]
  9781. // - Otherwise pointer comparisons are unspecified.
  9782. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  9783. bool WasArrayIndex;
  9784. unsigned Mismatch = FindDesignatorMismatch(
  9785. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  9786. // At the point where the designators diverge, the comparison has a
  9787. // specified value if:
  9788. // - we are comparing array indices
  9789. // - we are comparing fields of a union, or fields with the same access
  9790. // Otherwise, the result is unspecified and thus the comparison is not a
  9791. // constant expression.
  9792. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  9793. Mismatch < RHSDesignator.Entries.size()) {
  9794. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  9795. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  9796. if (!LF && !RF)
  9797. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  9798. else if (!LF)
  9799. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9800. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  9801. << RF->getParent() << RF;
  9802. else if (!RF)
  9803. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9804. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  9805. << LF->getParent() << LF;
  9806. else if (!LF->getParent()->isUnion() &&
  9807. LF->getAccess() != RF->getAccess())
  9808. Info.CCEDiag(E,
  9809. diag::note_constexpr_pointer_comparison_differing_access)
  9810. << LF << LF->getAccess() << RF << RF->getAccess()
  9811. << LF->getParent();
  9812. }
  9813. }
  9814. // The comparison here must be unsigned, and performed with the same
  9815. // width as the pointer.
  9816. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  9817. uint64_t CompareLHS = LHSOffset.getQuantity();
  9818. uint64_t CompareRHS = RHSOffset.getQuantity();
  9819. assert(PtrSize <= 64 && "Unexpected pointer width");
  9820. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  9821. CompareLHS &= Mask;
  9822. CompareRHS &= Mask;
  9823. // If there is a base and this is a relational operator, we can only
  9824. // compare pointers within the object in question; otherwise, the result
  9825. // depends on where the object is located in memory.
  9826. if (!LHSValue.Base.isNull() && IsRelational) {
  9827. QualType BaseTy = getType(LHSValue.Base);
  9828. if (BaseTy->isIncompleteType())
  9829. return Error(E);
  9830. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  9831. uint64_t OffsetLimit = Size.getQuantity();
  9832. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  9833. return Error(E);
  9834. }
  9835. if (CompareLHS < CompareRHS)
  9836. return Success(CCR::Less, E);
  9837. if (CompareLHS > CompareRHS)
  9838. return Success(CCR::Greater, E);
  9839. return Success(CCR::Equal, E);
  9840. }
  9841. if (LHSTy->isMemberPointerType()) {
  9842. assert(IsEquality && "unexpected member pointer operation");
  9843. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  9844. MemberPtr LHSValue, RHSValue;
  9845. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  9846. if (!LHSOK && !Info.noteFailure())
  9847. return false;
  9848. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9849. return false;
  9850. // C++11 [expr.eq]p2:
  9851. // If both operands are null, they compare equal. Otherwise if only one is
  9852. // null, they compare unequal.
  9853. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  9854. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  9855. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9856. }
  9857. // Otherwise if either is a pointer to a virtual member function, the
  9858. // result is unspecified.
  9859. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  9860. if (MD->isVirtual())
  9861. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9862. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  9863. if (MD->isVirtual())
  9864. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9865. // Otherwise they compare equal if and only if they would refer to the
  9866. // same member of the same most derived object or the same subobject if
  9867. // they were dereferenced with a hypothetical object of the associated
  9868. // class type.
  9869. bool Equal = LHSValue == RHSValue;
  9870. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9871. }
  9872. if (LHSTy->isNullPtrType()) {
  9873. assert(E->isComparisonOp() && "unexpected nullptr operation");
  9874. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  9875. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  9876. // are compared, the result is true of the operator is <=, >= or ==, and
  9877. // false otherwise.
  9878. return Success(CCR::Equal, E);
  9879. }
  9880. return DoAfter();
  9881. }
  9882. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  9883. if (!CheckLiteralType(Info, E))
  9884. return false;
  9885. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9886. const BinaryOperator *E) {
  9887. // Evaluation succeeded. Lookup the information for the comparison category
  9888. // type and fetch the VarDecl for the result.
  9889. const ComparisonCategoryInfo &CmpInfo =
  9890. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9891. const VarDecl *VD =
  9892. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  9893. // Check and evaluate the result as a constant expression.
  9894. LValue LV;
  9895. LV.set(VD);
  9896. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9897. return false;
  9898. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9899. };
  9900. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9901. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  9902. });
  9903. }
  9904. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9905. // We don't call noteFailure immediately because the assignment happens after
  9906. // we evaluate LHS and RHS.
  9907. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  9908. return Error(E);
  9909. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  9910. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  9911. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  9912. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  9913. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  9914. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  9915. if (E->isComparisonOp()) {
  9916. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  9917. // comparisons and then translating the result.
  9918. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9919. const BinaryOperator *E) {
  9920. using CCR = ComparisonCategoryResult;
  9921. bool IsEqual = ResKind == CCR::Equal,
  9922. IsLess = ResKind == CCR::Less,
  9923. IsGreater = ResKind == CCR::Greater;
  9924. auto Op = E->getOpcode();
  9925. switch (Op) {
  9926. default:
  9927. llvm_unreachable("unsupported binary operator");
  9928. case BO_EQ:
  9929. case BO_NE:
  9930. return Success(IsEqual == (Op == BO_EQ), E);
  9931. case BO_LT: return Success(IsLess, E);
  9932. case BO_GT: return Success(IsGreater, E);
  9933. case BO_LE: return Success(IsEqual || IsLess, E);
  9934. case BO_GE: return Success(IsEqual || IsGreater, E);
  9935. }
  9936. };
  9937. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9938. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9939. });
  9940. }
  9941. QualType LHSTy = E->getLHS()->getType();
  9942. QualType RHSTy = E->getRHS()->getType();
  9943. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  9944. E->getOpcode() == BO_Sub) {
  9945. LValue LHSValue, RHSValue;
  9946. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9947. if (!LHSOK && !Info.noteFailure())
  9948. return false;
  9949. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9950. return false;
  9951. // Reject differing bases from the normal codepath; we special-case
  9952. // comparisons to null.
  9953. if (!HasSameBase(LHSValue, RHSValue)) {
  9954. // Handle &&A - &&B.
  9955. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  9956. return Error(E);
  9957. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  9958. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  9959. if (!LHSExpr || !RHSExpr)
  9960. return Error(E);
  9961. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9962. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9963. if (!LHSAddrExpr || !RHSAddrExpr)
  9964. return Error(E);
  9965. // Make sure both labels come from the same function.
  9966. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9967. RHSAddrExpr->getLabel()->getDeclContext())
  9968. return Error(E);
  9969. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  9970. }
  9971. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9972. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9973. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9974. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9975. // C++11 [expr.add]p6:
  9976. // Unless both pointers point to elements of the same array object, or
  9977. // one past the last element of the array object, the behavior is
  9978. // undefined.
  9979. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  9980. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  9981. RHSDesignator))
  9982. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  9983. QualType Type = E->getLHS()->getType();
  9984. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  9985. CharUnits ElementSize;
  9986. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  9987. return false;
  9988. // As an extension, a type may have zero size (empty struct or union in
  9989. // C, array of zero length). Pointer subtraction in such cases has
  9990. // undefined behavior, so is not constant.
  9991. if (ElementSize.isZero()) {
  9992. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  9993. << ElementType;
  9994. return false;
  9995. }
  9996. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  9997. // and produce incorrect results when it overflows. Such behavior
  9998. // appears to be non-conforming, but is common, so perhaps we should
  9999. // assume the standard intended for such cases to be undefined behavior
  10000. // and check for them.
  10001. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  10002. // overflow in the final conversion to ptrdiff_t.
  10003. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  10004. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  10005. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  10006. false);
  10007. APSInt TrueResult = (LHS - RHS) / ElemSize;
  10008. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  10009. if (Result.extend(65) != TrueResult &&
  10010. !HandleOverflow(Info, E, TrueResult, E->getType()))
  10011. return false;
  10012. return Success(Result, E);
  10013. }
  10014. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10015. }
  10016. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  10017. /// a result as the expression's type.
  10018. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  10019. const UnaryExprOrTypeTraitExpr *E) {
  10020. switch(E->getKind()) {
  10021. case UETT_PreferredAlignOf:
  10022. case UETT_AlignOf: {
  10023. if (E->isArgumentType())
  10024. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  10025. E);
  10026. else
  10027. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  10028. E);
  10029. }
  10030. case UETT_VecStep: {
  10031. QualType Ty = E->getTypeOfArgument();
  10032. if (Ty->isVectorType()) {
  10033. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  10034. // The vec_step built-in functions that take a 3-component
  10035. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  10036. if (n == 3)
  10037. n = 4;
  10038. return Success(n, E);
  10039. } else
  10040. return Success(1, E);
  10041. }
  10042. case UETT_SizeOf: {
  10043. QualType SrcTy = E->getTypeOfArgument();
  10044. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  10045. // the result is the size of the referenced type."
  10046. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  10047. SrcTy = Ref->getPointeeType();
  10048. CharUnits Sizeof;
  10049. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  10050. return false;
  10051. return Success(Sizeof, E);
  10052. }
  10053. case UETT_OpenMPRequiredSimdAlign:
  10054. assert(E->isArgumentType());
  10055. return Success(
  10056. Info.Ctx.toCharUnitsFromBits(
  10057. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  10058. .getQuantity(),
  10059. E);
  10060. }
  10061. llvm_unreachable("unknown expr/type trait");
  10062. }
  10063. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  10064. CharUnits Result;
  10065. unsigned n = OOE->getNumComponents();
  10066. if (n == 0)
  10067. return Error(OOE);
  10068. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  10069. for (unsigned i = 0; i != n; ++i) {
  10070. OffsetOfNode ON = OOE->getComponent(i);
  10071. switch (ON.getKind()) {
  10072. case OffsetOfNode::Array: {
  10073. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  10074. APSInt IdxResult;
  10075. if (!EvaluateInteger(Idx, IdxResult, Info))
  10076. return false;
  10077. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  10078. if (!AT)
  10079. return Error(OOE);
  10080. CurrentType = AT->getElementType();
  10081. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  10082. Result += IdxResult.getSExtValue() * ElementSize;
  10083. break;
  10084. }
  10085. case OffsetOfNode::Field: {
  10086. FieldDecl *MemberDecl = ON.getField();
  10087. const RecordType *RT = CurrentType->getAs<RecordType>();
  10088. if (!RT)
  10089. return Error(OOE);
  10090. RecordDecl *RD = RT->getDecl();
  10091. if (RD->isInvalidDecl()) return false;
  10092. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10093. unsigned i = MemberDecl->getFieldIndex();
  10094. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  10095. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  10096. CurrentType = MemberDecl->getType().getNonReferenceType();
  10097. break;
  10098. }
  10099. case OffsetOfNode::Identifier:
  10100. llvm_unreachable("dependent __builtin_offsetof");
  10101. case OffsetOfNode::Base: {
  10102. CXXBaseSpecifier *BaseSpec = ON.getBase();
  10103. if (BaseSpec->isVirtual())
  10104. return Error(OOE);
  10105. // Find the layout of the class whose base we are looking into.
  10106. const RecordType *RT = CurrentType->getAs<RecordType>();
  10107. if (!RT)
  10108. return Error(OOE);
  10109. RecordDecl *RD = RT->getDecl();
  10110. if (RD->isInvalidDecl()) return false;
  10111. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10112. // Find the base class itself.
  10113. CurrentType = BaseSpec->getType();
  10114. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  10115. if (!BaseRT)
  10116. return Error(OOE);
  10117. // Add the offset to the base.
  10118. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  10119. break;
  10120. }
  10121. }
  10122. }
  10123. return Success(Result, OOE);
  10124. }
  10125. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10126. switch (E->getOpcode()) {
  10127. default:
  10128. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  10129. // See C99 6.6p3.
  10130. return Error(E);
  10131. case UO_Extension:
  10132. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  10133. // If so, we could clear the diagnostic ID.
  10134. return Visit(E->getSubExpr());
  10135. case UO_Plus:
  10136. // The result is just the value.
  10137. return Visit(E->getSubExpr());
  10138. case UO_Minus: {
  10139. if (!Visit(E->getSubExpr()))
  10140. return false;
  10141. if (!Result.isInt()) return Error(E);
  10142. const APSInt &Value = Result.getInt();
  10143. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  10144. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  10145. E->getType()))
  10146. return false;
  10147. return Success(-Value, E);
  10148. }
  10149. case UO_Not: {
  10150. if (!Visit(E->getSubExpr()))
  10151. return false;
  10152. if (!Result.isInt()) return Error(E);
  10153. return Success(~Result.getInt(), E);
  10154. }
  10155. case UO_LNot: {
  10156. bool bres;
  10157. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10158. return false;
  10159. return Success(!bres, E);
  10160. }
  10161. }
  10162. }
  10163. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  10164. /// result type is integer.
  10165. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10166. const Expr *SubExpr = E->getSubExpr();
  10167. QualType DestType = E->getType();
  10168. QualType SrcType = SubExpr->getType();
  10169. switch (E->getCastKind()) {
  10170. case CK_BaseToDerived:
  10171. case CK_DerivedToBase:
  10172. case CK_UncheckedDerivedToBase:
  10173. case CK_Dynamic:
  10174. case CK_ToUnion:
  10175. case CK_ArrayToPointerDecay:
  10176. case CK_FunctionToPointerDecay:
  10177. case CK_NullToPointer:
  10178. case CK_NullToMemberPointer:
  10179. case CK_BaseToDerivedMemberPointer:
  10180. case CK_DerivedToBaseMemberPointer:
  10181. case CK_ReinterpretMemberPointer:
  10182. case CK_ConstructorConversion:
  10183. case CK_IntegralToPointer:
  10184. case CK_ToVoid:
  10185. case CK_VectorSplat:
  10186. case CK_IntegralToFloating:
  10187. case CK_FloatingCast:
  10188. case CK_CPointerToObjCPointerCast:
  10189. case CK_BlockPointerToObjCPointerCast:
  10190. case CK_AnyPointerToBlockPointerCast:
  10191. case CK_ObjCObjectLValueCast:
  10192. case CK_FloatingRealToComplex:
  10193. case CK_FloatingComplexToReal:
  10194. case CK_FloatingComplexCast:
  10195. case CK_FloatingComplexToIntegralComplex:
  10196. case CK_IntegralRealToComplex:
  10197. case CK_IntegralComplexCast:
  10198. case CK_IntegralComplexToFloatingComplex:
  10199. case CK_BuiltinFnToFnPtr:
  10200. case CK_ZeroToOCLOpaqueType:
  10201. case CK_NonAtomicToAtomic:
  10202. case CK_AddressSpaceConversion:
  10203. case CK_IntToOCLSampler:
  10204. case CK_FixedPointCast:
  10205. case CK_IntegralToFixedPoint:
  10206. llvm_unreachable("invalid cast kind for integral value");
  10207. case CK_BitCast:
  10208. case CK_Dependent:
  10209. case CK_LValueBitCast:
  10210. case CK_ARCProduceObject:
  10211. case CK_ARCConsumeObject:
  10212. case CK_ARCReclaimReturnedObject:
  10213. case CK_ARCExtendBlockObject:
  10214. case CK_CopyAndAutoreleaseBlockObject:
  10215. return Error(E);
  10216. case CK_UserDefinedConversion:
  10217. case CK_LValueToRValue:
  10218. case CK_AtomicToNonAtomic:
  10219. case CK_NoOp:
  10220. case CK_LValueToRValueBitCast:
  10221. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10222. case CK_MemberPointerToBoolean:
  10223. case CK_PointerToBoolean:
  10224. case CK_IntegralToBoolean:
  10225. case CK_FloatingToBoolean:
  10226. case CK_BooleanToSignedIntegral:
  10227. case CK_FloatingComplexToBoolean:
  10228. case CK_IntegralComplexToBoolean: {
  10229. bool BoolResult;
  10230. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  10231. return false;
  10232. uint64_t IntResult = BoolResult;
  10233. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  10234. IntResult = (uint64_t)-1;
  10235. return Success(IntResult, E);
  10236. }
  10237. case CK_FixedPointToIntegral: {
  10238. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  10239. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10240. return false;
  10241. bool Overflowed;
  10242. llvm::APSInt Result = Src.convertToInt(
  10243. Info.Ctx.getIntWidth(DestType),
  10244. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  10245. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10246. return false;
  10247. return Success(Result, E);
  10248. }
  10249. case CK_FixedPointToBoolean: {
  10250. // Unsigned padding does not affect this.
  10251. APValue Val;
  10252. if (!Evaluate(Val, Info, SubExpr))
  10253. return false;
  10254. return Success(Val.getFixedPoint().getBoolValue(), E);
  10255. }
  10256. case CK_IntegralCast: {
  10257. if (!Visit(SubExpr))
  10258. return false;
  10259. if (!Result.isInt()) {
  10260. // Allow casts of address-of-label differences if they are no-ops
  10261. // or narrowing. (The narrowing case isn't actually guaranteed to
  10262. // be constant-evaluatable except in some narrow cases which are hard
  10263. // to detect here. We let it through on the assumption the user knows
  10264. // what they are doing.)
  10265. if (Result.isAddrLabelDiff())
  10266. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  10267. // Only allow casts of lvalues if they are lossless.
  10268. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  10269. }
  10270. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  10271. Result.getInt()), E);
  10272. }
  10273. case CK_PointerToIntegral: {
  10274. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  10275. LValue LV;
  10276. if (!EvaluatePointer(SubExpr, LV, Info))
  10277. return false;
  10278. if (LV.getLValueBase()) {
  10279. // Only allow based lvalue casts if they are lossless.
  10280. // FIXME: Allow a larger integer size than the pointer size, and allow
  10281. // narrowing back down to pointer width in subsequent integral casts.
  10282. // FIXME: Check integer type's active bits, not its type size.
  10283. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  10284. return Error(E);
  10285. LV.Designator.setInvalid();
  10286. LV.moveInto(Result);
  10287. return true;
  10288. }
  10289. APSInt AsInt;
  10290. APValue V;
  10291. LV.moveInto(V);
  10292. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  10293. llvm_unreachable("Can't cast this!");
  10294. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  10295. }
  10296. case CK_IntegralComplexToReal: {
  10297. ComplexValue C;
  10298. if (!EvaluateComplex(SubExpr, C, Info))
  10299. return false;
  10300. return Success(C.getComplexIntReal(), E);
  10301. }
  10302. case CK_FloatingToIntegral: {
  10303. APFloat F(0.0);
  10304. if (!EvaluateFloat(SubExpr, F, Info))
  10305. return false;
  10306. APSInt Value;
  10307. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  10308. return false;
  10309. return Success(Value, E);
  10310. }
  10311. }
  10312. llvm_unreachable("unknown cast resulting in integral value");
  10313. }
  10314. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10315. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10316. ComplexValue LV;
  10317. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10318. return false;
  10319. if (!LV.isComplexInt())
  10320. return Error(E);
  10321. return Success(LV.getComplexIntReal(), E);
  10322. }
  10323. return Visit(E->getSubExpr());
  10324. }
  10325. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10326. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  10327. ComplexValue LV;
  10328. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10329. return false;
  10330. if (!LV.isComplexInt())
  10331. return Error(E);
  10332. return Success(LV.getComplexIntImag(), E);
  10333. }
  10334. VisitIgnoredValue(E->getSubExpr());
  10335. return Success(0, E);
  10336. }
  10337. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  10338. return Success(E->getPackLength(), E);
  10339. }
  10340. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  10341. return Success(E->getValue(), E);
  10342. }
  10343. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10344. switch (E->getOpcode()) {
  10345. default:
  10346. // Invalid unary operators
  10347. return Error(E);
  10348. case UO_Plus:
  10349. // The result is just the value.
  10350. return Visit(E->getSubExpr());
  10351. case UO_Minus: {
  10352. if (!Visit(E->getSubExpr())) return false;
  10353. if (!Result.isFixedPoint())
  10354. return Error(E);
  10355. bool Overflowed;
  10356. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  10357. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  10358. return false;
  10359. return Success(Negated, E);
  10360. }
  10361. case UO_LNot: {
  10362. bool bres;
  10363. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10364. return false;
  10365. return Success(!bres, E);
  10366. }
  10367. }
  10368. }
  10369. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10370. const Expr *SubExpr = E->getSubExpr();
  10371. QualType DestType = E->getType();
  10372. assert(DestType->isFixedPointType() &&
  10373. "Expected destination type to be a fixed point type");
  10374. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  10375. switch (E->getCastKind()) {
  10376. case CK_FixedPointCast: {
  10377. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  10378. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10379. return false;
  10380. bool Overflowed;
  10381. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  10382. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10383. return false;
  10384. return Success(Result, E);
  10385. }
  10386. case CK_IntegralToFixedPoint: {
  10387. APSInt Src;
  10388. if (!EvaluateInteger(SubExpr, Src, Info))
  10389. return false;
  10390. bool Overflowed;
  10391. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10392. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  10393. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  10394. return false;
  10395. return Success(IntResult, E);
  10396. }
  10397. case CK_NoOp:
  10398. case CK_LValueToRValue:
  10399. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10400. default:
  10401. return Error(E);
  10402. }
  10403. }
  10404. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10405. const Expr *LHS = E->getLHS();
  10406. const Expr *RHS = E->getRHS();
  10407. FixedPointSemantics ResultFXSema =
  10408. Info.Ctx.getFixedPointSemantics(E->getType());
  10409. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  10410. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  10411. return false;
  10412. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  10413. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  10414. return false;
  10415. switch (E->getOpcode()) {
  10416. case BO_Add: {
  10417. bool AddOverflow, ConversionOverflow;
  10418. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  10419. .convert(ResultFXSema, &ConversionOverflow);
  10420. if ((AddOverflow || ConversionOverflow) &&
  10421. !HandleOverflow(Info, E, Result, E->getType()))
  10422. return false;
  10423. return Success(Result, E);
  10424. }
  10425. default:
  10426. return false;
  10427. }
  10428. llvm_unreachable("Should've exited before this");
  10429. }
  10430. //===----------------------------------------------------------------------===//
  10431. // Float Evaluation
  10432. //===----------------------------------------------------------------------===//
  10433. namespace {
  10434. class FloatExprEvaluator
  10435. : public ExprEvaluatorBase<FloatExprEvaluator> {
  10436. APFloat &Result;
  10437. public:
  10438. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  10439. : ExprEvaluatorBaseTy(info), Result(result) {}
  10440. bool Success(const APValue &V, const Expr *e) {
  10441. Result = V.getFloat();
  10442. return true;
  10443. }
  10444. bool ZeroInitialization(const Expr *E) {
  10445. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  10446. return true;
  10447. }
  10448. bool VisitCallExpr(const CallExpr *E);
  10449. bool VisitUnaryOperator(const UnaryOperator *E);
  10450. bool VisitBinaryOperator(const BinaryOperator *E);
  10451. bool VisitFloatingLiteral(const FloatingLiteral *E);
  10452. bool VisitCastExpr(const CastExpr *E);
  10453. bool VisitUnaryReal(const UnaryOperator *E);
  10454. bool VisitUnaryImag(const UnaryOperator *E);
  10455. // FIXME: Missing: array subscript of vector, member of vector
  10456. };
  10457. } // end anonymous namespace
  10458. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  10459. assert(E->isRValue() && E->getType()->isRealFloatingType());
  10460. return FloatExprEvaluator(Info, Result).Visit(E);
  10461. }
  10462. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  10463. QualType ResultTy,
  10464. const Expr *Arg,
  10465. bool SNaN,
  10466. llvm::APFloat &Result) {
  10467. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  10468. if (!S) return false;
  10469. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  10470. llvm::APInt fill;
  10471. // Treat empty strings as if they were zero.
  10472. if (S->getString().empty())
  10473. fill = llvm::APInt(32, 0);
  10474. else if (S->getString().getAsInteger(0, fill))
  10475. return false;
  10476. if (Context.getTargetInfo().isNan2008()) {
  10477. if (SNaN)
  10478. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10479. else
  10480. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10481. } else {
  10482. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  10483. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  10484. // a different encoding to what became a standard in 2008, and for pre-
  10485. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  10486. // sNaN. This is now known as "legacy NaN" encoding.
  10487. if (SNaN)
  10488. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10489. else
  10490. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10491. }
  10492. return true;
  10493. }
  10494. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10495. switch (E->getBuiltinCallee()) {
  10496. default:
  10497. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10498. case Builtin::BI__builtin_huge_val:
  10499. case Builtin::BI__builtin_huge_valf:
  10500. case Builtin::BI__builtin_huge_vall:
  10501. case Builtin::BI__builtin_huge_valf128:
  10502. case Builtin::BI__builtin_inf:
  10503. case Builtin::BI__builtin_inff:
  10504. case Builtin::BI__builtin_infl:
  10505. case Builtin::BI__builtin_inff128: {
  10506. const llvm::fltSemantics &Sem =
  10507. Info.Ctx.getFloatTypeSemantics(E->getType());
  10508. Result = llvm::APFloat::getInf(Sem);
  10509. return true;
  10510. }
  10511. case Builtin::BI__builtin_nans:
  10512. case Builtin::BI__builtin_nansf:
  10513. case Builtin::BI__builtin_nansl:
  10514. case Builtin::BI__builtin_nansf128:
  10515. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10516. true, Result))
  10517. return Error(E);
  10518. return true;
  10519. case Builtin::BI__builtin_nan:
  10520. case Builtin::BI__builtin_nanf:
  10521. case Builtin::BI__builtin_nanl:
  10522. case Builtin::BI__builtin_nanf128:
  10523. // If this is __builtin_nan() turn this into a nan, otherwise we
  10524. // can't constant fold it.
  10525. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10526. false, Result))
  10527. return Error(E);
  10528. return true;
  10529. case Builtin::BI__builtin_fabs:
  10530. case Builtin::BI__builtin_fabsf:
  10531. case Builtin::BI__builtin_fabsl:
  10532. case Builtin::BI__builtin_fabsf128:
  10533. if (!EvaluateFloat(E->getArg(0), Result, Info))
  10534. return false;
  10535. if (Result.isNegative())
  10536. Result.changeSign();
  10537. return true;
  10538. // FIXME: Builtin::BI__builtin_powi
  10539. // FIXME: Builtin::BI__builtin_powif
  10540. // FIXME: Builtin::BI__builtin_powil
  10541. case Builtin::BI__builtin_copysign:
  10542. case Builtin::BI__builtin_copysignf:
  10543. case Builtin::BI__builtin_copysignl:
  10544. case Builtin::BI__builtin_copysignf128: {
  10545. APFloat RHS(0.);
  10546. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  10547. !EvaluateFloat(E->getArg(1), RHS, Info))
  10548. return false;
  10549. Result.copySign(RHS);
  10550. return true;
  10551. }
  10552. }
  10553. }
  10554. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10555. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10556. ComplexValue CV;
  10557. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10558. return false;
  10559. Result = CV.FloatReal;
  10560. return true;
  10561. }
  10562. return Visit(E->getSubExpr());
  10563. }
  10564. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10565. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10566. ComplexValue CV;
  10567. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10568. return false;
  10569. Result = CV.FloatImag;
  10570. return true;
  10571. }
  10572. VisitIgnoredValue(E->getSubExpr());
  10573. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  10574. Result = llvm::APFloat::getZero(Sem);
  10575. return true;
  10576. }
  10577. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10578. switch (E->getOpcode()) {
  10579. default: return Error(E);
  10580. case UO_Plus:
  10581. return EvaluateFloat(E->getSubExpr(), Result, Info);
  10582. case UO_Minus:
  10583. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  10584. return false;
  10585. Result.changeSign();
  10586. return true;
  10587. }
  10588. }
  10589. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10590. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10591. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10592. APFloat RHS(0.0);
  10593. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  10594. if (!LHSOK && !Info.noteFailure())
  10595. return false;
  10596. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  10597. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  10598. }
  10599. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  10600. Result = E->getValue();
  10601. return true;
  10602. }
  10603. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10604. const Expr* SubExpr = E->getSubExpr();
  10605. switch (E->getCastKind()) {
  10606. default:
  10607. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10608. case CK_IntegralToFloating: {
  10609. APSInt IntResult;
  10610. return EvaluateInteger(SubExpr, IntResult, Info) &&
  10611. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  10612. E->getType(), Result);
  10613. }
  10614. case CK_FloatingCast: {
  10615. if (!Visit(SubExpr))
  10616. return false;
  10617. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  10618. Result);
  10619. }
  10620. case CK_FloatingComplexToReal: {
  10621. ComplexValue V;
  10622. if (!EvaluateComplex(SubExpr, V, Info))
  10623. return false;
  10624. Result = V.getComplexFloatReal();
  10625. return true;
  10626. }
  10627. }
  10628. }
  10629. //===----------------------------------------------------------------------===//
  10630. // Complex Evaluation (for float and integer)
  10631. //===----------------------------------------------------------------------===//
  10632. namespace {
  10633. class ComplexExprEvaluator
  10634. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  10635. ComplexValue &Result;
  10636. public:
  10637. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  10638. : ExprEvaluatorBaseTy(info), Result(Result) {}
  10639. bool Success(const APValue &V, const Expr *e) {
  10640. Result.setFrom(V);
  10641. return true;
  10642. }
  10643. bool ZeroInitialization(const Expr *E);
  10644. //===--------------------------------------------------------------------===//
  10645. // Visitor Methods
  10646. //===--------------------------------------------------------------------===//
  10647. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  10648. bool VisitCastExpr(const CastExpr *E);
  10649. bool VisitBinaryOperator(const BinaryOperator *E);
  10650. bool VisitUnaryOperator(const UnaryOperator *E);
  10651. bool VisitInitListExpr(const InitListExpr *E);
  10652. };
  10653. } // end anonymous namespace
  10654. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  10655. EvalInfo &Info) {
  10656. assert(E->isRValue() && E->getType()->isAnyComplexType());
  10657. return ComplexExprEvaluator(Info, Result).Visit(E);
  10658. }
  10659. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  10660. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  10661. if (ElemTy->isRealFloatingType()) {
  10662. Result.makeComplexFloat();
  10663. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  10664. Result.FloatReal = Zero;
  10665. Result.FloatImag = Zero;
  10666. } else {
  10667. Result.makeComplexInt();
  10668. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  10669. Result.IntReal = Zero;
  10670. Result.IntImag = Zero;
  10671. }
  10672. return true;
  10673. }
  10674. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  10675. const Expr* SubExpr = E->getSubExpr();
  10676. if (SubExpr->getType()->isRealFloatingType()) {
  10677. Result.makeComplexFloat();
  10678. APFloat &Imag = Result.FloatImag;
  10679. if (!EvaluateFloat(SubExpr, Imag, Info))
  10680. return false;
  10681. Result.FloatReal = APFloat(Imag.getSemantics());
  10682. return true;
  10683. } else {
  10684. assert(SubExpr->getType()->isIntegerType() &&
  10685. "Unexpected imaginary literal.");
  10686. Result.makeComplexInt();
  10687. APSInt &Imag = Result.IntImag;
  10688. if (!EvaluateInteger(SubExpr, Imag, Info))
  10689. return false;
  10690. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  10691. return true;
  10692. }
  10693. }
  10694. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10695. switch (E->getCastKind()) {
  10696. case CK_BitCast:
  10697. case CK_BaseToDerived:
  10698. case CK_DerivedToBase:
  10699. case CK_UncheckedDerivedToBase:
  10700. case CK_Dynamic:
  10701. case CK_ToUnion:
  10702. case CK_ArrayToPointerDecay:
  10703. case CK_FunctionToPointerDecay:
  10704. case CK_NullToPointer:
  10705. case CK_NullToMemberPointer:
  10706. case CK_BaseToDerivedMemberPointer:
  10707. case CK_DerivedToBaseMemberPointer:
  10708. case CK_MemberPointerToBoolean:
  10709. case CK_ReinterpretMemberPointer:
  10710. case CK_ConstructorConversion:
  10711. case CK_IntegralToPointer:
  10712. case CK_PointerToIntegral:
  10713. case CK_PointerToBoolean:
  10714. case CK_ToVoid:
  10715. case CK_VectorSplat:
  10716. case CK_IntegralCast:
  10717. case CK_BooleanToSignedIntegral:
  10718. case CK_IntegralToBoolean:
  10719. case CK_IntegralToFloating:
  10720. case CK_FloatingToIntegral:
  10721. case CK_FloatingToBoolean:
  10722. case CK_FloatingCast:
  10723. case CK_CPointerToObjCPointerCast:
  10724. case CK_BlockPointerToObjCPointerCast:
  10725. case CK_AnyPointerToBlockPointerCast:
  10726. case CK_ObjCObjectLValueCast:
  10727. case CK_FloatingComplexToReal:
  10728. case CK_FloatingComplexToBoolean:
  10729. case CK_IntegralComplexToReal:
  10730. case CK_IntegralComplexToBoolean:
  10731. case CK_ARCProduceObject:
  10732. case CK_ARCConsumeObject:
  10733. case CK_ARCReclaimReturnedObject:
  10734. case CK_ARCExtendBlockObject:
  10735. case CK_CopyAndAutoreleaseBlockObject:
  10736. case CK_BuiltinFnToFnPtr:
  10737. case CK_ZeroToOCLOpaqueType:
  10738. case CK_NonAtomicToAtomic:
  10739. case CK_AddressSpaceConversion:
  10740. case CK_IntToOCLSampler:
  10741. case CK_FixedPointCast:
  10742. case CK_FixedPointToBoolean:
  10743. case CK_FixedPointToIntegral:
  10744. case CK_IntegralToFixedPoint:
  10745. llvm_unreachable("invalid cast kind for complex value");
  10746. case CK_LValueToRValue:
  10747. case CK_AtomicToNonAtomic:
  10748. case CK_NoOp:
  10749. case CK_LValueToRValueBitCast:
  10750. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10751. case CK_Dependent:
  10752. case CK_LValueBitCast:
  10753. case CK_UserDefinedConversion:
  10754. return Error(E);
  10755. case CK_FloatingRealToComplex: {
  10756. APFloat &Real = Result.FloatReal;
  10757. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  10758. return false;
  10759. Result.makeComplexFloat();
  10760. Result.FloatImag = APFloat(Real.getSemantics());
  10761. return true;
  10762. }
  10763. case CK_FloatingComplexCast: {
  10764. if (!Visit(E->getSubExpr()))
  10765. return false;
  10766. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10767. QualType From
  10768. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10769. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  10770. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  10771. }
  10772. case CK_FloatingComplexToIntegralComplex: {
  10773. if (!Visit(E->getSubExpr()))
  10774. return false;
  10775. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10776. QualType From
  10777. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10778. Result.makeComplexInt();
  10779. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  10780. To, Result.IntReal) &&
  10781. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  10782. To, Result.IntImag);
  10783. }
  10784. case CK_IntegralRealToComplex: {
  10785. APSInt &Real = Result.IntReal;
  10786. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  10787. return false;
  10788. Result.makeComplexInt();
  10789. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  10790. return true;
  10791. }
  10792. case CK_IntegralComplexCast: {
  10793. if (!Visit(E->getSubExpr()))
  10794. return false;
  10795. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10796. QualType From
  10797. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10798. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  10799. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  10800. return true;
  10801. }
  10802. case CK_IntegralComplexToFloatingComplex: {
  10803. if (!Visit(E->getSubExpr()))
  10804. return false;
  10805. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  10806. QualType From
  10807. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  10808. Result.makeComplexFloat();
  10809. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  10810. To, Result.FloatReal) &&
  10811. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  10812. To, Result.FloatImag);
  10813. }
  10814. }
  10815. llvm_unreachable("unknown cast resulting in complex value");
  10816. }
  10817. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10818. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10819. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10820. // Track whether the LHS or RHS is real at the type system level. When this is
  10821. // the case we can simplify our evaluation strategy.
  10822. bool LHSReal = false, RHSReal = false;
  10823. bool LHSOK;
  10824. if (E->getLHS()->getType()->isRealFloatingType()) {
  10825. LHSReal = true;
  10826. APFloat &Real = Result.FloatReal;
  10827. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  10828. if (LHSOK) {
  10829. Result.makeComplexFloat();
  10830. Result.FloatImag = APFloat(Real.getSemantics());
  10831. }
  10832. } else {
  10833. LHSOK = Visit(E->getLHS());
  10834. }
  10835. if (!LHSOK && !Info.noteFailure())
  10836. return false;
  10837. ComplexValue RHS;
  10838. if (E->getRHS()->getType()->isRealFloatingType()) {
  10839. RHSReal = true;
  10840. APFloat &Real = RHS.FloatReal;
  10841. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  10842. return false;
  10843. RHS.makeComplexFloat();
  10844. RHS.FloatImag = APFloat(Real.getSemantics());
  10845. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10846. return false;
  10847. assert(!(LHSReal && RHSReal) &&
  10848. "Cannot have both operands of a complex operation be real.");
  10849. switch (E->getOpcode()) {
  10850. default: return Error(E);
  10851. case BO_Add:
  10852. if (Result.isComplexFloat()) {
  10853. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  10854. APFloat::rmNearestTiesToEven);
  10855. if (LHSReal)
  10856. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10857. else if (!RHSReal)
  10858. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  10859. APFloat::rmNearestTiesToEven);
  10860. } else {
  10861. Result.getComplexIntReal() += RHS.getComplexIntReal();
  10862. Result.getComplexIntImag() += RHS.getComplexIntImag();
  10863. }
  10864. break;
  10865. case BO_Sub:
  10866. if (Result.isComplexFloat()) {
  10867. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  10868. APFloat::rmNearestTiesToEven);
  10869. if (LHSReal) {
  10870. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10871. Result.getComplexFloatImag().changeSign();
  10872. } else if (!RHSReal) {
  10873. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  10874. APFloat::rmNearestTiesToEven);
  10875. }
  10876. } else {
  10877. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  10878. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  10879. }
  10880. break;
  10881. case BO_Mul:
  10882. if (Result.isComplexFloat()) {
  10883. // This is an implementation of complex multiplication according to the
  10884. // constraints laid out in C11 Annex G. The implementation uses the
  10885. // following naming scheme:
  10886. // (a + ib) * (c + id)
  10887. ComplexValue LHS = Result;
  10888. APFloat &A = LHS.getComplexFloatReal();
  10889. APFloat &B = LHS.getComplexFloatImag();
  10890. APFloat &C = RHS.getComplexFloatReal();
  10891. APFloat &D = RHS.getComplexFloatImag();
  10892. APFloat &ResR = Result.getComplexFloatReal();
  10893. APFloat &ResI = Result.getComplexFloatImag();
  10894. if (LHSReal) {
  10895. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  10896. ResR = A * C;
  10897. ResI = A * D;
  10898. } else if (RHSReal) {
  10899. ResR = C * A;
  10900. ResI = C * B;
  10901. } else {
  10902. // In the fully general case, we need to handle NaNs and infinities
  10903. // robustly.
  10904. APFloat AC = A * C;
  10905. APFloat BD = B * D;
  10906. APFloat AD = A * D;
  10907. APFloat BC = B * C;
  10908. ResR = AC - BD;
  10909. ResI = AD + BC;
  10910. if (ResR.isNaN() && ResI.isNaN()) {
  10911. bool Recalc = false;
  10912. if (A.isInfinity() || B.isInfinity()) {
  10913. A = APFloat::copySign(
  10914. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10915. B = APFloat::copySign(
  10916. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10917. if (C.isNaN())
  10918. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10919. if (D.isNaN())
  10920. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10921. Recalc = true;
  10922. }
  10923. if (C.isInfinity() || D.isInfinity()) {
  10924. C = APFloat::copySign(
  10925. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10926. D = APFloat::copySign(
  10927. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10928. if (A.isNaN())
  10929. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10930. if (B.isNaN())
  10931. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10932. Recalc = true;
  10933. }
  10934. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  10935. AD.isInfinity() || BC.isInfinity())) {
  10936. if (A.isNaN())
  10937. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10938. if (B.isNaN())
  10939. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10940. if (C.isNaN())
  10941. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10942. if (D.isNaN())
  10943. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10944. Recalc = true;
  10945. }
  10946. if (Recalc) {
  10947. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  10948. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  10949. }
  10950. }
  10951. }
  10952. } else {
  10953. ComplexValue LHS = Result;
  10954. Result.getComplexIntReal() =
  10955. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  10956. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  10957. Result.getComplexIntImag() =
  10958. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  10959. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  10960. }
  10961. break;
  10962. case BO_Div:
  10963. if (Result.isComplexFloat()) {
  10964. // This is an implementation of complex division according to the
  10965. // constraints laid out in C11 Annex G. The implementation uses the
  10966. // following naming scheme:
  10967. // (a + ib) / (c + id)
  10968. ComplexValue LHS = Result;
  10969. APFloat &A = LHS.getComplexFloatReal();
  10970. APFloat &B = LHS.getComplexFloatImag();
  10971. APFloat &C = RHS.getComplexFloatReal();
  10972. APFloat &D = RHS.getComplexFloatImag();
  10973. APFloat &ResR = Result.getComplexFloatReal();
  10974. APFloat &ResI = Result.getComplexFloatImag();
  10975. if (RHSReal) {
  10976. ResR = A / C;
  10977. ResI = B / C;
  10978. } else {
  10979. if (LHSReal) {
  10980. // No real optimizations we can do here, stub out with zero.
  10981. B = APFloat::getZero(A.getSemantics());
  10982. }
  10983. int DenomLogB = 0;
  10984. APFloat MaxCD = maxnum(abs(C), abs(D));
  10985. if (MaxCD.isFinite()) {
  10986. DenomLogB = ilogb(MaxCD);
  10987. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  10988. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  10989. }
  10990. APFloat Denom = C * C + D * D;
  10991. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  10992. APFloat::rmNearestTiesToEven);
  10993. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  10994. APFloat::rmNearestTiesToEven);
  10995. if (ResR.isNaN() && ResI.isNaN()) {
  10996. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  10997. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  10998. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  10999. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  11000. D.isFinite()) {
  11001. A = APFloat::copySign(
  11002. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11003. B = APFloat::copySign(
  11004. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11005. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  11006. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  11007. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  11008. C = APFloat::copySign(
  11009. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11010. D = APFloat::copySign(
  11011. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11012. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  11013. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  11014. }
  11015. }
  11016. }
  11017. } else {
  11018. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  11019. return Error(E, diag::note_expr_divide_by_zero);
  11020. ComplexValue LHS = Result;
  11021. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11022. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  11023. Result.getComplexIntReal() =
  11024. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11025. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  11026. Result.getComplexIntImag() =
  11027. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  11028. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  11029. }
  11030. break;
  11031. }
  11032. return true;
  11033. }
  11034. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11035. // Get the operand value into 'Result'.
  11036. if (!Visit(E->getSubExpr()))
  11037. return false;
  11038. switch (E->getOpcode()) {
  11039. default:
  11040. return Error(E);
  11041. case UO_Extension:
  11042. return true;
  11043. case UO_Plus:
  11044. // The result is always just the subexpr.
  11045. return true;
  11046. case UO_Minus:
  11047. if (Result.isComplexFloat()) {
  11048. Result.getComplexFloatReal().changeSign();
  11049. Result.getComplexFloatImag().changeSign();
  11050. }
  11051. else {
  11052. Result.getComplexIntReal() = -Result.getComplexIntReal();
  11053. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11054. }
  11055. return true;
  11056. case UO_Not:
  11057. if (Result.isComplexFloat())
  11058. Result.getComplexFloatImag().changeSign();
  11059. else
  11060. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11061. return true;
  11062. }
  11063. }
  11064. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  11065. if (E->getNumInits() == 2) {
  11066. if (E->getType()->isComplexType()) {
  11067. Result.makeComplexFloat();
  11068. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  11069. return false;
  11070. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  11071. return false;
  11072. } else {
  11073. Result.makeComplexInt();
  11074. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  11075. return false;
  11076. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  11077. return false;
  11078. }
  11079. return true;
  11080. }
  11081. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  11082. }
  11083. //===----------------------------------------------------------------------===//
  11084. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  11085. // implicit conversion.
  11086. //===----------------------------------------------------------------------===//
  11087. namespace {
  11088. class AtomicExprEvaluator :
  11089. public ExprEvaluatorBase<AtomicExprEvaluator> {
  11090. const LValue *This;
  11091. APValue &Result;
  11092. public:
  11093. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  11094. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  11095. bool Success(const APValue &V, const Expr *E) {
  11096. Result = V;
  11097. return true;
  11098. }
  11099. bool ZeroInitialization(const Expr *E) {
  11100. ImplicitValueInitExpr VIE(
  11101. E->getType()->castAs<AtomicType>()->getValueType());
  11102. // For atomic-qualified class (and array) types in C++, initialize the
  11103. // _Atomic-wrapped subobject directly, in-place.
  11104. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  11105. : Evaluate(Result, Info, &VIE);
  11106. }
  11107. bool VisitCastExpr(const CastExpr *E) {
  11108. switch (E->getCastKind()) {
  11109. default:
  11110. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11111. case CK_NonAtomicToAtomic:
  11112. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  11113. : Evaluate(Result, Info, E->getSubExpr());
  11114. }
  11115. }
  11116. };
  11117. } // end anonymous namespace
  11118. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  11119. EvalInfo &Info) {
  11120. assert(E->isRValue() && E->getType()->isAtomicType());
  11121. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  11122. }
  11123. //===----------------------------------------------------------------------===//
  11124. // Void expression evaluation, primarily for a cast to void on the LHS of a
  11125. // comma operator
  11126. //===----------------------------------------------------------------------===//
  11127. namespace {
  11128. class VoidExprEvaluator
  11129. : public ExprEvaluatorBase<VoidExprEvaluator> {
  11130. public:
  11131. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  11132. bool Success(const APValue &V, const Expr *e) { return true; }
  11133. bool ZeroInitialization(const Expr *E) { return true; }
  11134. bool VisitCastExpr(const CastExpr *E) {
  11135. switch (E->getCastKind()) {
  11136. default:
  11137. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11138. case CK_ToVoid:
  11139. VisitIgnoredValue(E->getSubExpr());
  11140. return true;
  11141. }
  11142. }
  11143. bool VisitCallExpr(const CallExpr *E) {
  11144. switch (E->getBuiltinCallee()) {
  11145. default:
  11146. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  11147. case Builtin::BI__assume:
  11148. case Builtin::BI__builtin_assume:
  11149. // The argument is not evaluated!
  11150. return true;
  11151. }
  11152. }
  11153. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  11154. };
  11155. } // end anonymous namespace
  11156. static bool hasVirtualDestructor(QualType T) {
  11157. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  11158. if (CXXDestructorDecl *DD = RD->getDestructor())
  11159. return DD->isVirtual();
  11160. return false;
  11161. }
  11162. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  11163. // We cannot speculatively evaluate a delete expression.
  11164. if (Info.SpeculativeEvaluationDepth)
  11165. return false;
  11166. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  11167. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  11168. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  11169. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  11170. return false;
  11171. }
  11172. const Expr *Arg = E->getArgument();
  11173. LValue Pointer;
  11174. if (!EvaluatePointer(Arg, Pointer, Info))
  11175. return false;
  11176. if (Pointer.Designator.Invalid)
  11177. return false;
  11178. // Deleting a null pointer has no effect.
  11179. if (Pointer.isNullPointer()) {
  11180. // This is the only case where we need to produce an extension warning:
  11181. // the only other way we can succeed is if we find a dynamic allocation,
  11182. // and we will have warned when we allocated it in that case.
  11183. if (!Info.getLangOpts().CPlusPlus2a)
  11184. Info.CCEDiag(E, diag::note_constexpr_new);
  11185. return true;
  11186. }
  11187. auto PointerAsString = [&] {
  11188. APValue Printable;
  11189. Pointer.moveInto(Printable);
  11190. return Printable.getAsString(Info.Ctx, Arg->getType());
  11191. };
  11192. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  11193. if (!DA) {
  11194. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  11195. << PointerAsString();
  11196. if (Pointer.Base)
  11197. NoteLValueLocation(Info, Pointer.Base);
  11198. return false;
  11199. }
  11200. QualType AllocType = Pointer.Base.getDynamicAllocType();
  11201. Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  11202. if (!Alloc) {
  11203. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11204. return false;
  11205. }
  11206. if (E->isArrayForm() != AllocType->isConstantArrayType()) {
  11207. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  11208. << E->isArrayForm() << AllocType;
  11209. NoteLValueLocation(Info, Pointer.Base);
  11210. return false;
  11211. }
  11212. bool Subobject = false;
  11213. if (E->isArrayForm()) {
  11214. Subobject = Pointer.Designator.Entries.size() != 1 ||
  11215. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  11216. } else {
  11217. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  11218. Pointer.Designator.isOnePastTheEnd();
  11219. }
  11220. if (Subobject) {
  11221. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  11222. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  11223. return false;
  11224. }
  11225. // For the non-array case, the designator must be empty if the static type
  11226. // does not have a virtual destructor.
  11227. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  11228. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  11229. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  11230. << Arg->getType()->getPointeeType() << AllocType;
  11231. return false;
  11232. }
  11233. if (!HandleDestructorCall(Info, E->getExprLoc(), Pointer.getLValueBase(),
  11234. (*Alloc)->Value, AllocType))
  11235. return false;
  11236. if (!Info.HeapAllocs.erase(DA)) {
  11237. // The element was already erased. This means the destructor call also
  11238. // deleted the object.
  11239. // FIXME: This probably results in undefined behavior before we get this
  11240. // far, and should be diagnosed elsewhere first.
  11241. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11242. return false;
  11243. }
  11244. return true;
  11245. }
  11246. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  11247. assert(E->isRValue() && E->getType()->isVoidType());
  11248. return VoidExprEvaluator(Info).Visit(E);
  11249. }
  11250. //===----------------------------------------------------------------------===//
  11251. // Top level Expr::EvaluateAsRValue method.
  11252. //===----------------------------------------------------------------------===//
  11253. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  11254. // In C, function designators are not lvalues, but we evaluate them as if they
  11255. // are.
  11256. QualType T = E->getType();
  11257. if (E->isGLValue() || T->isFunctionType()) {
  11258. LValue LV;
  11259. if (!EvaluateLValue(E, LV, Info))
  11260. return false;
  11261. LV.moveInto(Result);
  11262. } else if (T->isVectorType()) {
  11263. if (!EvaluateVector(E, Result, Info))
  11264. return false;
  11265. } else if (T->isIntegralOrEnumerationType()) {
  11266. if (!IntExprEvaluator(Info, Result).Visit(E))
  11267. return false;
  11268. } else if (T->hasPointerRepresentation()) {
  11269. LValue LV;
  11270. if (!EvaluatePointer(E, LV, Info))
  11271. return false;
  11272. LV.moveInto(Result);
  11273. } else if (T->isRealFloatingType()) {
  11274. llvm::APFloat F(0.0);
  11275. if (!EvaluateFloat(E, F, Info))
  11276. return false;
  11277. Result = APValue(F);
  11278. } else if (T->isAnyComplexType()) {
  11279. ComplexValue C;
  11280. if (!EvaluateComplex(E, C, Info))
  11281. return false;
  11282. C.moveInto(Result);
  11283. } else if (T->isFixedPointType()) {
  11284. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  11285. } else if (T->isMemberPointerType()) {
  11286. MemberPtr P;
  11287. if (!EvaluateMemberPointer(E, P, Info))
  11288. return false;
  11289. P.moveInto(Result);
  11290. return true;
  11291. } else if (T->isArrayType()) {
  11292. LValue LV;
  11293. APValue &Value =
  11294. Info.CurrentCall->createTemporary(E, T, false, LV);
  11295. if (!EvaluateArray(E, LV, Value, Info))
  11296. return false;
  11297. Result = Value;
  11298. } else if (T->isRecordType()) {
  11299. LValue LV;
  11300. APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
  11301. if (!EvaluateRecord(E, LV, Value, Info))
  11302. return false;
  11303. Result = Value;
  11304. } else if (T->isVoidType()) {
  11305. if (!Info.getLangOpts().CPlusPlus11)
  11306. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  11307. << E->getType();
  11308. if (!EvaluateVoid(E, Info))
  11309. return false;
  11310. } else if (T->isAtomicType()) {
  11311. QualType Unqual = T.getAtomicUnqualifiedType();
  11312. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  11313. LValue LV;
  11314. APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
  11315. if (!EvaluateAtomic(E, &LV, Value, Info))
  11316. return false;
  11317. } else {
  11318. if (!EvaluateAtomic(E, nullptr, Result, Info))
  11319. return false;
  11320. }
  11321. } else if (Info.getLangOpts().CPlusPlus11) {
  11322. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  11323. return false;
  11324. } else {
  11325. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11326. return false;
  11327. }
  11328. return true;
  11329. }
  11330. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  11331. /// cases, the in-place evaluation is essential, since later initializers for
  11332. /// an object can indirectly refer to subobjects which were initialized earlier.
  11333. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  11334. const Expr *E, bool AllowNonLiteralTypes) {
  11335. assert(!E->isValueDependent());
  11336. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  11337. return false;
  11338. if (E->isRValue()) {
  11339. // Evaluate arrays and record types in-place, so that later initializers can
  11340. // refer to earlier-initialized members of the object.
  11341. QualType T = E->getType();
  11342. if (T->isArrayType())
  11343. return EvaluateArray(E, This, Result, Info);
  11344. else if (T->isRecordType())
  11345. return EvaluateRecord(E, This, Result, Info);
  11346. else if (T->isAtomicType()) {
  11347. QualType Unqual = T.getAtomicUnqualifiedType();
  11348. if (Unqual->isArrayType() || Unqual->isRecordType())
  11349. return EvaluateAtomic(E, &This, Result, Info);
  11350. }
  11351. }
  11352. // For any other type, in-place evaluation is unimportant.
  11353. return Evaluate(Result, Info, E);
  11354. }
  11355. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  11356. /// lvalue-to-rvalue cast if it is an lvalue.
  11357. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  11358. if (Info.EnableNewConstInterp) {
  11359. auto &InterpCtx = Info.Ctx.getInterpContext();
  11360. switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
  11361. case interp::InterpResult::Success:
  11362. return true;
  11363. case interp::InterpResult::Fail:
  11364. return false;
  11365. case interp::InterpResult::Bail:
  11366. break;
  11367. }
  11368. }
  11369. if (E->getType().isNull())
  11370. return false;
  11371. if (!CheckLiteralType(Info, E))
  11372. return false;
  11373. if (!::Evaluate(Result, Info, E))
  11374. return false;
  11375. if (E->isGLValue()) {
  11376. LValue LV;
  11377. LV.setFrom(Info.Ctx, Result);
  11378. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11379. return false;
  11380. }
  11381. // Check this core constant expression is a constant expression.
  11382. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
  11383. CheckMemoryLeaks(Info);
  11384. }
  11385. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  11386. const ASTContext &Ctx, bool &IsConst) {
  11387. // Fast-path evaluations of integer literals, since we sometimes see files
  11388. // containing vast quantities of these.
  11389. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  11390. Result.Val = APValue(APSInt(L->getValue(),
  11391. L->getType()->isUnsignedIntegerType()));
  11392. IsConst = true;
  11393. return true;
  11394. }
  11395. // This case should be rare, but we need to check it before we check on
  11396. // the type below.
  11397. if (Exp->getType().isNull()) {
  11398. IsConst = false;
  11399. return true;
  11400. }
  11401. // FIXME: Evaluating values of large array and record types can cause
  11402. // performance problems. Only do so in C++11 for now.
  11403. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  11404. Exp->getType()->isRecordType()) &&
  11405. !Ctx.getLangOpts().CPlusPlus11) {
  11406. IsConst = false;
  11407. return true;
  11408. }
  11409. return false;
  11410. }
  11411. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  11412. Expr::SideEffectsKind SEK) {
  11413. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  11414. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  11415. }
  11416. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  11417. const ASTContext &Ctx, EvalInfo &Info) {
  11418. bool IsConst;
  11419. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  11420. return IsConst;
  11421. return EvaluateAsRValue(Info, E, Result.Val);
  11422. }
  11423. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  11424. const ASTContext &Ctx,
  11425. Expr::SideEffectsKind AllowSideEffects,
  11426. EvalInfo &Info) {
  11427. if (!E->getType()->isIntegralOrEnumerationType())
  11428. return false;
  11429. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  11430. !ExprResult.Val.isInt() ||
  11431. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11432. return false;
  11433. return true;
  11434. }
  11435. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  11436. const ASTContext &Ctx,
  11437. Expr::SideEffectsKind AllowSideEffects,
  11438. EvalInfo &Info) {
  11439. if (!E->getType()->isFixedPointType())
  11440. return false;
  11441. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  11442. return false;
  11443. if (!ExprResult.Val.isFixedPoint() ||
  11444. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11445. return false;
  11446. return true;
  11447. }
  11448. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  11449. /// any crazy technique (that has nothing to do with language standards) that
  11450. /// we want to. If this function returns true, it returns the folded constant
  11451. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  11452. /// will be applied to the result.
  11453. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  11454. bool InConstantContext) const {
  11455. assert(!isValueDependent() &&
  11456. "Expression evaluator can't be called on a dependent expression.");
  11457. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11458. Info.InConstantContext = InConstantContext;
  11459. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  11460. }
  11461. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  11462. bool InConstantContext) const {
  11463. assert(!isValueDependent() &&
  11464. "Expression evaluator can't be called on a dependent expression.");
  11465. EvalResult Scratch;
  11466. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  11467. HandleConversionToBool(Scratch.Val, Result);
  11468. }
  11469. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  11470. SideEffectsKind AllowSideEffects,
  11471. bool InConstantContext) const {
  11472. assert(!isValueDependent() &&
  11473. "Expression evaluator can't be called on a dependent expression.");
  11474. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11475. Info.InConstantContext = InConstantContext;
  11476. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  11477. }
  11478. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  11479. SideEffectsKind AllowSideEffects,
  11480. bool InConstantContext) const {
  11481. assert(!isValueDependent() &&
  11482. "Expression evaluator can't be called on a dependent expression.");
  11483. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11484. Info.InConstantContext = InConstantContext;
  11485. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  11486. }
  11487. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  11488. SideEffectsKind AllowSideEffects,
  11489. bool InConstantContext) const {
  11490. assert(!isValueDependent() &&
  11491. "Expression evaluator can't be called on a dependent expression.");
  11492. if (!getType()->isRealFloatingType())
  11493. return false;
  11494. EvalResult ExprResult;
  11495. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  11496. !ExprResult.Val.isFloat() ||
  11497. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11498. return false;
  11499. Result = ExprResult.Val.getFloat();
  11500. return true;
  11501. }
  11502. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  11503. bool InConstantContext) const {
  11504. assert(!isValueDependent() &&
  11505. "Expression evaluator can't be called on a dependent expression.");
  11506. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  11507. Info.InConstantContext = InConstantContext;
  11508. LValue LV;
  11509. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  11510. Result.HasSideEffects ||
  11511. !CheckLValueConstantExpression(Info, getExprLoc(),
  11512. Ctx.getLValueReferenceType(getType()), LV,
  11513. Expr::EvaluateForCodeGen))
  11514. return false;
  11515. LV.moveInto(Result.Val);
  11516. return true;
  11517. }
  11518. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  11519. const ASTContext &Ctx) const {
  11520. assert(!isValueDependent() &&
  11521. "Expression evaluator can't be called on a dependent expression.");
  11522. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  11523. EvalInfo Info(Ctx, Result, EM);
  11524. Info.InConstantContext = true;
  11525. if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
  11526. return false;
  11527. if (!Info.discardCleanups())
  11528. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11529. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  11530. Usage) &&
  11531. CheckMemoryLeaks(Info);
  11532. }
  11533. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  11534. const VarDecl *VD,
  11535. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11536. assert(!isValueDependent() &&
  11537. "Expression evaluator can't be called on a dependent expression.");
  11538. // FIXME: Evaluating initializers for large array and record types can cause
  11539. // performance problems. Only do so in C++11 for now.
  11540. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  11541. !Ctx.getLangOpts().CPlusPlus11)
  11542. return false;
  11543. Expr::EvalStatus EStatus;
  11544. EStatus.Diag = &Notes;
  11545. EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
  11546. ? EvalInfo::EM_ConstantExpression
  11547. : EvalInfo::EM_ConstantFold);
  11548. Info.setEvaluatingDecl(VD, Value);
  11549. Info.InConstantContext = true;
  11550. SourceLocation DeclLoc = VD->getLocation();
  11551. QualType DeclTy = VD->getType();
  11552. if (Info.EnableNewConstInterp) {
  11553. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  11554. switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
  11555. case interp::InterpResult::Fail:
  11556. // Bail out if an error was encountered.
  11557. return false;
  11558. case interp::InterpResult::Success:
  11559. // Evaluation succeeded and value was set.
  11560. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  11561. case interp::InterpResult::Bail:
  11562. // Evaluate the value again for the tree evaluator to use.
  11563. break;
  11564. }
  11565. }
  11566. LValue LVal;
  11567. LVal.set(VD);
  11568. // C++11 [basic.start.init]p2:
  11569. // Variables with static storage duration or thread storage duration shall be
  11570. // zero-initialized before any other initialization takes place.
  11571. // This behavior is not present in C.
  11572. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  11573. !DeclTy->isReferenceType()) {
  11574. ImplicitValueInitExpr VIE(DeclTy);
  11575. if (!EvaluateInPlace(Value, Info, LVal, &VIE,
  11576. /*AllowNonLiteralTypes=*/true))
  11577. return false;
  11578. }
  11579. if (!EvaluateInPlace(Value, Info, LVal, this,
  11580. /*AllowNonLiteralTypes=*/true) ||
  11581. EStatus.HasSideEffects)
  11582. return false;
  11583. // At this point, any lifetime-extended temporaries are completely
  11584. // initialized.
  11585. Info.performLifetimeExtension();
  11586. if (!Info.discardCleanups())
  11587. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11588. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
  11589. CheckMemoryLeaks(Info);
  11590. }
  11591. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  11592. /// constant folded, but discard the result.
  11593. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  11594. assert(!isValueDependent() &&
  11595. "Expression evaluator can't be called on a dependent expression.");
  11596. EvalResult Result;
  11597. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  11598. !hasUnacceptableSideEffect(Result, SEK);
  11599. }
  11600. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  11601. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11602. assert(!isValueDependent() &&
  11603. "Expression evaluator can't be called on a dependent expression.");
  11604. EvalResult EVResult;
  11605. EVResult.Diag = Diag;
  11606. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11607. Info.InConstantContext = true;
  11608. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  11609. (void)Result;
  11610. assert(Result && "Could not evaluate expression");
  11611. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11612. return EVResult.Val.getInt();
  11613. }
  11614. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  11615. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11616. assert(!isValueDependent() &&
  11617. "Expression evaluator can't be called on a dependent expression.");
  11618. EvalResult EVResult;
  11619. EVResult.Diag = Diag;
  11620. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11621. Info.InConstantContext = true;
  11622. Info.CheckingForUndefinedBehavior = true;
  11623. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  11624. (void)Result;
  11625. assert(Result && "Could not evaluate expression");
  11626. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11627. return EVResult.Val.getInt();
  11628. }
  11629. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  11630. assert(!isValueDependent() &&
  11631. "Expression evaluator can't be called on a dependent expression.");
  11632. bool IsConst;
  11633. EvalResult EVResult;
  11634. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  11635. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11636. Info.CheckingForUndefinedBehavior = true;
  11637. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  11638. }
  11639. }
  11640. bool Expr::EvalResult::isGlobalLValue() const {
  11641. assert(Val.isLValue());
  11642. return IsGlobalLValue(Val.getLValueBase());
  11643. }
  11644. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  11645. /// an integer constant expression.
  11646. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  11647. /// comma, etc
  11648. // CheckICE - This function does the fundamental ICE checking: the returned
  11649. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  11650. // and a (possibly null) SourceLocation indicating the location of the problem.
  11651. //
  11652. // Note that to reduce code duplication, this helper does no evaluation
  11653. // itself; the caller checks whether the expression is evaluatable, and
  11654. // in the rare cases where CheckICE actually cares about the evaluated
  11655. // value, it calls into Evaluate.
  11656. namespace {
  11657. enum ICEKind {
  11658. /// This expression is an ICE.
  11659. IK_ICE,
  11660. /// This expression is not an ICE, but if it isn't evaluated, it's
  11661. /// a legal subexpression for an ICE. This return value is used to handle
  11662. /// the comma operator in C99 mode, and non-constant subexpressions.
  11663. IK_ICEIfUnevaluated,
  11664. /// This expression is not an ICE, and is not a legal subexpression for one.
  11665. IK_NotICE
  11666. };
  11667. struct ICEDiag {
  11668. ICEKind Kind;
  11669. SourceLocation Loc;
  11670. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  11671. };
  11672. }
  11673. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  11674. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  11675. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  11676. Expr::EvalResult EVResult;
  11677. Expr::EvalStatus Status;
  11678. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11679. Info.InConstantContext = true;
  11680. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  11681. !EVResult.Val.isInt())
  11682. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11683. return NoDiag();
  11684. }
  11685. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  11686. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  11687. if (!E->getType()->isIntegralOrEnumerationType())
  11688. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11689. switch (E->getStmtClass()) {
  11690. #define ABSTRACT_STMT(Node)
  11691. #define STMT(Node, Base) case Expr::Node##Class:
  11692. #define EXPR(Node, Base)
  11693. #include "clang/AST/StmtNodes.inc"
  11694. case Expr::PredefinedExprClass:
  11695. case Expr::FloatingLiteralClass:
  11696. case Expr::ImaginaryLiteralClass:
  11697. case Expr::StringLiteralClass:
  11698. case Expr::ArraySubscriptExprClass:
  11699. case Expr::OMPArraySectionExprClass:
  11700. case Expr::MemberExprClass:
  11701. case Expr::CompoundAssignOperatorClass:
  11702. case Expr::CompoundLiteralExprClass:
  11703. case Expr::ExtVectorElementExprClass:
  11704. case Expr::DesignatedInitExprClass:
  11705. case Expr::ArrayInitLoopExprClass:
  11706. case Expr::ArrayInitIndexExprClass:
  11707. case Expr::NoInitExprClass:
  11708. case Expr::DesignatedInitUpdateExprClass:
  11709. case Expr::ImplicitValueInitExprClass:
  11710. case Expr::ParenListExprClass:
  11711. case Expr::VAArgExprClass:
  11712. case Expr::AddrLabelExprClass:
  11713. case Expr::StmtExprClass:
  11714. case Expr::CXXMemberCallExprClass:
  11715. case Expr::CUDAKernelCallExprClass:
  11716. case Expr::CXXDynamicCastExprClass:
  11717. case Expr::CXXTypeidExprClass:
  11718. case Expr::CXXUuidofExprClass:
  11719. case Expr::MSPropertyRefExprClass:
  11720. case Expr::MSPropertySubscriptExprClass:
  11721. case Expr::CXXNullPtrLiteralExprClass:
  11722. case Expr::UserDefinedLiteralClass:
  11723. case Expr::CXXThisExprClass:
  11724. case Expr::CXXThrowExprClass:
  11725. case Expr::CXXNewExprClass:
  11726. case Expr::CXXDeleteExprClass:
  11727. case Expr::CXXPseudoDestructorExprClass:
  11728. case Expr::UnresolvedLookupExprClass:
  11729. case Expr::TypoExprClass:
  11730. case Expr::DependentScopeDeclRefExprClass:
  11731. case Expr::CXXConstructExprClass:
  11732. case Expr::CXXInheritedCtorInitExprClass:
  11733. case Expr::CXXStdInitializerListExprClass:
  11734. case Expr::CXXBindTemporaryExprClass:
  11735. case Expr::ExprWithCleanupsClass:
  11736. case Expr::CXXTemporaryObjectExprClass:
  11737. case Expr::CXXUnresolvedConstructExprClass:
  11738. case Expr::CXXDependentScopeMemberExprClass:
  11739. case Expr::UnresolvedMemberExprClass:
  11740. case Expr::ObjCStringLiteralClass:
  11741. case Expr::ObjCBoxedExprClass:
  11742. case Expr::ObjCArrayLiteralClass:
  11743. case Expr::ObjCDictionaryLiteralClass:
  11744. case Expr::ObjCEncodeExprClass:
  11745. case Expr::ObjCMessageExprClass:
  11746. case Expr::ObjCSelectorExprClass:
  11747. case Expr::ObjCProtocolExprClass:
  11748. case Expr::ObjCIvarRefExprClass:
  11749. case Expr::ObjCPropertyRefExprClass:
  11750. case Expr::ObjCSubscriptRefExprClass:
  11751. case Expr::ObjCIsaExprClass:
  11752. case Expr::ObjCAvailabilityCheckExprClass:
  11753. case Expr::ShuffleVectorExprClass:
  11754. case Expr::ConvertVectorExprClass:
  11755. case Expr::BlockExprClass:
  11756. case Expr::NoStmtClass:
  11757. case Expr::OpaqueValueExprClass:
  11758. case Expr::PackExpansionExprClass:
  11759. case Expr::SubstNonTypeTemplateParmPackExprClass:
  11760. case Expr::FunctionParmPackExprClass:
  11761. case Expr::AsTypeExprClass:
  11762. case Expr::ObjCIndirectCopyRestoreExprClass:
  11763. case Expr::MaterializeTemporaryExprClass:
  11764. case Expr::PseudoObjectExprClass:
  11765. case Expr::AtomicExprClass:
  11766. case Expr::LambdaExprClass:
  11767. case Expr::CXXFoldExprClass:
  11768. case Expr::CoawaitExprClass:
  11769. case Expr::DependentCoawaitExprClass:
  11770. case Expr::CoyieldExprClass:
  11771. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11772. case Expr::InitListExprClass: {
  11773. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  11774. // form "T x = { a };" is equivalent to "T x = a;".
  11775. // Unless we're initializing a reference, T is a scalar as it is known to be
  11776. // of integral or enumeration type.
  11777. if (E->isRValue())
  11778. if (cast<InitListExpr>(E)->getNumInits() == 1)
  11779. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  11780. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11781. }
  11782. case Expr::SizeOfPackExprClass:
  11783. case Expr::GNUNullExprClass:
  11784. case Expr::SourceLocExprClass:
  11785. return NoDiag();
  11786. case Expr::SubstNonTypeTemplateParmExprClass:
  11787. return
  11788. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  11789. case Expr::ConstantExprClass:
  11790. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  11791. case Expr::ParenExprClass:
  11792. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  11793. case Expr::GenericSelectionExprClass:
  11794. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  11795. case Expr::IntegerLiteralClass:
  11796. case Expr::FixedPointLiteralClass:
  11797. case Expr::CharacterLiteralClass:
  11798. case Expr::ObjCBoolLiteralExprClass:
  11799. case Expr::CXXBoolLiteralExprClass:
  11800. case Expr::CXXScalarValueInitExprClass:
  11801. case Expr::TypeTraitExprClass:
  11802. case Expr::ArrayTypeTraitExprClass:
  11803. case Expr::ExpressionTraitExprClass:
  11804. case Expr::CXXNoexceptExprClass:
  11805. return NoDiag();
  11806. case Expr::CallExprClass:
  11807. case Expr::CXXOperatorCallExprClass: {
  11808. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  11809. // constant expressions, but they can never be ICEs because an ICE cannot
  11810. // contain an operand of (pointer to) function type.
  11811. const CallExpr *CE = cast<CallExpr>(E);
  11812. if (CE->getBuiltinCallee())
  11813. return CheckEvalInICE(E, Ctx);
  11814. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11815. }
  11816. case Expr::DeclRefExprClass: {
  11817. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  11818. return NoDiag();
  11819. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  11820. if (Ctx.getLangOpts().CPlusPlus &&
  11821. D && IsConstNonVolatile(D->getType())) {
  11822. // Parameter variables are never constants. Without this check,
  11823. // getAnyInitializer() can find a default argument, which leads
  11824. // to chaos.
  11825. if (isa<ParmVarDecl>(D))
  11826. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11827. // C++ 7.1.5.1p2
  11828. // A variable of non-volatile const-qualified integral or enumeration
  11829. // type initialized by an ICE can be used in ICEs.
  11830. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  11831. if (!Dcl->getType()->isIntegralOrEnumerationType())
  11832. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11833. const VarDecl *VD;
  11834. // Look for a declaration of this variable that has an initializer, and
  11835. // check whether it is an ICE.
  11836. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  11837. return NoDiag();
  11838. else
  11839. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11840. }
  11841. }
  11842. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11843. }
  11844. case Expr::UnaryOperatorClass: {
  11845. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  11846. switch (Exp->getOpcode()) {
  11847. case UO_PostInc:
  11848. case UO_PostDec:
  11849. case UO_PreInc:
  11850. case UO_PreDec:
  11851. case UO_AddrOf:
  11852. case UO_Deref:
  11853. case UO_Coawait:
  11854. // C99 6.6/3 allows increment and decrement within unevaluated
  11855. // subexpressions of constant expressions, but they can never be ICEs
  11856. // because an ICE cannot contain an lvalue operand.
  11857. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11858. case UO_Extension:
  11859. case UO_LNot:
  11860. case UO_Plus:
  11861. case UO_Minus:
  11862. case UO_Not:
  11863. case UO_Real:
  11864. case UO_Imag:
  11865. return CheckICE(Exp->getSubExpr(), Ctx);
  11866. }
  11867. llvm_unreachable("invalid unary operator class");
  11868. }
  11869. case Expr::OffsetOfExprClass: {
  11870. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  11871. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  11872. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  11873. // compliance: we should warn earlier for offsetof expressions with
  11874. // array subscripts that aren't ICEs, and if the array subscripts
  11875. // are ICEs, the value of the offsetof must be an integer constant.
  11876. return CheckEvalInICE(E, Ctx);
  11877. }
  11878. case Expr::UnaryExprOrTypeTraitExprClass: {
  11879. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  11880. if ((Exp->getKind() == UETT_SizeOf) &&
  11881. Exp->getTypeOfArgument()->isVariableArrayType())
  11882. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11883. return NoDiag();
  11884. }
  11885. case Expr::BinaryOperatorClass: {
  11886. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  11887. switch (Exp->getOpcode()) {
  11888. case BO_PtrMemD:
  11889. case BO_PtrMemI:
  11890. case BO_Assign:
  11891. case BO_MulAssign:
  11892. case BO_DivAssign:
  11893. case BO_RemAssign:
  11894. case BO_AddAssign:
  11895. case BO_SubAssign:
  11896. case BO_ShlAssign:
  11897. case BO_ShrAssign:
  11898. case BO_AndAssign:
  11899. case BO_XorAssign:
  11900. case BO_OrAssign:
  11901. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  11902. // constant expressions, but they can never be ICEs because an ICE cannot
  11903. // contain an lvalue operand.
  11904. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11905. case BO_Mul:
  11906. case BO_Div:
  11907. case BO_Rem:
  11908. case BO_Add:
  11909. case BO_Sub:
  11910. case BO_Shl:
  11911. case BO_Shr:
  11912. case BO_LT:
  11913. case BO_GT:
  11914. case BO_LE:
  11915. case BO_GE:
  11916. case BO_EQ:
  11917. case BO_NE:
  11918. case BO_And:
  11919. case BO_Xor:
  11920. case BO_Or:
  11921. case BO_Comma:
  11922. case BO_Cmp: {
  11923. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  11924. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  11925. if (Exp->getOpcode() == BO_Div ||
  11926. Exp->getOpcode() == BO_Rem) {
  11927. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  11928. // we don't evaluate one.
  11929. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  11930. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  11931. if (REval == 0)
  11932. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11933. if (REval.isSigned() && REval.isAllOnesValue()) {
  11934. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  11935. if (LEval.isMinSignedValue())
  11936. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11937. }
  11938. }
  11939. }
  11940. if (Exp->getOpcode() == BO_Comma) {
  11941. if (Ctx.getLangOpts().C99) {
  11942. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  11943. // if it isn't evaluated.
  11944. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  11945. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11946. } else {
  11947. // In both C89 and C++, commas in ICEs are illegal.
  11948. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11949. }
  11950. }
  11951. return Worst(LHSResult, RHSResult);
  11952. }
  11953. case BO_LAnd:
  11954. case BO_LOr: {
  11955. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  11956. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  11957. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  11958. // Rare case where the RHS has a comma "side-effect"; we need
  11959. // to actually check the condition to see whether the side
  11960. // with the comma is evaluated.
  11961. if ((Exp->getOpcode() == BO_LAnd) !=
  11962. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  11963. return RHSResult;
  11964. return NoDiag();
  11965. }
  11966. return Worst(LHSResult, RHSResult);
  11967. }
  11968. }
  11969. llvm_unreachable("invalid binary operator kind");
  11970. }
  11971. case Expr::ImplicitCastExprClass:
  11972. case Expr::CStyleCastExprClass:
  11973. case Expr::CXXFunctionalCastExprClass:
  11974. case Expr::CXXStaticCastExprClass:
  11975. case Expr::CXXReinterpretCastExprClass:
  11976. case Expr::CXXConstCastExprClass:
  11977. case Expr::ObjCBridgedCastExprClass: {
  11978. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  11979. if (isa<ExplicitCastExpr>(E)) {
  11980. if (const FloatingLiteral *FL
  11981. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  11982. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  11983. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  11984. APSInt IgnoredVal(DestWidth, !DestSigned);
  11985. bool Ignored;
  11986. // If the value does not fit in the destination type, the behavior is
  11987. // undefined, so we are not required to treat it as a constant
  11988. // expression.
  11989. if (FL->getValue().convertToInteger(IgnoredVal,
  11990. llvm::APFloat::rmTowardZero,
  11991. &Ignored) & APFloat::opInvalidOp)
  11992. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11993. return NoDiag();
  11994. }
  11995. }
  11996. switch (cast<CastExpr>(E)->getCastKind()) {
  11997. case CK_LValueToRValue:
  11998. case CK_AtomicToNonAtomic:
  11999. case CK_NonAtomicToAtomic:
  12000. case CK_NoOp:
  12001. case CK_IntegralToBoolean:
  12002. case CK_IntegralCast:
  12003. return CheckICE(SubExpr, Ctx);
  12004. default:
  12005. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12006. }
  12007. }
  12008. case Expr::BinaryConditionalOperatorClass: {
  12009. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  12010. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  12011. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  12012. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12013. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  12014. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  12015. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  12016. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  12017. return FalseResult;
  12018. }
  12019. case Expr::ConditionalOperatorClass: {
  12020. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  12021. // If the condition (ignoring parens) is a __builtin_constant_p call,
  12022. // then only the true side is actually considered in an integer constant
  12023. // expression, and it is fully evaluated. This is an important GNU
  12024. // extension. See GCC PR38377 for discussion.
  12025. if (const CallExpr *CallCE
  12026. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  12027. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  12028. return CheckEvalInICE(E, Ctx);
  12029. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  12030. if (CondResult.Kind == IK_NotICE)
  12031. return CondResult;
  12032. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  12033. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12034. if (TrueResult.Kind == IK_NotICE)
  12035. return TrueResult;
  12036. if (FalseResult.Kind == IK_NotICE)
  12037. return FalseResult;
  12038. if (CondResult.Kind == IK_ICEIfUnevaluated)
  12039. return CondResult;
  12040. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  12041. return NoDiag();
  12042. // Rare case where the diagnostics depend on which side is evaluated
  12043. // Note that if we get here, CondResult is 0, and at least one of
  12044. // TrueResult and FalseResult is non-zero.
  12045. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  12046. return FalseResult;
  12047. return TrueResult;
  12048. }
  12049. case Expr::CXXDefaultArgExprClass:
  12050. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  12051. case Expr::CXXDefaultInitExprClass:
  12052. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  12053. case Expr::ChooseExprClass: {
  12054. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  12055. }
  12056. case Expr::BuiltinBitCastExprClass: {
  12057. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  12058. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12059. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  12060. }
  12061. }
  12062. llvm_unreachable("Invalid StmtClass!");
  12063. }
  12064. /// Evaluate an expression as a C++11 integral constant expression.
  12065. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  12066. const Expr *E,
  12067. llvm::APSInt *Value,
  12068. SourceLocation *Loc) {
  12069. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12070. if (Loc) *Loc = E->getExprLoc();
  12071. return false;
  12072. }
  12073. APValue Result;
  12074. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  12075. return false;
  12076. if (!Result.isInt()) {
  12077. if (Loc) *Loc = E->getExprLoc();
  12078. return false;
  12079. }
  12080. if (Value) *Value = Result.getInt();
  12081. return true;
  12082. }
  12083. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  12084. SourceLocation *Loc) const {
  12085. assert(!isValueDependent() &&
  12086. "Expression evaluator can't be called on a dependent expression.");
  12087. if (Ctx.getLangOpts().CPlusPlus11)
  12088. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  12089. ICEDiag D = CheckICE(this, Ctx);
  12090. if (D.Kind != IK_ICE) {
  12091. if (Loc) *Loc = D.Loc;
  12092. return false;
  12093. }
  12094. return true;
  12095. }
  12096. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  12097. SourceLocation *Loc, bool isEvaluated) const {
  12098. assert(!isValueDependent() &&
  12099. "Expression evaluator can't be called on a dependent expression.");
  12100. if (Ctx.getLangOpts().CPlusPlus11)
  12101. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  12102. if (!isIntegerConstantExpr(Ctx, Loc))
  12103. return false;
  12104. // The only possible side-effects here are due to UB discovered in the
  12105. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  12106. // required to treat the expression as an ICE, so we produce the folded
  12107. // value.
  12108. EvalResult ExprResult;
  12109. Expr::EvalStatus Status;
  12110. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  12111. Info.InConstantContext = true;
  12112. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  12113. llvm_unreachable("ICE cannot be evaluated!");
  12114. Value = ExprResult.Val.getInt();
  12115. return true;
  12116. }
  12117. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  12118. assert(!isValueDependent() &&
  12119. "Expression evaluator can't be called on a dependent expression.");
  12120. return CheckICE(this, Ctx).Kind == IK_ICE;
  12121. }
  12122. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  12123. SourceLocation *Loc) const {
  12124. assert(!isValueDependent() &&
  12125. "Expression evaluator can't be called on a dependent expression.");
  12126. // We support this checking in C++98 mode in order to diagnose compatibility
  12127. // issues.
  12128. assert(Ctx.getLangOpts().CPlusPlus);
  12129. // Build evaluation settings.
  12130. Expr::EvalStatus Status;
  12131. SmallVector<PartialDiagnosticAt, 8> Diags;
  12132. Status.Diag = &Diags;
  12133. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12134. APValue Scratch;
  12135. bool IsConstExpr =
  12136. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  12137. // FIXME: We don't produce a diagnostic for this, but the callers that
  12138. // call us on arbitrary full-expressions should generally not care.
  12139. Info.discardCleanups() && !Status.HasSideEffects;
  12140. if (!Diags.empty()) {
  12141. IsConstExpr = false;
  12142. if (Loc) *Loc = Diags[0].first;
  12143. } else if (!IsConstExpr) {
  12144. // FIXME: This shouldn't happen.
  12145. if (Loc) *Loc = getExprLoc();
  12146. }
  12147. return IsConstExpr;
  12148. }
  12149. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  12150. const FunctionDecl *Callee,
  12151. ArrayRef<const Expr*> Args,
  12152. const Expr *This) const {
  12153. assert(!isValueDependent() &&
  12154. "Expression evaluator can't be called on a dependent expression.");
  12155. Expr::EvalStatus Status;
  12156. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  12157. Info.InConstantContext = true;
  12158. LValue ThisVal;
  12159. const LValue *ThisPtr = nullptr;
  12160. if (This) {
  12161. #ifndef NDEBUG
  12162. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  12163. assert(MD && "Don't provide `this` for non-methods.");
  12164. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  12165. #endif
  12166. if (EvaluateObjectArgument(Info, This, ThisVal))
  12167. ThisPtr = &ThisVal;
  12168. if (Info.EvalStatus.HasSideEffects)
  12169. return false;
  12170. }
  12171. ArgVector ArgValues(Args.size());
  12172. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  12173. I != E; ++I) {
  12174. if ((*I)->isValueDependent() ||
  12175. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  12176. // If evaluation fails, throw away the argument entirely.
  12177. ArgValues[I - Args.begin()] = APValue();
  12178. if (Info.EvalStatus.HasSideEffects)
  12179. return false;
  12180. }
  12181. // Build fake call to Callee.
  12182. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  12183. ArgValues.data());
  12184. return Evaluate(Value, Info, this) && Info.discardCleanups() &&
  12185. !Info.EvalStatus.HasSideEffects;
  12186. }
  12187. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  12188. SmallVectorImpl<
  12189. PartialDiagnosticAt> &Diags) {
  12190. // FIXME: It would be useful to check constexpr function templates, but at the
  12191. // moment the constant expression evaluator cannot cope with the non-rigorous
  12192. // ASTs which we build for dependent expressions.
  12193. if (FD->isDependentContext())
  12194. return true;
  12195. Expr::EvalStatus Status;
  12196. Status.Diag = &Diags;
  12197. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  12198. Info.InConstantContext = true;
  12199. Info.CheckingPotentialConstantExpression = true;
  12200. // The constexpr VM attempts to compile all methods to bytecode here.
  12201. if (Info.EnableNewConstInterp) {
  12202. auto &InterpCtx = Info.Ctx.getInterpContext();
  12203. switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
  12204. case interp::InterpResult::Success:
  12205. case interp::InterpResult::Fail:
  12206. return Diags.empty();
  12207. case interp::InterpResult::Bail:
  12208. break;
  12209. }
  12210. }
  12211. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  12212. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  12213. // Fabricate an arbitrary expression on the stack and pretend that it
  12214. // is a temporary being used as the 'this' pointer.
  12215. LValue This;
  12216. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  12217. This.set({&VIE, Info.CurrentCall->Index});
  12218. ArrayRef<const Expr*> Args;
  12219. APValue Scratch;
  12220. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  12221. // Evaluate the call as a constant initializer, to allow the construction
  12222. // of objects of non-literal types.
  12223. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  12224. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  12225. } else {
  12226. SourceLocation Loc = FD->getLocation();
  12227. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  12228. Args, FD->getBody(), Info, Scratch, nullptr);
  12229. }
  12230. return Diags.empty();
  12231. }
  12232. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  12233. const FunctionDecl *FD,
  12234. SmallVectorImpl<
  12235. PartialDiagnosticAt> &Diags) {
  12236. assert(!E->isValueDependent() &&
  12237. "Expression evaluator can't be called on a dependent expression.");
  12238. Expr::EvalStatus Status;
  12239. Status.Diag = &Diags;
  12240. EvalInfo Info(FD->getASTContext(), Status,
  12241. EvalInfo::EM_ConstantExpressionUnevaluated);
  12242. Info.InConstantContext = true;
  12243. Info.CheckingPotentialConstantExpression = true;
  12244. // Fabricate a call stack frame to give the arguments a plausible cover story.
  12245. ArrayRef<const Expr*> Args;
  12246. ArgVector ArgValues(0);
  12247. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  12248. (void)Success;
  12249. assert(Success &&
  12250. "Failed to set up arguments for potential constant evaluation");
  12251. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  12252. APValue ResultScratch;
  12253. Evaluate(ResultScratch, Info, E);
  12254. return Diags.empty();
  12255. }
  12256. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  12257. unsigned Type) const {
  12258. if (!getType()->isPointerType())
  12259. return false;
  12260. Expr::EvalStatus Status;
  12261. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  12262. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  12263. }