ExprConstant.cpp 471 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241
  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 "clang/AST/APValue.h"
  35. #include "clang/AST/ASTContext.h"
  36. #include "clang/AST/ASTDiagnostic.h"
  37. #include "clang/AST/ASTLambda.h"
  38. #include "clang/AST/CharUnits.h"
  39. #include "clang/AST/CurrentSourceLocExprScope.h"
  40. #include "clang/AST/CXXInheritance.h"
  41. #include "clang/AST/Expr.h"
  42. #include "clang/AST/OSLog.h"
  43. #include "clang/AST/RecordLayout.h"
  44. #include "clang/AST/StmtVisitor.h"
  45. #include "clang/AST/TypeLoc.h"
  46. #include "clang/Basic/Builtins.h"
  47. #include "clang/Basic/FixedPoint.h"
  48. #include "clang/Basic/TargetInfo.h"
  49. #include "llvm/ADT/Optional.h"
  50. #include "llvm/ADT/SmallBitVector.h"
  51. #include "llvm/Support/SaveAndRestore.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include <cstring>
  54. #include <functional>
  55. #define DEBUG_TYPE "exprconstant"
  56. using namespace clang;
  57. using llvm::APInt;
  58. using llvm::APSInt;
  59. using llvm::APFloat;
  60. using llvm::Optional;
  61. static bool IsGlobalLValue(APValue::LValueBase B);
  62. namespace {
  63. struct LValue;
  64. struct CallStackFrame;
  65. struct EvalInfo;
  66. using SourceLocExprScopeGuard =
  67. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  68. static QualType getType(APValue::LValueBase B) {
  69. if (!B) return QualType();
  70. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  71. // FIXME: It's unclear where we're supposed to take the type from, and
  72. // this actually matters for arrays of unknown bound. Eg:
  73. //
  74. // extern int arr[]; void f() { extern int arr[3]; };
  75. // constexpr int *p = &arr[1]; // valid?
  76. //
  77. // For now, we take the array bound from the most recent declaration.
  78. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  79. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  80. QualType T = Redecl->getType();
  81. if (!T->isIncompleteArrayType())
  82. return T;
  83. }
  84. return D->getType();
  85. }
  86. if (B.is<TypeInfoLValue>())
  87. return B.getTypeInfoType();
  88. const Expr *Base = B.get<const Expr*>();
  89. // For a materialized temporary, the type of the temporary we materialized
  90. // may not be the type of the expression.
  91. if (const MaterializeTemporaryExpr *MTE =
  92. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  93. SmallVector<const Expr *, 2> CommaLHSs;
  94. SmallVector<SubobjectAdjustment, 2> Adjustments;
  95. const Expr *Temp = MTE->GetTemporaryExpr();
  96. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  97. Adjustments);
  98. // Keep any cv-qualifiers from the reference if we generated a temporary
  99. // for it directly. Otherwise use the type after adjustment.
  100. if (!Adjustments.empty())
  101. return Inner->getType();
  102. }
  103. return Base->getType();
  104. }
  105. /// Get an LValue path entry, which is known to not be an array index, as a
  106. /// field declaration.
  107. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  108. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  109. }
  110. /// Get an LValue path entry, which is known to not be an array index, as a
  111. /// base class declaration.
  112. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  113. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  114. }
  115. /// Determine whether this LValue path entry for a base class names a virtual
  116. /// base class.
  117. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  118. return E.getAsBaseOrMember().getInt();
  119. }
  120. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  121. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  122. const FunctionDecl *Callee = CE->getDirectCallee();
  123. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  124. }
  125. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  126. /// This will look through a single cast.
  127. ///
  128. /// Returns null if we couldn't unwrap a function with alloc_size.
  129. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  130. if (!E->getType()->isPointerType())
  131. return nullptr;
  132. E = E->IgnoreParens();
  133. // If we're doing a variable assignment from e.g. malloc(N), there will
  134. // probably be a cast of some kind. In exotic cases, we might also see a
  135. // top-level ExprWithCleanups. Ignore them either way.
  136. if (const auto *FE = dyn_cast<FullExpr>(E))
  137. E = FE->getSubExpr()->IgnoreParens();
  138. if (const auto *Cast = dyn_cast<CastExpr>(E))
  139. E = Cast->getSubExpr()->IgnoreParens();
  140. if (const auto *CE = dyn_cast<CallExpr>(E))
  141. return getAllocSizeAttr(CE) ? CE : nullptr;
  142. return nullptr;
  143. }
  144. /// Determines whether or not the given Base contains a call to a function
  145. /// with the alloc_size attribute.
  146. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  147. const auto *E = Base.dyn_cast<const Expr *>();
  148. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  149. }
  150. /// The bound to claim that an array of unknown bound has.
  151. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  152. /// to an arbitrary value that's likely to loudly break things if it's used.
  153. static const uint64_t AssumedSizeForUnsizedArray =
  154. std::numeric_limits<uint64_t>::max() / 2;
  155. /// Determines if an LValue with the given LValueBase will have an unsized
  156. /// array in its designator.
  157. /// Find the path length and type of the most-derived subobject in the given
  158. /// path, and find the size of the containing array, if any.
  159. static unsigned
  160. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  161. ArrayRef<APValue::LValuePathEntry> Path,
  162. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  163. bool &FirstEntryIsUnsizedArray) {
  164. // This only accepts LValueBases from APValues, and APValues don't support
  165. // arrays that lack size info.
  166. assert(!isBaseAnAllocSizeCall(Base) &&
  167. "Unsized arrays shouldn't appear here");
  168. unsigned MostDerivedLength = 0;
  169. Type = getType(Base);
  170. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  171. if (Type->isArrayType()) {
  172. const ArrayType *AT = Ctx.getAsArrayType(Type);
  173. Type = AT->getElementType();
  174. MostDerivedLength = I + 1;
  175. IsArray = true;
  176. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  177. ArraySize = CAT->getSize().getZExtValue();
  178. } else {
  179. assert(I == 0 && "unexpected unsized array designator");
  180. FirstEntryIsUnsizedArray = true;
  181. ArraySize = AssumedSizeForUnsizedArray;
  182. }
  183. } else if (Type->isAnyComplexType()) {
  184. const ComplexType *CT = Type->castAs<ComplexType>();
  185. Type = CT->getElementType();
  186. ArraySize = 2;
  187. MostDerivedLength = I + 1;
  188. IsArray = true;
  189. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  190. Type = FD->getType();
  191. ArraySize = 0;
  192. MostDerivedLength = I + 1;
  193. IsArray = false;
  194. } else {
  195. // Path[I] describes a base class.
  196. ArraySize = 0;
  197. IsArray = false;
  198. }
  199. }
  200. return MostDerivedLength;
  201. }
  202. // The order of this enum is important for diagnostics.
  203. enum CheckSubobjectKind {
  204. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  205. CSK_Real, CSK_Imag
  206. };
  207. /// A path from a glvalue to a subobject of that glvalue.
  208. struct SubobjectDesignator {
  209. /// True if the subobject was named in a manner not supported by C++11. Such
  210. /// lvalues can still be folded, but they are not core constant expressions
  211. /// and we cannot perform lvalue-to-rvalue conversions on them.
  212. unsigned Invalid : 1;
  213. /// Is this a pointer one past the end of an object?
  214. unsigned IsOnePastTheEnd : 1;
  215. /// Indicator of whether the first entry is an unsized array.
  216. unsigned FirstEntryIsAnUnsizedArray : 1;
  217. /// Indicator of whether the most-derived object is an array element.
  218. unsigned MostDerivedIsArrayElement : 1;
  219. /// The length of the path to the most-derived object of which this is a
  220. /// subobject.
  221. unsigned MostDerivedPathLength : 28;
  222. /// The size of the array of which the most-derived object is an element.
  223. /// This will always be 0 if the most-derived object is not an array
  224. /// element. 0 is not an indicator of whether or not the most-derived object
  225. /// is an array, however, because 0-length arrays are allowed.
  226. ///
  227. /// If the current array is an unsized array, the value of this is
  228. /// undefined.
  229. uint64_t MostDerivedArraySize;
  230. /// The type of the most derived object referred to by this address.
  231. QualType MostDerivedType;
  232. typedef APValue::LValuePathEntry PathEntry;
  233. /// The entries on the path from the glvalue to the designated subobject.
  234. SmallVector<PathEntry, 8> Entries;
  235. SubobjectDesignator() : Invalid(true) {}
  236. explicit SubobjectDesignator(QualType T)
  237. : Invalid(false), IsOnePastTheEnd(false),
  238. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  239. MostDerivedPathLength(0), MostDerivedArraySize(0),
  240. MostDerivedType(T) {}
  241. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  242. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  243. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  244. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  245. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  246. if (!Invalid) {
  247. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  248. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  249. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  250. if (V.getLValueBase()) {
  251. bool IsArray = false;
  252. bool FirstIsUnsizedArray = false;
  253. MostDerivedPathLength = findMostDerivedSubobject(
  254. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  255. MostDerivedType, IsArray, FirstIsUnsizedArray);
  256. MostDerivedIsArrayElement = IsArray;
  257. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  258. }
  259. }
  260. }
  261. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  262. unsigned NewLength) {
  263. if (Invalid)
  264. return;
  265. assert(Base && "cannot truncate path for null pointer");
  266. assert(NewLength <= Entries.size() && "not a truncation");
  267. if (NewLength == Entries.size())
  268. return;
  269. Entries.resize(NewLength);
  270. bool IsArray = false;
  271. bool FirstIsUnsizedArray = false;
  272. MostDerivedPathLength = findMostDerivedSubobject(
  273. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  274. FirstIsUnsizedArray);
  275. MostDerivedIsArrayElement = IsArray;
  276. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  277. }
  278. void setInvalid() {
  279. Invalid = true;
  280. Entries.clear();
  281. }
  282. /// Determine whether the most derived subobject is an array without a
  283. /// known bound.
  284. bool isMostDerivedAnUnsizedArray() const {
  285. assert(!Invalid && "Calling this makes no sense on invalid designators");
  286. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  287. }
  288. /// Determine what the most derived array's size is. Results in an assertion
  289. /// failure if the most derived array lacks a size.
  290. uint64_t getMostDerivedArraySize() const {
  291. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  292. return MostDerivedArraySize;
  293. }
  294. /// Determine whether this is a one-past-the-end pointer.
  295. bool isOnePastTheEnd() const {
  296. assert(!Invalid);
  297. if (IsOnePastTheEnd)
  298. return true;
  299. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  300. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  301. MostDerivedArraySize)
  302. return true;
  303. return false;
  304. }
  305. /// Get the range of valid index adjustments in the form
  306. /// {maximum value that can be subtracted from this pointer,
  307. /// maximum value that can be added to this pointer}
  308. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  309. if (Invalid || isMostDerivedAnUnsizedArray())
  310. return {0, 0};
  311. // [expr.add]p4: For the purposes of these operators, a pointer to a
  312. // nonarray object behaves the same as a pointer to the first element of
  313. // an array of length one with the type of the object as its element type.
  314. bool IsArray = MostDerivedPathLength == Entries.size() &&
  315. MostDerivedIsArrayElement;
  316. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  317. : (uint64_t)IsOnePastTheEnd;
  318. uint64_t ArraySize =
  319. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  320. return {ArrayIndex, ArraySize - ArrayIndex};
  321. }
  322. /// Check that this refers to a valid subobject.
  323. bool isValidSubobject() const {
  324. if (Invalid)
  325. return false;
  326. return !isOnePastTheEnd();
  327. }
  328. /// Check that this refers to a valid subobject, and if not, produce a
  329. /// relevant diagnostic and set the designator as invalid.
  330. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  331. /// Get the type of the designated object.
  332. QualType getType(ASTContext &Ctx) const {
  333. assert(!Invalid && "invalid designator has no subobject type");
  334. return MostDerivedPathLength == Entries.size()
  335. ? MostDerivedType
  336. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  337. }
  338. /// Update this designator to refer to the first element within this array.
  339. void addArrayUnchecked(const ConstantArrayType *CAT) {
  340. Entries.push_back(PathEntry::ArrayIndex(0));
  341. // This is a most-derived object.
  342. MostDerivedType = CAT->getElementType();
  343. MostDerivedIsArrayElement = true;
  344. MostDerivedArraySize = CAT->getSize().getZExtValue();
  345. MostDerivedPathLength = Entries.size();
  346. }
  347. /// Update this designator to refer to the first element within the array of
  348. /// elements of type T. This is an array of unknown size.
  349. void addUnsizedArrayUnchecked(QualType ElemTy) {
  350. Entries.push_back(PathEntry::ArrayIndex(0));
  351. MostDerivedType = ElemTy;
  352. MostDerivedIsArrayElement = true;
  353. // The value in MostDerivedArraySize is undefined in this case. So, set it
  354. // to an arbitrary value that's likely to loudly break things if it's
  355. // used.
  356. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  357. MostDerivedPathLength = Entries.size();
  358. }
  359. /// Update this designator to refer to the given base or member of this
  360. /// object.
  361. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  362. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  363. // If this isn't a base class, it's a new most-derived object.
  364. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  365. MostDerivedType = FD->getType();
  366. MostDerivedIsArrayElement = false;
  367. MostDerivedArraySize = 0;
  368. MostDerivedPathLength = Entries.size();
  369. }
  370. }
  371. /// Update this designator to refer to the given complex component.
  372. void addComplexUnchecked(QualType EltTy, bool Imag) {
  373. Entries.push_back(PathEntry::ArrayIndex(Imag));
  374. // This is technically a most-derived object, though in practice this
  375. // is unlikely to matter.
  376. MostDerivedType = EltTy;
  377. MostDerivedIsArrayElement = true;
  378. MostDerivedArraySize = 2;
  379. MostDerivedPathLength = Entries.size();
  380. }
  381. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  382. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  383. const APSInt &N);
  384. /// Add N to the address of this subobject.
  385. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  386. if (Invalid || !N) return;
  387. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  388. if (isMostDerivedAnUnsizedArray()) {
  389. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  390. // Can't verify -- trust that the user is doing the right thing (or if
  391. // not, trust that the caller will catch the bad behavior).
  392. // FIXME: Should we reject if this overflows, at least?
  393. Entries.back() = PathEntry::ArrayIndex(
  394. Entries.back().getAsArrayIndex() + TruncatedN);
  395. return;
  396. }
  397. // [expr.add]p4: For the purposes of these operators, a pointer to a
  398. // nonarray object behaves the same as a pointer to the first element of
  399. // an array of length one with the type of the object as its element type.
  400. bool IsArray = MostDerivedPathLength == Entries.size() &&
  401. MostDerivedIsArrayElement;
  402. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  403. : (uint64_t)IsOnePastTheEnd;
  404. uint64_t ArraySize =
  405. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  406. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  407. // Calculate the actual index in a wide enough type, so we can include
  408. // it in the note.
  409. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  410. (llvm::APInt&)N += ArrayIndex;
  411. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  412. diagnosePointerArithmetic(Info, E, N);
  413. setInvalid();
  414. return;
  415. }
  416. ArrayIndex += TruncatedN;
  417. assert(ArrayIndex <= ArraySize &&
  418. "bounds check succeeded for out-of-bounds index");
  419. if (IsArray)
  420. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  421. else
  422. IsOnePastTheEnd = (ArrayIndex != 0);
  423. }
  424. };
  425. /// A stack frame in the constexpr call stack.
  426. struct CallStackFrame {
  427. EvalInfo &Info;
  428. /// Parent - The caller of this stack frame.
  429. CallStackFrame *Caller;
  430. /// Callee - The function which was called.
  431. const FunctionDecl *Callee;
  432. /// This - The binding for the this pointer in this call, if any.
  433. const LValue *This;
  434. /// Arguments - Parameter bindings for this function call, indexed by
  435. /// parameters' function scope indices.
  436. APValue *Arguments;
  437. /// Source location information about the default argument or default
  438. /// initializer expression we're evaluating, if any.
  439. CurrentSourceLocExprScope CurSourceLocExprScope;
  440. // Note that we intentionally use std::map here so that references to
  441. // values are stable.
  442. typedef std::pair<const void *, unsigned> MapKeyTy;
  443. typedef std::map<MapKeyTy, APValue> MapTy;
  444. /// Temporaries - Temporary lvalues materialized within this stack frame.
  445. MapTy Temporaries;
  446. /// CallLoc - The location of the call expression for this call.
  447. SourceLocation CallLoc;
  448. /// Index - The call index of this call.
  449. unsigned Index;
  450. /// The stack of integers for tracking version numbers for temporaries.
  451. SmallVector<unsigned, 2> TempVersionStack = {1};
  452. unsigned CurTempVersion = TempVersionStack.back();
  453. unsigned getTempVersion() const { return TempVersionStack.back(); }
  454. void pushTempVersion() {
  455. TempVersionStack.push_back(++CurTempVersion);
  456. }
  457. void popTempVersion() {
  458. TempVersionStack.pop_back();
  459. }
  460. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  461. // on the overall stack usage of deeply-recursing constexpr evaluations.
  462. // (We should cache this map rather than recomputing it repeatedly.)
  463. // But let's try this and see how it goes; we can look into caching the map
  464. // as a later change.
  465. /// LambdaCaptureFields - Mapping from captured variables/this to
  466. /// corresponding data members in the closure class.
  467. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  468. FieldDecl *LambdaThisCaptureField;
  469. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  470. const FunctionDecl *Callee, const LValue *This,
  471. APValue *Arguments);
  472. ~CallStackFrame();
  473. // Return the temporary for Key whose version number is Version.
  474. APValue *getTemporary(const void *Key, unsigned Version) {
  475. MapKeyTy KV(Key, Version);
  476. auto LB = Temporaries.lower_bound(KV);
  477. if (LB != Temporaries.end() && LB->first == KV)
  478. return &LB->second;
  479. // Pair (Key,Version) wasn't found in the map. Check that no elements
  480. // in the map have 'Key' as their key.
  481. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  482. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  483. "Element with key 'Key' found in map");
  484. return nullptr;
  485. }
  486. // Return the current temporary for Key in the map.
  487. APValue *getCurrentTemporary(const void *Key) {
  488. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  489. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  490. return &std::prev(UB)->second;
  491. return nullptr;
  492. }
  493. // Return the version number of the current temporary for Key.
  494. unsigned getCurrentTemporaryVersion(const void *Key) const {
  495. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  496. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  497. return std::prev(UB)->first.second;
  498. return 0;
  499. }
  500. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  501. };
  502. /// Temporarily override 'this'.
  503. class ThisOverrideRAII {
  504. public:
  505. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  506. : Frame(Frame), OldThis(Frame.This) {
  507. if (Enable)
  508. Frame.This = NewThis;
  509. }
  510. ~ThisOverrideRAII() {
  511. Frame.This = OldThis;
  512. }
  513. private:
  514. CallStackFrame &Frame;
  515. const LValue *OldThis;
  516. };
  517. /// A partial diagnostic which we might know in advance that we are not going
  518. /// to emit.
  519. class OptionalDiagnostic {
  520. PartialDiagnostic *Diag;
  521. public:
  522. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  523. : Diag(Diag) {}
  524. template<typename T>
  525. OptionalDiagnostic &operator<<(const T &v) {
  526. if (Diag)
  527. *Diag << v;
  528. return *this;
  529. }
  530. OptionalDiagnostic &operator<<(const APSInt &I) {
  531. if (Diag) {
  532. SmallVector<char, 32> Buffer;
  533. I.toString(Buffer);
  534. *Diag << StringRef(Buffer.data(), Buffer.size());
  535. }
  536. return *this;
  537. }
  538. OptionalDiagnostic &operator<<(const APFloat &F) {
  539. if (Diag) {
  540. // FIXME: Force the precision of the source value down so we don't
  541. // print digits which are usually useless (we don't really care here if
  542. // we truncate a digit by accident in edge cases). Ideally,
  543. // APFloat::toString would automatically print the shortest
  544. // representation which rounds to the correct value, but it's a bit
  545. // tricky to implement.
  546. unsigned precision =
  547. llvm::APFloat::semanticsPrecision(F.getSemantics());
  548. precision = (precision * 59 + 195) / 196;
  549. SmallVector<char, 32> Buffer;
  550. F.toString(Buffer, precision);
  551. *Diag << StringRef(Buffer.data(), Buffer.size());
  552. }
  553. return *this;
  554. }
  555. OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
  556. if (Diag) {
  557. SmallVector<char, 32> Buffer;
  558. FX.toString(Buffer);
  559. *Diag << StringRef(Buffer.data(), Buffer.size());
  560. }
  561. return *this;
  562. }
  563. };
  564. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  565. class Cleanup {
  566. llvm::PointerIntPair<APValue*, 1, bool> Value;
  567. public:
  568. Cleanup(APValue *Val, bool IsLifetimeExtended)
  569. : Value(Val, IsLifetimeExtended) {}
  570. bool isLifetimeExtended() const { return Value.getInt(); }
  571. void endLifetime() {
  572. *Value.getPointer() = APValue();
  573. }
  574. };
  575. /// A reference to an object whose construction we are currently evaluating.
  576. struct ObjectUnderConstruction {
  577. APValue::LValueBase Base;
  578. ArrayRef<APValue::LValuePathEntry> Path;
  579. friend bool operator==(const ObjectUnderConstruction &LHS,
  580. const ObjectUnderConstruction &RHS) {
  581. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  582. }
  583. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  584. return llvm::hash_combine(Obj.Base, Obj.Path);
  585. }
  586. };
  587. enum class ConstructionPhase { None, Bases, AfterBases };
  588. }
  589. namespace llvm {
  590. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  591. using Base = DenseMapInfo<APValue::LValueBase>;
  592. static ObjectUnderConstruction getEmptyKey() {
  593. return {Base::getEmptyKey(), {}}; }
  594. static ObjectUnderConstruction getTombstoneKey() {
  595. return {Base::getTombstoneKey(), {}};
  596. }
  597. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  598. return hash_value(Object);
  599. }
  600. static bool isEqual(const ObjectUnderConstruction &LHS,
  601. const ObjectUnderConstruction &RHS) {
  602. return LHS == RHS;
  603. }
  604. };
  605. }
  606. namespace {
  607. /// EvalInfo - This is a private struct used by the evaluator to capture
  608. /// information about a subexpression as it is folded. It retains information
  609. /// about the AST context, but also maintains information about the folded
  610. /// expression.
  611. ///
  612. /// If an expression could be evaluated, it is still possible it is not a C
  613. /// "integer constant expression" or constant expression. If not, this struct
  614. /// captures information about how and why not.
  615. ///
  616. /// One bit of information passed *into* the request for constant folding
  617. /// indicates whether the subexpression is "evaluated" or not according to C
  618. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  619. /// evaluate the expression regardless of what the RHS is, but C only allows
  620. /// certain things in certain situations.
  621. struct EvalInfo {
  622. ASTContext &Ctx;
  623. /// EvalStatus - Contains information about the evaluation.
  624. Expr::EvalStatus &EvalStatus;
  625. /// CurrentCall - The top of the constexpr call stack.
  626. CallStackFrame *CurrentCall;
  627. /// CallStackDepth - The number of calls in the call stack right now.
  628. unsigned CallStackDepth;
  629. /// NextCallIndex - The next call index to assign.
  630. unsigned NextCallIndex;
  631. /// StepsLeft - The remaining number of evaluation steps we're permitted
  632. /// to perform. This is essentially a limit for the number of statements
  633. /// we will evaluate.
  634. unsigned StepsLeft;
  635. /// BottomFrame - The frame in which evaluation started. This must be
  636. /// initialized after CurrentCall and CallStackDepth.
  637. CallStackFrame BottomFrame;
  638. /// A stack of values whose lifetimes end at the end of some surrounding
  639. /// evaluation frame.
  640. llvm::SmallVector<Cleanup, 16> CleanupStack;
  641. /// EvaluatingDecl - This is the declaration whose initializer is being
  642. /// evaluated, if any.
  643. APValue::LValueBase EvaluatingDecl;
  644. /// EvaluatingDeclValue - This is the value being constructed for the
  645. /// declaration whose initializer is being evaluated, if any.
  646. APValue *EvaluatingDeclValue;
  647. /// Set of objects that are currently being constructed.
  648. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  649. ObjectsUnderConstruction;
  650. struct EvaluatingConstructorRAII {
  651. EvalInfo &EI;
  652. ObjectUnderConstruction Object;
  653. bool DidInsert;
  654. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  655. bool HasBases)
  656. : EI(EI), Object(Object) {
  657. DidInsert =
  658. EI.ObjectsUnderConstruction
  659. .insert({Object, HasBases ? ConstructionPhase::Bases
  660. : ConstructionPhase::AfterBases})
  661. .second;
  662. }
  663. void finishedConstructingBases() {
  664. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  665. }
  666. ~EvaluatingConstructorRAII() {
  667. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  668. }
  669. };
  670. ConstructionPhase
  671. isEvaluatingConstructor(APValue::LValueBase Base,
  672. ArrayRef<APValue::LValuePathEntry> Path) {
  673. return ObjectsUnderConstruction.lookup({Base, Path});
  674. }
  675. /// If we're currently speculatively evaluating, the outermost call stack
  676. /// depth at which we can mutate state, otherwise 0.
  677. unsigned SpeculativeEvaluationDepth = 0;
  678. /// The current array initialization index, if we're performing array
  679. /// initialization.
  680. uint64_t ArrayInitIndex = -1;
  681. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  682. /// notes attached to it will also be stored, otherwise they will not be.
  683. bool HasActiveDiagnostic;
  684. /// Have we emitted a diagnostic explaining why we couldn't constant
  685. /// fold (not just why it's not strictly a constant expression)?
  686. bool HasFoldFailureDiagnostic;
  687. /// Whether or not we're in a context where the front end requires a
  688. /// constant value.
  689. bool InConstantContext;
  690. enum EvaluationMode {
  691. /// Evaluate as a constant expression. Stop if we find that the expression
  692. /// is not a constant expression.
  693. EM_ConstantExpression,
  694. /// Evaluate as a potential constant expression. Keep going if we hit a
  695. /// construct that we can't evaluate yet (because we don't yet know the
  696. /// value of something) but stop if we hit something that could never be
  697. /// a constant expression.
  698. EM_PotentialConstantExpression,
  699. /// Fold the expression to a constant. Stop if we hit a side-effect that
  700. /// we can't model.
  701. EM_ConstantFold,
  702. /// Evaluate the expression looking for integer overflow and similar
  703. /// issues. Don't worry about side-effects, and try to visit all
  704. /// subexpressions.
  705. EM_EvaluateForOverflow,
  706. /// Evaluate in any way we know how. Don't worry about side-effects that
  707. /// can't be modeled.
  708. EM_IgnoreSideEffects,
  709. /// Evaluate as a constant expression. Stop if we find that the expression
  710. /// is not a constant expression. Some expressions can be retried in the
  711. /// optimizer if we don't constant fold them here, but in an unevaluated
  712. /// context we try to fold them immediately since the optimizer never
  713. /// gets a chance to look at it.
  714. EM_ConstantExpressionUnevaluated,
  715. /// Evaluate as a potential constant expression. Keep going if we hit a
  716. /// construct that we can't evaluate yet (because we don't yet know the
  717. /// value of something) but stop if we hit something that could never be
  718. /// a constant expression. Some expressions can be retried in the
  719. /// optimizer if we don't constant fold them here, but in an unevaluated
  720. /// context we try to fold them immediately since the optimizer never
  721. /// gets a chance to look at it.
  722. EM_PotentialConstantExpressionUnevaluated,
  723. } EvalMode;
  724. /// Are we checking whether the expression is a potential constant
  725. /// expression?
  726. bool checkingPotentialConstantExpression() const {
  727. return EvalMode == EM_PotentialConstantExpression ||
  728. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  729. }
  730. /// Are we checking an expression for overflow?
  731. // FIXME: We should check for any kind of undefined or suspicious behavior
  732. // in such constructs, not just overflow.
  733. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  734. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  735. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  736. CallStackDepth(0), NextCallIndex(1),
  737. StepsLeft(getLangOpts().ConstexprStepLimit),
  738. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  739. EvaluatingDecl((const ValueDecl *)nullptr),
  740. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  741. HasFoldFailureDiagnostic(false),
  742. InConstantContext(false), EvalMode(Mode) {}
  743. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  744. EvaluatingDecl = Base;
  745. EvaluatingDeclValue = &Value;
  746. }
  747. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  748. bool CheckCallLimit(SourceLocation Loc) {
  749. // Don't perform any constexpr calls (other than the call we're checking)
  750. // when checking a potential constant expression.
  751. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  752. return false;
  753. if (NextCallIndex == 0) {
  754. // NextCallIndex has wrapped around.
  755. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  756. return false;
  757. }
  758. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  759. return true;
  760. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  761. << getLangOpts().ConstexprCallDepth;
  762. return false;
  763. }
  764. std::pair<CallStackFrame *, unsigned>
  765. getCallFrameAndDepth(unsigned CallIndex) {
  766. assert(CallIndex && "no call index in getCallFrameAndDepth");
  767. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  768. // be null in this loop.
  769. unsigned Depth = CallStackDepth;
  770. CallStackFrame *Frame = CurrentCall;
  771. while (Frame->Index > CallIndex) {
  772. Frame = Frame->Caller;
  773. --Depth;
  774. }
  775. if (Frame->Index == CallIndex)
  776. return {Frame, Depth};
  777. return {nullptr, 0};
  778. }
  779. bool nextStep(const Stmt *S) {
  780. if (!StepsLeft) {
  781. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  782. return false;
  783. }
  784. --StepsLeft;
  785. return true;
  786. }
  787. private:
  788. /// Add a diagnostic to the diagnostics list.
  789. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  790. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  791. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  792. return EvalStatus.Diag->back().second;
  793. }
  794. /// Add notes containing a call stack to the current point of evaluation.
  795. void addCallStack(unsigned Limit);
  796. private:
  797. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  798. unsigned ExtraNotes, bool IsCCEDiag) {
  799. if (EvalStatus.Diag) {
  800. // If we have a prior diagnostic, it will be noting that the expression
  801. // isn't a constant expression. This diagnostic is more important,
  802. // unless we require this evaluation to produce a constant expression.
  803. //
  804. // FIXME: We might want to show both diagnostics to the user in
  805. // EM_ConstantFold mode.
  806. if (!EvalStatus.Diag->empty()) {
  807. switch (EvalMode) {
  808. case EM_ConstantFold:
  809. case EM_IgnoreSideEffects:
  810. case EM_EvaluateForOverflow:
  811. if (!HasFoldFailureDiagnostic)
  812. break;
  813. // We've already failed to fold something. Keep that diagnostic.
  814. LLVM_FALLTHROUGH;
  815. case EM_ConstantExpression:
  816. case EM_PotentialConstantExpression:
  817. case EM_ConstantExpressionUnevaluated:
  818. case EM_PotentialConstantExpressionUnevaluated:
  819. HasActiveDiagnostic = false;
  820. return OptionalDiagnostic();
  821. }
  822. }
  823. unsigned CallStackNotes = CallStackDepth - 1;
  824. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  825. if (Limit)
  826. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  827. if (checkingPotentialConstantExpression())
  828. CallStackNotes = 0;
  829. HasActiveDiagnostic = true;
  830. HasFoldFailureDiagnostic = !IsCCEDiag;
  831. EvalStatus.Diag->clear();
  832. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  833. addDiag(Loc, DiagId);
  834. if (!checkingPotentialConstantExpression())
  835. addCallStack(Limit);
  836. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  837. }
  838. HasActiveDiagnostic = false;
  839. return OptionalDiagnostic();
  840. }
  841. public:
  842. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  843. OptionalDiagnostic
  844. FFDiag(SourceLocation Loc,
  845. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  846. unsigned ExtraNotes = 0) {
  847. return Diag(Loc, DiagId, ExtraNotes, false);
  848. }
  849. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  850. = diag::note_invalid_subexpr_in_const_expr,
  851. unsigned ExtraNotes = 0) {
  852. if (EvalStatus.Diag)
  853. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  854. HasActiveDiagnostic = false;
  855. return OptionalDiagnostic();
  856. }
  857. /// Diagnose that the evaluation does not produce a C++11 core constant
  858. /// expression.
  859. ///
  860. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  861. /// EM_PotentialConstantExpression mode and we produce one of these.
  862. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  863. = diag::note_invalid_subexpr_in_const_expr,
  864. unsigned ExtraNotes = 0) {
  865. // Don't override a previous diagnostic. Don't bother collecting
  866. // diagnostics if we're evaluating for overflow.
  867. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  868. HasActiveDiagnostic = false;
  869. return OptionalDiagnostic();
  870. }
  871. return Diag(Loc, DiagId, ExtraNotes, true);
  872. }
  873. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  874. = diag::note_invalid_subexpr_in_const_expr,
  875. unsigned ExtraNotes = 0) {
  876. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  877. }
  878. /// Add a note to a prior diagnostic.
  879. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  880. if (!HasActiveDiagnostic)
  881. return OptionalDiagnostic();
  882. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  883. }
  884. /// Add a stack of notes to a prior diagnostic.
  885. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  886. if (HasActiveDiagnostic) {
  887. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  888. Diags.begin(), Diags.end());
  889. }
  890. }
  891. /// Should we continue evaluation after encountering a side-effect that we
  892. /// couldn't model?
  893. bool keepEvaluatingAfterSideEffect() {
  894. switch (EvalMode) {
  895. case EM_PotentialConstantExpression:
  896. case EM_PotentialConstantExpressionUnevaluated:
  897. case EM_EvaluateForOverflow:
  898. case EM_IgnoreSideEffects:
  899. return true;
  900. case EM_ConstantExpression:
  901. case EM_ConstantExpressionUnevaluated:
  902. case EM_ConstantFold:
  903. return false;
  904. }
  905. llvm_unreachable("Missed EvalMode case");
  906. }
  907. /// Note that we have had a side-effect, and determine whether we should
  908. /// keep evaluating.
  909. bool noteSideEffect() {
  910. EvalStatus.HasSideEffects = true;
  911. return keepEvaluatingAfterSideEffect();
  912. }
  913. /// Should we continue evaluation after encountering undefined behavior?
  914. bool keepEvaluatingAfterUndefinedBehavior() {
  915. switch (EvalMode) {
  916. case EM_EvaluateForOverflow:
  917. case EM_IgnoreSideEffects:
  918. case EM_ConstantFold:
  919. return true;
  920. case EM_PotentialConstantExpression:
  921. case EM_PotentialConstantExpressionUnevaluated:
  922. case EM_ConstantExpression:
  923. case EM_ConstantExpressionUnevaluated:
  924. return false;
  925. }
  926. llvm_unreachable("Missed EvalMode case");
  927. }
  928. /// Note that we hit something that was technically undefined behavior, but
  929. /// that we can evaluate past it (such as signed overflow or floating-point
  930. /// division by zero.)
  931. bool noteUndefinedBehavior() {
  932. EvalStatus.HasUndefinedBehavior = true;
  933. return keepEvaluatingAfterUndefinedBehavior();
  934. }
  935. /// Should we continue evaluation as much as possible after encountering a
  936. /// construct which can't be reduced to a value?
  937. bool keepEvaluatingAfterFailure() {
  938. if (!StepsLeft)
  939. return false;
  940. switch (EvalMode) {
  941. case EM_PotentialConstantExpression:
  942. case EM_PotentialConstantExpressionUnevaluated:
  943. case EM_EvaluateForOverflow:
  944. return true;
  945. case EM_ConstantExpression:
  946. case EM_ConstantExpressionUnevaluated:
  947. case EM_ConstantFold:
  948. case EM_IgnoreSideEffects:
  949. return false;
  950. }
  951. llvm_unreachable("Missed EvalMode case");
  952. }
  953. /// Notes that we failed to evaluate an expression that other expressions
  954. /// directly depend on, and determine if we should keep evaluating. This
  955. /// should only be called if we actually intend to keep evaluating.
  956. ///
  957. /// Call noteSideEffect() instead if we may be able to ignore the value that
  958. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  959. ///
  960. /// (Foo(), 1) // use noteSideEffect
  961. /// (Foo() || true) // use noteSideEffect
  962. /// Foo() + 1 // use noteFailure
  963. LLVM_NODISCARD bool noteFailure() {
  964. // Failure when evaluating some expression often means there is some
  965. // subexpression whose evaluation was skipped. Therefore, (because we
  966. // don't track whether we skipped an expression when unwinding after an
  967. // evaluation failure) every evaluation failure that bubbles up from a
  968. // subexpression implies that a side-effect has potentially happened. We
  969. // skip setting the HasSideEffects flag to true until we decide to
  970. // continue evaluating after that point, which happens here.
  971. bool KeepGoing = keepEvaluatingAfterFailure();
  972. EvalStatus.HasSideEffects |= KeepGoing;
  973. return KeepGoing;
  974. }
  975. class ArrayInitLoopIndex {
  976. EvalInfo &Info;
  977. uint64_t OuterIndex;
  978. public:
  979. ArrayInitLoopIndex(EvalInfo &Info)
  980. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  981. Info.ArrayInitIndex = 0;
  982. }
  983. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  984. operator uint64_t&() { return Info.ArrayInitIndex; }
  985. };
  986. };
  987. /// Object used to treat all foldable expressions as constant expressions.
  988. struct FoldConstant {
  989. EvalInfo &Info;
  990. bool Enabled;
  991. bool HadNoPriorDiags;
  992. EvalInfo::EvaluationMode OldMode;
  993. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  994. : Info(Info),
  995. Enabled(Enabled),
  996. HadNoPriorDiags(Info.EvalStatus.Diag &&
  997. Info.EvalStatus.Diag->empty() &&
  998. !Info.EvalStatus.HasSideEffects),
  999. OldMode(Info.EvalMode) {
  1000. if (Enabled &&
  1001. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  1002. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  1003. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1004. }
  1005. void keepDiagnostics() { Enabled = false; }
  1006. ~FoldConstant() {
  1007. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1008. !Info.EvalStatus.HasSideEffects)
  1009. Info.EvalStatus.Diag->clear();
  1010. Info.EvalMode = OldMode;
  1011. }
  1012. };
  1013. /// RAII object used to set the current evaluation mode to ignore
  1014. /// side-effects.
  1015. struct IgnoreSideEffectsRAII {
  1016. EvalInfo &Info;
  1017. EvalInfo::EvaluationMode OldMode;
  1018. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1019. : Info(Info), OldMode(Info.EvalMode) {
  1020. if (!Info.checkingPotentialConstantExpression())
  1021. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1022. }
  1023. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1024. };
  1025. /// RAII object used to optionally suppress diagnostics and side-effects from
  1026. /// a speculative evaluation.
  1027. class SpeculativeEvaluationRAII {
  1028. EvalInfo *Info = nullptr;
  1029. Expr::EvalStatus OldStatus;
  1030. unsigned OldSpeculativeEvaluationDepth;
  1031. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1032. Info = Other.Info;
  1033. OldStatus = Other.OldStatus;
  1034. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1035. Other.Info = nullptr;
  1036. }
  1037. void maybeRestoreState() {
  1038. if (!Info)
  1039. return;
  1040. Info->EvalStatus = OldStatus;
  1041. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1042. }
  1043. public:
  1044. SpeculativeEvaluationRAII() = default;
  1045. SpeculativeEvaluationRAII(
  1046. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1047. : Info(&Info), OldStatus(Info.EvalStatus),
  1048. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1049. Info.EvalStatus.Diag = NewDiag;
  1050. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1051. }
  1052. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1053. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1054. moveFromAndCancel(std::move(Other));
  1055. }
  1056. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1057. maybeRestoreState();
  1058. moveFromAndCancel(std::move(Other));
  1059. return *this;
  1060. }
  1061. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1062. };
  1063. /// RAII object wrapping a full-expression or block scope, and handling
  1064. /// the ending of the lifetime of temporaries created within it.
  1065. template<bool IsFullExpression>
  1066. class ScopeRAII {
  1067. EvalInfo &Info;
  1068. unsigned OldStackSize;
  1069. public:
  1070. ScopeRAII(EvalInfo &Info)
  1071. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1072. // Push a new temporary version. This is needed to distinguish between
  1073. // temporaries created in different iterations of a loop.
  1074. Info.CurrentCall->pushTempVersion();
  1075. }
  1076. ~ScopeRAII() {
  1077. // Body moved to a static method to encourage the compiler to inline away
  1078. // instances of this class.
  1079. cleanup(Info, OldStackSize);
  1080. Info.CurrentCall->popTempVersion();
  1081. }
  1082. private:
  1083. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1084. unsigned NewEnd = OldStackSize;
  1085. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1086. I != N; ++I) {
  1087. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1088. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1089. // to do, just move this cleanup to the right place in the stack.
  1090. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1091. ++NewEnd;
  1092. } else {
  1093. // End the lifetime of the object.
  1094. Info.CleanupStack[I].endLifetime();
  1095. }
  1096. }
  1097. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1098. Info.CleanupStack.end());
  1099. }
  1100. };
  1101. typedef ScopeRAII<false> BlockScopeRAII;
  1102. typedef ScopeRAII<true> FullExpressionRAII;
  1103. }
  1104. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1105. CheckSubobjectKind CSK) {
  1106. if (Invalid)
  1107. return false;
  1108. if (isOnePastTheEnd()) {
  1109. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1110. << CSK;
  1111. setInvalid();
  1112. return false;
  1113. }
  1114. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1115. // must actually be at least one array element; even a VLA cannot have a
  1116. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1117. return true;
  1118. }
  1119. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1120. const Expr *E) {
  1121. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1122. // Do not set the designator as invalid: we can represent this situation,
  1123. // and correct handling of __builtin_object_size requires us to do so.
  1124. }
  1125. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1126. const Expr *E,
  1127. const APSInt &N) {
  1128. // If we're complaining, we must be able to statically determine the size of
  1129. // the most derived array.
  1130. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1131. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1132. << N << /*array*/ 0
  1133. << static_cast<unsigned>(getMostDerivedArraySize());
  1134. else
  1135. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1136. << N << /*non-array*/ 1;
  1137. setInvalid();
  1138. }
  1139. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1140. const FunctionDecl *Callee, const LValue *This,
  1141. APValue *Arguments)
  1142. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1143. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1144. Info.CurrentCall = this;
  1145. ++Info.CallStackDepth;
  1146. }
  1147. CallStackFrame::~CallStackFrame() {
  1148. assert(Info.CurrentCall == this && "calls retired out of order");
  1149. --Info.CallStackDepth;
  1150. Info.CurrentCall = Caller;
  1151. }
  1152. APValue &CallStackFrame::createTemporary(const void *Key,
  1153. bool IsLifetimeExtended) {
  1154. unsigned Version = Info.CurrentCall->getTempVersion();
  1155. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1156. assert(Result.isAbsent() && "temporary created multiple times");
  1157. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1158. return Result;
  1159. }
  1160. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1161. void EvalInfo::addCallStack(unsigned Limit) {
  1162. // Determine which calls to skip, if any.
  1163. unsigned ActiveCalls = CallStackDepth - 1;
  1164. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1165. if (Limit && Limit < ActiveCalls) {
  1166. SkipStart = Limit / 2 + Limit % 2;
  1167. SkipEnd = ActiveCalls - Limit / 2;
  1168. }
  1169. // Walk the call stack and add the diagnostics.
  1170. unsigned CallIdx = 0;
  1171. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1172. Frame = Frame->Caller, ++CallIdx) {
  1173. // Skip this call?
  1174. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1175. if (CallIdx == SkipStart) {
  1176. // Note that we're skipping calls.
  1177. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1178. << unsigned(ActiveCalls - Limit);
  1179. }
  1180. continue;
  1181. }
  1182. // Use a different note for an inheriting constructor, because from the
  1183. // user's perspective it's not really a function at all.
  1184. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1185. if (CD->isInheritingConstructor()) {
  1186. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1187. << CD->getParent();
  1188. continue;
  1189. }
  1190. }
  1191. SmallVector<char, 128> Buffer;
  1192. llvm::raw_svector_ostream Out(Buffer);
  1193. describeCall(Frame, Out);
  1194. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1195. }
  1196. }
  1197. /// Kinds of access we can perform on an object, for diagnostics. Note that
  1198. /// we consider a member function call to be a kind of access, even though
  1199. /// it is not formally an access of the object, because it has (largely) the
  1200. /// same set of semantic restrictions.
  1201. enum AccessKinds {
  1202. AK_Read,
  1203. AK_Assign,
  1204. AK_Increment,
  1205. AK_Decrement,
  1206. AK_MemberCall,
  1207. AK_DynamicCast,
  1208. AK_TypeId,
  1209. };
  1210. static bool isModification(AccessKinds AK) {
  1211. switch (AK) {
  1212. case AK_Read:
  1213. case AK_MemberCall:
  1214. case AK_DynamicCast:
  1215. case AK_TypeId:
  1216. return false;
  1217. case AK_Assign:
  1218. case AK_Increment:
  1219. case AK_Decrement:
  1220. return true;
  1221. }
  1222. llvm_unreachable("unknown access kind");
  1223. }
  1224. /// Is this an access per the C++ definition?
  1225. static bool isFormalAccess(AccessKinds AK) {
  1226. return AK == AK_Read || isModification(AK);
  1227. }
  1228. namespace {
  1229. struct ComplexValue {
  1230. private:
  1231. bool IsInt;
  1232. public:
  1233. APSInt IntReal, IntImag;
  1234. APFloat FloatReal, FloatImag;
  1235. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1236. void makeComplexFloat() { IsInt = false; }
  1237. bool isComplexFloat() const { return !IsInt; }
  1238. APFloat &getComplexFloatReal() { return FloatReal; }
  1239. APFloat &getComplexFloatImag() { return FloatImag; }
  1240. void makeComplexInt() { IsInt = true; }
  1241. bool isComplexInt() const { return IsInt; }
  1242. APSInt &getComplexIntReal() { return IntReal; }
  1243. APSInt &getComplexIntImag() { return IntImag; }
  1244. void moveInto(APValue &v) const {
  1245. if (isComplexFloat())
  1246. v = APValue(FloatReal, FloatImag);
  1247. else
  1248. v = APValue(IntReal, IntImag);
  1249. }
  1250. void setFrom(const APValue &v) {
  1251. assert(v.isComplexFloat() || v.isComplexInt());
  1252. if (v.isComplexFloat()) {
  1253. makeComplexFloat();
  1254. FloatReal = v.getComplexFloatReal();
  1255. FloatImag = v.getComplexFloatImag();
  1256. } else {
  1257. makeComplexInt();
  1258. IntReal = v.getComplexIntReal();
  1259. IntImag = v.getComplexIntImag();
  1260. }
  1261. }
  1262. };
  1263. struct LValue {
  1264. APValue::LValueBase Base;
  1265. CharUnits Offset;
  1266. SubobjectDesignator Designator;
  1267. bool IsNullPtr : 1;
  1268. bool InvalidBase : 1;
  1269. const APValue::LValueBase getLValueBase() const { return Base; }
  1270. CharUnits &getLValueOffset() { return Offset; }
  1271. const CharUnits &getLValueOffset() const { return Offset; }
  1272. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1273. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1274. bool isNullPointer() const { return IsNullPtr;}
  1275. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1276. unsigned getLValueVersion() const { return Base.getVersion(); }
  1277. void moveInto(APValue &V) const {
  1278. if (Designator.Invalid)
  1279. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1280. else {
  1281. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1282. V = APValue(Base, Offset, Designator.Entries,
  1283. Designator.IsOnePastTheEnd, IsNullPtr);
  1284. }
  1285. }
  1286. void setFrom(ASTContext &Ctx, const APValue &V) {
  1287. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1288. Base = V.getLValueBase();
  1289. Offset = V.getLValueOffset();
  1290. InvalidBase = false;
  1291. Designator = SubobjectDesignator(Ctx, V);
  1292. IsNullPtr = V.isNullPointer();
  1293. }
  1294. void set(APValue::LValueBase B, bool BInvalid = false) {
  1295. #ifndef NDEBUG
  1296. // We only allow a few types of invalid bases. Enforce that here.
  1297. if (BInvalid) {
  1298. const auto *E = B.get<const Expr *>();
  1299. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1300. "Unexpected type of invalid base");
  1301. }
  1302. #endif
  1303. Base = B;
  1304. Offset = CharUnits::fromQuantity(0);
  1305. InvalidBase = BInvalid;
  1306. Designator = SubobjectDesignator(getType(B));
  1307. IsNullPtr = false;
  1308. }
  1309. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1310. Base = (Expr *)nullptr;
  1311. Offset = CharUnits::fromQuantity(TargetVal);
  1312. InvalidBase = false;
  1313. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1314. IsNullPtr = true;
  1315. }
  1316. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1317. set(B, true);
  1318. }
  1319. private:
  1320. // Check that this LValue is not based on a null pointer. If it is, produce
  1321. // a diagnostic and mark the designator as invalid.
  1322. template <typename GenDiagType>
  1323. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1324. if (Designator.Invalid)
  1325. return false;
  1326. if (IsNullPtr) {
  1327. GenDiag();
  1328. Designator.setInvalid();
  1329. return false;
  1330. }
  1331. return true;
  1332. }
  1333. public:
  1334. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1335. CheckSubobjectKind CSK) {
  1336. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1337. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1338. });
  1339. }
  1340. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1341. AccessKinds AK) {
  1342. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1343. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1344. });
  1345. }
  1346. // Check this LValue refers to an object. If not, set the designator to be
  1347. // invalid and emit a diagnostic.
  1348. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1349. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1350. Designator.checkSubobject(Info, E, CSK);
  1351. }
  1352. void addDecl(EvalInfo &Info, const Expr *E,
  1353. const Decl *D, bool Virtual = false) {
  1354. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1355. Designator.addDeclUnchecked(D, Virtual);
  1356. }
  1357. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1358. if (!Designator.Entries.empty()) {
  1359. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1360. Designator.setInvalid();
  1361. return;
  1362. }
  1363. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1364. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1365. Designator.FirstEntryIsAnUnsizedArray = true;
  1366. Designator.addUnsizedArrayUnchecked(ElemTy);
  1367. }
  1368. }
  1369. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1370. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1371. Designator.addArrayUnchecked(CAT);
  1372. }
  1373. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1374. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1375. Designator.addComplexUnchecked(EltTy, Imag);
  1376. }
  1377. void clearIsNullPointer() {
  1378. IsNullPtr = false;
  1379. }
  1380. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1381. const APSInt &Index, CharUnits ElementSize) {
  1382. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1383. // but we're not required to diagnose it and it's valid in C++.)
  1384. if (!Index)
  1385. return;
  1386. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1387. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1388. // offsets.
  1389. uint64_t Offset64 = Offset.getQuantity();
  1390. uint64_t ElemSize64 = ElementSize.getQuantity();
  1391. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1392. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1393. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1394. Designator.adjustIndex(Info, E, Index);
  1395. clearIsNullPointer();
  1396. }
  1397. void adjustOffset(CharUnits N) {
  1398. Offset += N;
  1399. if (N.getQuantity())
  1400. clearIsNullPointer();
  1401. }
  1402. };
  1403. struct MemberPtr {
  1404. MemberPtr() {}
  1405. explicit MemberPtr(const ValueDecl *Decl) :
  1406. DeclAndIsDerivedMember(Decl, false), Path() {}
  1407. /// The member or (direct or indirect) field referred to by this member
  1408. /// pointer, or 0 if this is a null member pointer.
  1409. const ValueDecl *getDecl() const {
  1410. return DeclAndIsDerivedMember.getPointer();
  1411. }
  1412. /// Is this actually a member of some type derived from the relevant class?
  1413. bool isDerivedMember() const {
  1414. return DeclAndIsDerivedMember.getInt();
  1415. }
  1416. /// Get the class which the declaration actually lives in.
  1417. const CXXRecordDecl *getContainingRecord() const {
  1418. return cast<CXXRecordDecl>(
  1419. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1420. }
  1421. void moveInto(APValue &V) const {
  1422. V = APValue(getDecl(), isDerivedMember(), Path);
  1423. }
  1424. void setFrom(const APValue &V) {
  1425. assert(V.isMemberPointer());
  1426. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1427. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1428. Path.clear();
  1429. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1430. Path.insert(Path.end(), P.begin(), P.end());
  1431. }
  1432. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1433. /// whether the member is a member of some class derived from the class type
  1434. /// of the member pointer.
  1435. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1436. /// Path - The path of base/derived classes from the member declaration's
  1437. /// class (exclusive) to the class type of the member pointer (inclusive).
  1438. SmallVector<const CXXRecordDecl*, 4> Path;
  1439. /// Perform a cast towards the class of the Decl (either up or down the
  1440. /// hierarchy).
  1441. bool castBack(const CXXRecordDecl *Class) {
  1442. assert(!Path.empty());
  1443. const CXXRecordDecl *Expected;
  1444. if (Path.size() >= 2)
  1445. Expected = Path[Path.size() - 2];
  1446. else
  1447. Expected = getContainingRecord();
  1448. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1449. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1450. // if B does not contain the original member and is not a base or
  1451. // derived class of the class containing the original member, the result
  1452. // of the cast is undefined.
  1453. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1454. // (D::*). We consider that to be a language defect.
  1455. return false;
  1456. }
  1457. Path.pop_back();
  1458. return true;
  1459. }
  1460. /// Perform a base-to-derived member pointer cast.
  1461. bool castToDerived(const CXXRecordDecl *Derived) {
  1462. if (!getDecl())
  1463. return true;
  1464. if (!isDerivedMember()) {
  1465. Path.push_back(Derived);
  1466. return true;
  1467. }
  1468. if (!castBack(Derived))
  1469. return false;
  1470. if (Path.empty())
  1471. DeclAndIsDerivedMember.setInt(false);
  1472. return true;
  1473. }
  1474. /// Perform a derived-to-base member pointer cast.
  1475. bool castToBase(const CXXRecordDecl *Base) {
  1476. if (!getDecl())
  1477. return true;
  1478. if (Path.empty())
  1479. DeclAndIsDerivedMember.setInt(true);
  1480. if (isDerivedMember()) {
  1481. Path.push_back(Base);
  1482. return true;
  1483. }
  1484. return castBack(Base);
  1485. }
  1486. };
  1487. /// Compare two member pointers, which are assumed to be of the same type.
  1488. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1489. if (!LHS.getDecl() || !RHS.getDecl())
  1490. return !LHS.getDecl() && !RHS.getDecl();
  1491. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1492. return false;
  1493. return LHS.Path == RHS.Path;
  1494. }
  1495. }
  1496. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1497. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1498. const LValue &This, const Expr *E,
  1499. bool AllowNonLiteralTypes = false);
  1500. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1501. bool InvalidBaseOK = false);
  1502. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1503. bool InvalidBaseOK = false);
  1504. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1505. EvalInfo &Info);
  1506. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1507. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1508. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1509. EvalInfo &Info);
  1510. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1511. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1512. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1513. EvalInfo &Info);
  1514. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1515. /// Evaluate an integer or fixed point expression into an APResult.
  1516. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1517. EvalInfo &Info);
  1518. /// Evaluate only a fixed point expression into an APResult.
  1519. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1520. EvalInfo &Info);
  1521. //===----------------------------------------------------------------------===//
  1522. // Misc utilities
  1523. //===----------------------------------------------------------------------===//
  1524. /// A helper function to create a temporary and set an LValue.
  1525. template <class KeyTy>
  1526. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1527. LValue &LV, CallStackFrame &Frame) {
  1528. LV.set({Key, Frame.Info.CurrentCall->Index,
  1529. Frame.Info.CurrentCall->getTempVersion()});
  1530. return Frame.createTemporary(Key, IsLifetimeExtended);
  1531. }
  1532. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1533. /// preserving its value (by extending by up to one bit as needed).
  1534. static void negateAsSigned(APSInt &Int) {
  1535. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1536. Int = Int.extend(Int.getBitWidth() + 1);
  1537. Int.setIsSigned(true);
  1538. }
  1539. Int = -Int;
  1540. }
  1541. /// Produce a string describing the given constexpr call.
  1542. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1543. unsigned ArgIndex = 0;
  1544. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1545. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1546. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1547. if (!IsMemberCall)
  1548. Out << *Frame->Callee << '(';
  1549. if (Frame->This && IsMemberCall) {
  1550. APValue Val;
  1551. Frame->This->moveInto(Val);
  1552. Val.printPretty(Out, Frame->Info.Ctx,
  1553. Frame->This->Designator.MostDerivedType);
  1554. // FIXME: Add parens around Val if needed.
  1555. Out << "->" << *Frame->Callee << '(';
  1556. IsMemberCall = false;
  1557. }
  1558. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1559. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1560. if (ArgIndex > (unsigned)IsMemberCall)
  1561. Out << ", ";
  1562. const ParmVarDecl *Param = *I;
  1563. const APValue &Arg = Frame->Arguments[ArgIndex];
  1564. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1565. if (ArgIndex == 0 && IsMemberCall)
  1566. Out << "->" << *Frame->Callee << '(';
  1567. }
  1568. Out << ')';
  1569. }
  1570. /// Evaluate an expression to see if it had side-effects, and discard its
  1571. /// result.
  1572. /// \return \c true if the caller should keep evaluating.
  1573. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1574. APValue Scratch;
  1575. if (!Evaluate(Scratch, Info, E))
  1576. // We don't need the value, but we might have skipped a side effect here.
  1577. return Info.noteSideEffect();
  1578. return true;
  1579. }
  1580. /// Should this call expression be treated as a string literal?
  1581. static bool IsStringLiteralCall(const CallExpr *E) {
  1582. unsigned Builtin = E->getBuiltinCallee();
  1583. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1584. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1585. }
  1586. static bool IsGlobalLValue(APValue::LValueBase B) {
  1587. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1588. // constant expression of pointer type that evaluates to...
  1589. // ... a null pointer value, or a prvalue core constant expression of type
  1590. // std::nullptr_t.
  1591. if (!B) return true;
  1592. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1593. // ... the address of an object with static storage duration,
  1594. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1595. return VD->hasGlobalStorage();
  1596. // ... the address of a function,
  1597. return isa<FunctionDecl>(D);
  1598. }
  1599. if (B.is<TypeInfoLValue>())
  1600. return true;
  1601. const Expr *E = B.get<const Expr*>();
  1602. switch (E->getStmtClass()) {
  1603. default:
  1604. return false;
  1605. case Expr::CompoundLiteralExprClass: {
  1606. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1607. return CLE->isFileScope() && CLE->isLValue();
  1608. }
  1609. case Expr::MaterializeTemporaryExprClass:
  1610. // A materialized temporary might have been lifetime-extended to static
  1611. // storage duration.
  1612. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1613. // A string literal has static storage duration.
  1614. case Expr::StringLiteralClass:
  1615. case Expr::PredefinedExprClass:
  1616. case Expr::ObjCStringLiteralClass:
  1617. case Expr::ObjCEncodeExprClass:
  1618. case Expr::CXXUuidofExprClass:
  1619. return true;
  1620. case Expr::ObjCBoxedExprClass:
  1621. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1622. case Expr::CallExprClass:
  1623. return IsStringLiteralCall(cast<CallExpr>(E));
  1624. // For GCC compatibility, &&label has static storage duration.
  1625. case Expr::AddrLabelExprClass:
  1626. return true;
  1627. // A Block literal expression may be used as the initialization value for
  1628. // Block variables at global or local static scope.
  1629. case Expr::BlockExprClass:
  1630. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1631. case Expr::ImplicitValueInitExprClass:
  1632. // FIXME:
  1633. // We can never form an lvalue with an implicit value initialization as its
  1634. // base through expression evaluation, so these only appear in one case: the
  1635. // implicit variable declaration we invent when checking whether a constexpr
  1636. // constructor can produce a constant expression. We must assume that such
  1637. // an expression might be a global lvalue.
  1638. return true;
  1639. }
  1640. }
  1641. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1642. return LVal.Base.dyn_cast<const ValueDecl*>();
  1643. }
  1644. static bool IsLiteralLValue(const LValue &Value) {
  1645. if (Value.getLValueCallIndex())
  1646. return false;
  1647. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1648. return E && !isa<MaterializeTemporaryExpr>(E);
  1649. }
  1650. static bool IsWeakLValue(const LValue &Value) {
  1651. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1652. return Decl && Decl->isWeak();
  1653. }
  1654. static bool isZeroSized(const LValue &Value) {
  1655. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1656. if (Decl && isa<VarDecl>(Decl)) {
  1657. QualType Ty = Decl->getType();
  1658. if (Ty->isArrayType())
  1659. return Ty->isIncompleteType() ||
  1660. Decl->getASTContext().getTypeSize(Ty) == 0;
  1661. }
  1662. return false;
  1663. }
  1664. static bool HasSameBase(const LValue &A, const LValue &B) {
  1665. if (!A.getLValueBase())
  1666. return !B.getLValueBase();
  1667. if (!B.getLValueBase())
  1668. return false;
  1669. if (A.getLValueBase().getOpaqueValue() !=
  1670. B.getLValueBase().getOpaqueValue()) {
  1671. const Decl *ADecl = GetLValueBaseDecl(A);
  1672. if (!ADecl)
  1673. return false;
  1674. const Decl *BDecl = GetLValueBaseDecl(B);
  1675. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1676. return false;
  1677. }
  1678. return IsGlobalLValue(A.getLValueBase()) ||
  1679. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1680. A.getLValueVersion() == B.getLValueVersion());
  1681. }
  1682. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1683. assert(Base && "no location for a null lvalue");
  1684. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1685. if (VD)
  1686. Info.Note(VD->getLocation(), diag::note_declared_at);
  1687. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1688. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1689. // We have no information to show for a typeid(T) object.
  1690. }
  1691. /// Check that this reference or pointer core constant expression is a valid
  1692. /// value for an address or reference constant expression. Return true if we
  1693. /// can fold this expression, whether or not it's a constant expression.
  1694. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1695. QualType Type, const LValue &LVal,
  1696. Expr::ConstExprUsage Usage) {
  1697. bool IsReferenceType = Type->isReferenceType();
  1698. APValue::LValueBase Base = LVal.getLValueBase();
  1699. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1700. // Check that the object is a global. Note that the fake 'this' object we
  1701. // manufacture when checking potential constant expressions is conservatively
  1702. // assumed to be global here.
  1703. if (!IsGlobalLValue(Base)) {
  1704. if (Info.getLangOpts().CPlusPlus11) {
  1705. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1706. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1707. << IsReferenceType << !Designator.Entries.empty()
  1708. << !!VD << VD;
  1709. NoteLValueLocation(Info, Base);
  1710. } else {
  1711. Info.FFDiag(Loc);
  1712. }
  1713. // Don't allow references to temporaries to escape.
  1714. return false;
  1715. }
  1716. assert((Info.checkingPotentialConstantExpression() ||
  1717. LVal.getLValueCallIndex() == 0) &&
  1718. "have call index for global lvalue");
  1719. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1720. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1721. // Check if this is a thread-local variable.
  1722. if (Var->getTLSKind())
  1723. return false;
  1724. // A dllimport variable never acts like a constant.
  1725. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1726. return false;
  1727. }
  1728. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1729. // __declspec(dllimport) must be handled very carefully:
  1730. // We must never initialize an expression with the thunk in C++.
  1731. // Doing otherwise would allow the same id-expression to yield
  1732. // different addresses for the same function in different translation
  1733. // units. However, this means that we must dynamically initialize the
  1734. // expression with the contents of the import address table at runtime.
  1735. //
  1736. // The C language has no notion of ODR; furthermore, it has no notion of
  1737. // dynamic initialization. This means that we are permitted to
  1738. // perform initialization with the address of the thunk.
  1739. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1740. FD->hasAttr<DLLImportAttr>())
  1741. return false;
  1742. }
  1743. }
  1744. // Allow address constant expressions to be past-the-end pointers. This is
  1745. // an extension: the standard requires them to point to an object.
  1746. if (!IsReferenceType)
  1747. return true;
  1748. // A reference constant expression must refer to an object.
  1749. if (!Base) {
  1750. // FIXME: diagnostic
  1751. Info.CCEDiag(Loc);
  1752. return true;
  1753. }
  1754. // Does this refer one past the end of some object?
  1755. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1756. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1757. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1758. << !Designator.Entries.empty() << !!VD << VD;
  1759. NoteLValueLocation(Info, Base);
  1760. }
  1761. return true;
  1762. }
  1763. /// Member pointers are constant expressions unless they point to a
  1764. /// non-virtual dllimport member function.
  1765. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1766. SourceLocation Loc,
  1767. QualType Type,
  1768. const APValue &Value,
  1769. Expr::ConstExprUsage Usage) {
  1770. const ValueDecl *Member = Value.getMemberPointerDecl();
  1771. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1772. if (!FD)
  1773. return true;
  1774. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1775. !FD->hasAttr<DLLImportAttr>();
  1776. }
  1777. /// Check that this core constant expression is of literal type, and if not,
  1778. /// produce an appropriate diagnostic.
  1779. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1780. const LValue *This = nullptr) {
  1781. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1782. return true;
  1783. // C++1y: A constant initializer for an object o [...] may also invoke
  1784. // constexpr constructors for o and its subobjects even if those objects
  1785. // are of non-literal class types.
  1786. //
  1787. // C++11 missed this detail for aggregates, so classes like this:
  1788. // struct foo_t { union { int i; volatile int j; } u; };
  1789. // are not (obviously) initializable like so:
  1790. // __attribute__((__require_constant_initialization__))
  1791. // static const foo_t x = {{0}};
  1792. // because "i" is a subobject with non-literal initialization (due to the
  1793. // volatile member of the union). See:
  1794. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1795. // Therefore, we use the C++1y behavior.
  1796. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1797. return true;
  1798. // Prvalue constant expressions must be of literal types.
  1799. if (Info.getLangOpts().CPlusPlus11)
  1800. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1801. << E->getType();
  1802. else
  1803. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1804. return false;
  1805. }
  1806. /// Check that this core constant expression value is a valid value for a
  1807. /// constant expression. If not, report an appropriate diagnostic. Does not
  1808. /// check that the expression is of literal type.
  1809. static bool
  1810. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1811. const APValue &Value,
  1812. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
  1813. SourceLocation SubobjectLoc = SourceLocation()) {
  1814. if (!Value.hasValue()) {
  1815. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1816. << true << Type;
  1817. if (SubobjectLoc.isValid())
  1818. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1819. return false;
  1820. }
  1821. // We allow _Atomic(T) to be initialized from anything that T can be
  1822. // initialized from.
  1823. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1824. Type = AT->getValueType();
  1825. // Core issue 1454: For a literal constant expression of array or class type,
  1826. // each subobject of its value shall have been initialized by a constant
  1827. // expression.
  1828. if (Value.isArray()) {
  1829. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1830. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1831. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1832. Value.getArrayInitializedElt(I), Usage,
  1833. SubobjectLoc))
  1834. return false;
  1835. }
  1836. if (!Value.hasArrayFiller())
  1837. return true;
  1838. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1839. Usage, SubobjectLoc);
  1840. }
  1841. if (Value.isUnion() && Value.getUnionField()) {
  1842. return CheckConstantExpression(Info, DiagLoc,
  1843. Value.getUnionField()->getType(),
  1844. Value.getUnionValue(), Usage,
  1845. Value.getUnionField()->getLocation());
  1846. }
  1847. if (Value.isStruct()) {
  1848. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1849. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1850. unsigned BaseIndex = 0;
  1851. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1852. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1853. Value.getStructBase(BaseIndex), Usage,
  1854. BS.getBeginLoc()))
  1855. return false;
  1856. ++BaseIndex;
  1857. }
  1858. }
  1859. for (const auto *I : RD->fields()) {
  1860. if (I->isUnnamedBitfield())
  1861. continue;
  1862. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1863. Value.getStructField(I->getFieldIndex()),
  1864. Usage, I->getLocation()))
  1865. return false;
  1866. }
  1867. }
  1868. if (Value.isLValue()) {
  1869. LValue LVal;
  1870. LVal.setFrom(Info.Ctx, Value);
  1871. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1872. }
  1873. if (Value.isMemberPointer())
  1874. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1875. // Everything else is fine.
  1876. return true;
  1877. }
  1878. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1879. // A null base expression indicates a null pointer. These are always
  1880. // evaluatable, and they are false unless the offset is zero.
  1881. if (!Value.getLValueBase()) {
  1882. Result = !Value.getLValueOffset().isZero();
  1883. return true;
  1884. }
  1885. // We have a non-null base. These are generally known to be true, but if it's
  1886. // a weak declaration it can be null at runtime.
  1887. Result = true;
  1888. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1889. return !Decl || !Decl->isWeak();
  1890. }
  1891. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1892. switch (Val.getKind()) {
  1893. case APValue::None:
  1894. case APValue::Indeterminate:
  1895. return false;
  1896. case APValue::Int:
  1897. Result = Val.getInt().getBoolValue();
  1898. return true;
  1899. case APValue::FixedPoint:
  1900. Result = Val.getFixedPoint().getBoolValue();
  1901. return true;
  1902. case APValue::Float:
  1903. Result = !Val.getFloat().isZero();
  1904. return true;
  1905. case APValue::ComplexInt:
  1906. Result = Val.getComplexIntReal().getBoolValue() ||
  1907. Val.getComplexIntImag().getBoolValue();
  1908. return true;
  1909. case APValue::ComplexFloat:
  1910. Result = !Val.getComplexFloatReal().isZero() ||
  1911. !Val.getComplexFloatImag().isZero();
  1912. return true;
  1913. case APValue::LValue:
  1914. return EvalPointerValueAsBool(Val, Result);
  1915. case APValue::MemberPointer:
  1916. Result = Val.getMemberPointerDecl();
  1917. return true;
  1918. case APValue::Vector:
  1919. case APValue::Array:
  1920. case APValue::Struct:
  1921. case APValue::Union:
  1922. case APValue::AddrLabelDiff:
  1923. return false;
  1924. }
  1925. llvm_unreachable("unknown APValue kind");
  1926. }
  1927. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1928. EvalInfo &Info) {
  1929. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1930. APValue Val;
  1931. if (!Evaluate(Val, Info, E))
  1932. return false;
  1933. return HandleConversionToBool(Val, Result);
  1934. }
  1935. template<typename T>
  1936. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1937. const T &SrcValue, QualType DestType) {
  1938. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1939. << SrcValue << DestType;
  1940. return Info.noteUndefinedBehavior();
  1941. }
  1942. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1943. QualType SrcType, const APFloat &Value,
  1944. QualType DestType, APSInt &Result) {
  1945. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1946. // Determine whether we are converting to unsigned or signed.
  1947. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1948. Result = APSInt(DestWidth, !DestSigned);
  1949. bool ignored;
  1950. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1951. & APFloat::opInvalidOp)
  1952. return HandleOverflow(Info, E, Value, DestType);
  1953. return true;
  1954. }
  1955. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1956. QualType SrcType, QualType DestType,
  1957. APFloat &Result) {
  1958. APFloat Value = Result;
  1959. bool ignored;
  1960. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1961. APFloat::rmNearestTiesToEven, &ignored)
  1962. & APFloat::opOverflow)
  1963. return HandleOverflow(Info, E, Value, DestType);
  1964. return true;
  1965. }
  1966. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1967. QualType DestType, QualType SrcType,
  1968. const APSInt &Value) {
  1969. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1970. // Figure out if this is a truncate, extend or noop cast.
  1971. // If the input is signed, do a sign extend, noop, or truncate.
  1972. APSInt Result = Value.extOrTrunc(DestWidth);
  1973. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1974. if (DestType->isBooleanType())
  1975. Result = Value.getBoolValue();
  1976. return Result;
  1977. }
  1978. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1979. QualType SrcType, const APSInt &Value,
  1980. QualType DestType, APFloat &Result) {
  1981. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1982. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1983. APFloat::rmNearestTiesToEven)
  1984. & APFloat::opOverflow)
  1985. return HandleOverflow(Info, E, Value, DestType);
  1986. return true;
  1987. }
  1988. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1989. APValue &Value, const FieldDecl *FD) {
  1990. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1991. if (!Value.isInt()) {
  1992. // Trying to store a pointer-cast-to-integer into a bitfield.
  1993. // FIXME: In this case, we should provide the diagnostic for casting
  1994. // a pointer to an integer.
  1995. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1996. Info.FFDiag(E);
  1997. return false;
  1998. }
  1999. APSInt &Int = Value.getInt();
  2000. unsigned OldBitWidth = Int.getBitWidth();
  2001. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2002. if (NewBitWidth < OldBitWidth)
  2003. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2004. return true;
  2005. }
  2006. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2007. llvm::APInt &Res) {
  2008. APValue SVal;
  2009. if (!Evaluate(SVal, Info, E))
  2010. return false;
  2011. if (SVal.isInt()) {
  2012. Res = SVal.getInt();
  2013. return true;
  2014. }
  2015. if (SVal.isFloat()) {
  2016. Res = SVal.getFloat().bitcastToAPInt();
  2017. return true;
  2018. }
  2019. if (SVal.isVector()) {
  2020. QualType VecTy = E->getType();
  2021. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2022. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2023. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2024. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2025. Res = llvm::APInt::getNullValue(VecSize);
  2026. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2027. APValue &Elt = SVal.getVectorElt(i);
  2028. llvm::APInt EltAsInt;
  2029. if (Elt.isInt()) {
  2030. EltAsInt = Elt.getInt();
  2031. } else if (Elt.isFloat()) {
  2032. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2033. } else {
  2034. // Don't try to handle vectors of anything other than int or float
  2035. // (not sure if it's possible to hit this case).
  2036. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2037. return false;
  2038. }
  2039. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2040. if (BigEndian)
  2041. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2042. else
  2043. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2044. }
  2045. return true;
  2046. }
  2047. // Give up if the input isn't an int, float, or vector. For example, we
  2048. // reject "(v4i16)(intptr_t)&a".
  2049. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2050. return false;
  2051. }
  2052. /// Perform the given integer operation, which is known to need at most BitWidth
  2053. /// bits, and check for overflow in the original type (if that type was not an
  2054. /// unsigned type).
  2055. template<typename Operation>
  2056. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2057. const APSInt &LHS, const APSInt &RHS,
  2058. unsigned BitWidth, Operation Op,
  2059. APSInt &Result) {
  2060. if (LHS.isUnsigned()) {
  2061. Result = Op(LHS, RHS);
  2062. return true;
  2063. }
  2064. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2065. Result = Value.trunc(LHS.getBitWidth());
  2066. if (Result.extend(BitWidth) != Value) {
  2067. if (Info.checkingForOverflow())
  2068. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2069. diag::warn_integer_constant_overflow)
  2070. << Result.toString(10) << E->getType();
  2071. else
  2072. return HandleOverflow(Info, E, Value, E->getType());
  2073. }
  2074. return true;
  2075. }
  2076. /// Perform the given binary integer operation.
  2077. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2078. BinaryOperatorKind Opcode, APSInt RHS,
  2079. APSInt &Result) {
  2080. switch (Opcode) {
  2081. default:
  2082. Info.FFDiag(E);
  2083. return false;
  2084. case BO_Mul:
  2085. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2086. std::multiplies<APSInt>(), Result);
  2087. case BO_Add:
  2088. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2089. std::plus<APSInt>(), Result);
  2090. case BO_Sub:
  2091. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2092. std::minus<APSInt>(), Result);
  2093. case BO_And: Result = LHS & RHS; return true;
  2094. case BO_Xor: Result = LHS ^ RHS; return true;
  2095. case BO_Or: Result = LHS | RHS; return true;
  2096. case BO_Div:
  2097. case BO_Rem:
  2098. if (RHS == 0) {
  2099. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2100. return false;
  2101. }
  2102. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2103. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2104. // this operation and gives the two's complement result.
  2105. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2106. LHS.isSigned() && LHS.isMinSignedValue())
  2107. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2108. E->getType());
  2109. return true;
  2110. case BO_Shl: {
  2111. if (Info.getLangOpts().OpenCL)
  2112. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2113. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2114. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2115. RHS.isUnsigned());
  2116. else if (RHS.isSigned() && RHS.isNegative()) {
  2117. // During constant-folding, a negative shift is an opposite shift. Such
  2118. // a shift is not a constant expression.
  2119. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2120. RHS = -RHS;
  2121. goto shift_right;
  2122. }
  2123. shift_left:
  2124. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2125. // the shifted type.
  2126. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2127. if (SA != RHS) {
  2128. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2129. << RHS << E->getType() << LHS.getBitWidth();
  2130. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
  2131. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2132. // operand, and must not overflow the corresponding unsigned type.
  2133. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2134. // E1 x 2^E2 module 2^N.
  2135. if (LHS.isNegative())
  2136. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2137. else if (LHS.countLeadingZeros() < SA)
  2138. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2139. }
  2140. Result = LHS << SA;
  2141. return true;
  2142. }
  2143. case BO_Shr: {
  2144. if (Info.getLangOpts().OpenCL)
  2145. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2146. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2147. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2148. RHS.isUnsigned());
  2149. else if (RHS.isSigned() && RHS.isNegative()) {
  2150. // During constant-folding, a negative shift is an opposite shift. Such a
  2151. // shift is not a constant expression.
  2152. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2153. RHS = -RHS;
  2154. goto shift_left;
  2155. }
  2156. shift_right:
  2157. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2158. // shifted type.
  2159. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2160. if (SA != RHS)
  2161. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2162. << RHS << E->getType() << LHS.getBitWidth();
  2163. Result = LHS >> SA;
  2164. return true;
  2165. }
  2166. case BO_LT: Result = LHS < RHS; return true;
  2167. case BO_GT: Result = LHS > RHS; return true;
  2168. case BO_LE: Result = LHS <= RHS; return true;
  2169. case BO_GE: Result = LHS >= RHS; return true;
  2170. case BO_EQ: Result = LHS == RHS; return true;
  2171. case BO_NE: Result = LHS != RHS; return true;
  2172. case BO_Cmp:
  2173. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2174. }
  2175. }
  2176. /// Perform the given binary floating-point operation, in-place, on LHS.
  2177. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2178. APFloat &LHS, BinaryOperatorKind Opcode,
  2179. const APFloat &RHS) {
  2180. switch (Opcode) {
  2181. default:
  2182. Info.FFDiag(E);
  2183. return false;
  2184. case BO_Mul:
  2185. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2186. break;
  2187. case BO_Add:
  2188. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2189. break;
  2190. case BO_Sub:
  2191. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2192. break;
  2193. case BO_Div:
  2194. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2195. break;
  2196. }
  2197. if (LHS.isInfinity() || LHS.isNaN()) {
  2198. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2199. return Info.noteUndefinedBehavior();
  2200. }
  2201. return true;
  2202. }
  2203. /// Cast an lvalue referring to a base subobject to a derived class, by
  2204. /// truncating the lvalue's path to the given length.
  2205. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2206. const RecordDecl *TruncatedType,
  2207. unsigned TruncatedElements) {
  2208. SubobjectDesignator &D = Result.Designator;
  2209. // Check we actually point to a derived class object.
  2210. if (TruncatedElements == D.Entries.size())
  2211. return true;
  2212. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2213. "not casting to a derived class");
  2214. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2215. return false;
  2216. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2217. const RecordDecl *RD = TruncatedType;
  2218. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2219. if (RD->isInvalidDecl()) return false;
  2220. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2221. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2222. if (isVirtualBaseClass(D.Entries[I]))
  2223. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2224. else
  2225. Result.Offset -= Layout.getBaseClassOffset(Base);
  2226. RD = Base;
  2227. }
  2228. D.Entries.resize(TruncatedElements);
  2229. return true;
  2230. }
  2231. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2232. const CXXRecordDecl *Derived,
  2233. const CXXRecordDecl *Base,
  2234. const ASTRecordLayout *RL = nullptr) {
  2235. if (!RL) {
  2236. if (Derived->isInvalidDecl()) return false;
  2237. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2238. }
  2239. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2240. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2241. return true;
  2242. }
  2243. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2244. const CXXRecordDecl *DerivedDecl,
  2245. const CXXBaseSpecifier *Base) {
  2246. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2247. if (!Base->isVirtual())
  2248. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2249. SubobjectDesignator &D = Obj.Designator;
  2250. if (D.Invalid)
  2251. return false;
  2252. // Extract most-derived object and corresponding type.
  2253. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2254. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2255. return false;
  2256. // Find the virtual base class.
  2257. if (DerivedDecl->isInvalidDecl()) return false;
  2258. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2259. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2260. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2261. return true;
  2262. }
  2263. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2264. QualType Type, LValue &Result) {
  2265. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2266. PathE = E->path_end();
  2267. PathI != PathE; ++PathI) {
  2268. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2269. *PathI))
  2270. return false;
  2271. Type = (*PathI)->getType();
  2272. }
  2273. return true;
  2274. }
  2275. /// Cast an lvalue referring to a derived class to a known base subobject.
  2276. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2277. const CXXRecordDecl *DerivedRD,
  2278. const CXXRecordDecl *BaseRD) {
  2279. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2280. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2281. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2282. llvm_unreachable("Class must be derived from the passed in base class!");
  2283. for (CXXBasePathElement &Elem : Paths.front())
  2284. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2285. return false;
  2286. return true;
  2287. }
  2288. /// Update LVal to refer to the given field, which must be a member of the type
  2289. /// currently described by LVal.
  2290. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2291. const FieldDecl *FD,
  2292. const ASTRecordLayout *RL = nullptr) {
  2293. if (!RL) {
  2294. if (FD->getParent()->isInvalidDecl()) return false;
  2295. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2296. }
  2297. unsigned I = FD->getFieldIndex();
  2298. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2299. LVal.addDecl(Info, E, FD);
  2300. return true;
  2301. }
  2302. /// Update LVal to refer to the given indirect field.
  2303. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2304. LValue &LVal,
  2305. const IndirectFieldDecl *IFD) {
  2306. for (const auto *C : IFD->chain())
  2307. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2308. return false;
  2309. return true;
  2310. }
  2311. /// Get the size of the given type in char units.
  2312. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2313. QualType Type, CharUnits &Size) {
  2314. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2315. // extension.
  2316. if (Type->isVoidType() || Type->isFunctionType()) {
  2317. Size = CharUnits::One();
  2318. return true;
  2319. }
  2320. if (Type->isDependentType()) {
  2321. Info.FFDiag(Loc);
  2322. return false;
  2323. }
  2324. if (!Type->isConstantSizeType()) {
  2325. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2326. // FIXME: Better diagnostic.
  2327. Info.FFDiag(Loc);
  2328. return false;
  2329. }
  2330. Size = Info.Ctx.getTypeSizeInChars(Type);
  2331. return true;
  2332. }
  2333. /// Update a pointer value to model pointer arithmetic.
  2334. /// \param Info - Information about the ongoing evaluation.
  2335. /// \param E - The expression being evaluated, for diagnostic purposes.
  2336. /// \param LVal - The pointer value to be updated.
  2337. /// \param EltTy - The pointee type represented by LVal.
  2338. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2339. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2340. LValue &LVal, QualType EltTy,
  2341. APSInt Adjustment) {
  2342. CharUnits SizeOfPointee;
  2343. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2344. return false;
  2345. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2346. return true;
  2347. }
  2348. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2349. LValue &LVal, QualType EltTy,
  2350. int64_t Adjustment) {
  2351. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2352. APSInt::get(Adjustment));
  2353. }
  2354. /// Update an lvalue to refer to a component of a complex number.
  2355. /// \param Info - Information about the ongoing evaluation.
  2356. /// \param LVal - The lvalue to be updated.
  2357. /// \param EltTy - The complex number's component type.
  2358. /// \param Imag - False for the real component, true for the imaginary.
  2359. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2360. LValue &LVal, QualType EltTy,
  2361. bool Imag) {
  2362. if (Imag) {
  2363. CharUnits SizeOfComponent;
  2364. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2365. return false;
  2366. LVal.Offset += SizeOfComponent;
  2367. }
  2368. LVal.addComplex(Info, E, EltTy, Imag);
  2369. return true;
  2370. }
  2371. /// Try to evaluate the initializer for a variable declaration.
  2372. ///
  2373. /// \param Info Information about the ongoing evaluation.
  2374. /// \param E An expression to be used when printing diagnostics.
  2375. /// \param VD The variable whose initializer should be obtained.
  2376. /// \param Frame The frame in which the variable was created. Must be null
  2377. /// if this variable is not local to the evaluation.
  2378. /// \param Result Filled in with a pointer to the value of the variable.
  2379. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2380. const VarDecl *VD, CallStackFrame *Frame,
  2381. APValue *&Result, const LValue *LVal) {
  2382. // If this is a parameter to an active constexpr function call, perform
  2383. // argument substitution.
  2384. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2385. // Assume arguments of a potential constant expression are unknown
  2386. // constant expressions.
  2387. if (Info.checkingPotentialConstantExpression())
  2388. return false;
  2389. if (!Frame || !Frame->Arguments) {
  2390. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2391. return false;
  2392. }
  2393. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2394. return true;
  2395. }
  2396. // If this is a local variable, dig out its value.
  2397. if (Frame) {
  2398. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2399. : Frame->getCurrentTemporary(VD);
  2400. if (!Result) {
  2401. // Assume variables referenced within a lambda's call operator that were
  2402. // not declared within the call operator are captures and during checking
  2403. // of a potential constant expression, assume they are unknown constant
  2404. // expressions.
  2405. assert(isLambdaCallOperator(Frame->Callee) &&
  2406. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2407. "missing value for local variable");
  2408. if (Info.checkingPotentialConstantExpression())
  2409. return false;
  2410. // FIXME: implement capture evaluation during constant expr evaluation.
  2411. Info.FFDiag(E->getBeginLoc(),
  2412. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2413. << "captures not currently allowed";
  2414. return false;
  2415. }
  2416. return true;
  2417. }
  2418. // Dig out the initializer, and use the declaration which it's attached to.
  2419. const Expr *Init = VD->getAnyInitializer(VD);
  2420. if (!Init || Init->isValueDependent()) {
  2421. // If we're checking a potential constant expression, the variable could be
  2422. // initialized later.
  2423. if (!Info.checkingPotentialConstantExpression())
  2424. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2425. return false;
  2426. }
  2427. // If we're currently evaluating the initializer of this declaration, use that
  2428. // in-flight value.
  2429. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2430. Result = Info.EvaluatingDeclValue;
  2431. return true;
  2432. }
  2433. // Never evaluate the initializer of a weak variable. We can't be sure that
  2434. // this is the definition which will be used.
  2435. if (VD->isWeak()) {
  2436. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2437. return false;
  2438. }
  2439. // Check that we can fold the initializer. In C++, we will have already done
  2440. // this in the cases where it matters for conformance.
  2441. SmallVector<PartialDiagnosticAt, 8> Notes;
  2442. if (!VD->evaluateValue(Notes)) {
  2443. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2444. Notes.size() + 1) << VD;
  2445. Info.Note(VD->getLocation(), diag::note_declared_at);
  2446. Info.addNotes(Notes);
  2447. return false;
  2448. } else if (!VD->checkInitIsICE()) {
  2449. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2450. Notes.size() + 1) << VD;
  2451. Info.Note(VD->getLocation(), diag::note_declared_at);
  2452. Info.addNotes(Notes);
  2453. }
  2454. Result = VD->getEvaluatedValue();
  2455. return true;
  2456. }
  2457. static bool IsConstNonVolatile(QualType T) {
  2458. Qualifiers Quals = T.getQualifiers();
  2459. return Quals.hasConst() && !Quals.hasVolatile();
  2460. }
  2461. /// Get the base index of the given base class within an APValue representing
  2462. /// the given derived class.
  2463. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2464. const CXXRecordDecl *Base) {
  2465. Base = Base->getCanonicalDecl();
  2466. unsigned Index = 0;
  2467. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2468. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2469. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2470. return Index;
  2471. }
  2472. llvm_unreachable("base class missing from derived class's bases list");
  2473. }
  2474. /// Extract the value of a character from a string literal.
  2475. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2476. uint64_t Index) {
  2477. assert(!isa<SourceLocExpr>(Lit) &&
  2478. "SourceLocExpr should have already been converted to a StringLiteral");
  2479. // FIXME: Support MakeStringConstant
  2480. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2481. std::string Str;
  2482. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2483. assert(Index <= Str.size() && "Index too large");
  2484. return APSInt::getUnsigned(Str.c_str()[Index]);
  2485. }
  2486. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2487. Lit = PE->getFunctionName();
  2488. const StringLiteral *S = cast<StringLiteral>(Lit);
  2489. const ConstantArrayType *CAT =
  2490. Info.Ctx.getAsConstantArrayType(S->getType());
  2491. assert(CAT && "string literal isn't an array");
  2492. QualType CharType = CAT->getElementType();
  2493. assert(CharType->isIntegerType() && "unexpected character type");
  2494. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2495. CharType->isUnsignedIntegerType());
  2496. if (Index < S->getLength())
  2497. Value = S->getCodeUnit(Index);
  2498. return Value;
  2499. }
  2500. // Expand a string literal into an array of characters.
  2501. //
  2502. // FIXME: This is inefficient; we should probably introduce something similar
  2503. // to the LLVM ConstantDataArray to make this cheaper.
  2504. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2505. APValue &Result) {
  2506. const ConstantArrayType *CAT =
  2507. Info.Ctx.getAsConstantArrayType(S->getType());
  2508. assert(CAT && "string literal isn't an array");
  2509. QualType CharType = CAT->getElementType();
  2510. assert(CharType->isIntegerType() && "unexpected character type");
  2511. unsigned Elts = CAT->getSize().getZExtValue();
  2512. Result = APValue(APValue::UninitArray(),
  2513. std::min(S->getLength(), Elts), Elts);
  2514. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2515. CharType->isUnsignedIntegerType());
  2516. if (Result.hasArrayFiller())
  2517. Result.getArrayFiller() = APValue(Value);
  2518. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2519. Value = S->getCodeUnit(I);
  2520. Result.getArrayInitializedElt(I) = APValue(Value);
  2521. }
  2522. }
  2523. // Expand an array so that it has more than Index filled elements.
  2524. static void expandArray(APValue &Array, unsigned Index) {
  2525. unsigned Size = Array.getArraySize();
  2526. assert(Index < Size);
  2527. // Always at least double the number of elements for which we store a value.
  2528. unsigned OldElts = Array.getArrayInitializedElts();
  2529. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2530. NewElts = std::min(Size, std::max(NewElts, 8u));
  2531. // Copy the data across.
  2532. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2533. for (unsigned I = 0; I != OldElts; ++I)
  2534. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2535. for (unsigned I = OldElts; I != NewElts; ++I)
  2536. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2537. if (NewValue.hasArrayFiller())
  2538. NewValue.getArrayFiller() = Array.getArrayFiller();
  2539. Array.swap(NewValue);
  2540. }
  2541. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2542. /// conversion. If it's of class type, we may assume that the copy operation
  2543. /// is trivial. Note that this is never true for a union type with fields
  2544. /// (because the copy always "reads" the active member) and always true for
  2545. /// a non-class type.
  2546. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2547. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2548. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2549. return true;
  2550. if (RD->isEmpty())
  2551. return false;
  2552. for (auto *Field : RD->fields())
  2553. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2554. return true;
  2555. for (auto &BaseSpec : RD->bases())
  2556. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2557. return true;
  2558. return false;
  2559. }
  2560. /// Diagnose an attempt to read from any unreadable field within the specified
  2561. /// type, which might be a class type.
  2562. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2563. QualType T) {
  2564. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2565. if (!RD)
  2566. return false;
  2567. if (!RD->hasMutableFields())
  2568. return false;
  2569. for (auto *Field : RD->fields()) {
  2570. // If we're actually going to read this field in some way, then it can't
  2571. // be mutable. If we're in a union, then assigning to a mutable field
  2572. // (even an empty one) can change the active member, so that's not OK.
  2573. // FIXME: Add core issue number for the union case.
  2574. if (Field->isMutable() &&
  2575. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2576. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2577. Info.Note(Field->getLocation(), diag::note_declared_at);
  2578. return true;
  2579. }
  2580. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2581. return true;
  2582. }
  2583. for (auto &BaseSpec : RD->bases())
  2584. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2585. return true;
  2586. // All mutable fields were empty, and thus not actually read.
  2587. return false;
  2588. }
  2589. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2590. APValue::LValueBase Base) {
  2591. // A temporary we created.
  2592. if (Base.getCallIndex())
  2593. return true;
  2594. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2595. if (!Evaluating)
  2596. return false;
  2597. // The variable whose initializer we're evaluating.
  2598. if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
  2599. if (declaresSameEntity(Evaluating, BaseD))
  2600. return true;
  2601. // A temporary lifetime-extended by the variable whose initializer we're
  2602. // evaluating.
  2603. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2604. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2605. if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
  2606. return true;
  2607. return false;
  2608. }
  2609. namespace {
  2610. /// A handle to a complete object (an object that is not a subobject of
  2611. /// another object).
  2612. struct CompleteObject {
  2613. /// The identity of the object.
  2614. APValue::LValueBase Base;
  2615. /// The value of the complete object.
  2616. APValue *Value;
  2617. /// The type of the complete object.
  2618. QualType Type;
  2619. CompleteObject() : Value(nullptr) {}
  2620. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2621. : Base(Base), Value(Value), Type(Type) {}
  2622. bool mayReadMutableMembers(EvalInfo &Info) const {
  2623. // In C++14 onwards, it is permitted to read a mutable member whose
  2624. // lifetime began within the evaluation.
  2625. // FIXME: Should we also allow this in C++11?
  2626. if (!Info.getLangOpts().CPlusPlus14)
  2627. return false;
  2628. return lifetimeStartedInEvaluation(Info, Base);
  2629. }
  2630. explicit operator bool() const { return !Type.isNull(); }
  2631. };
  2632. } // end anonymous namespace
  2633. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2634. bool IsMutable = false) {
  2635. // C++ [basic.type.qualifier]p1:
  2636. // - A const object is an object of type const T or a non-mutable subobject
  2637. // of a const object.
  2638. if (ObjType.isConstQualified() && !IsMutable)
  2639. SubobjType.addConst();
  2640. // - A volatile object is an object of type const T or a subobject of a
  2641. // volatile object.
  2642. if (ObjType.isVolatileQualified())
  2643. SubobjType.addVolatile();
  2644. return SubobjType;
  2645. }
  2646. /// Find the designated sub-object of an rvalue.
  2647. template<typename SubobjectHandler>
  2648. typename SubobjectHandler::result_type
  2649. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2650. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2651. if (Sub.Invalid)
  2652. // A diagnostic will have already been produced.
  2653. return handler.failed();
  2654. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2655. if (Info.getLangOpts().CPlusPlus11)
  2656. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2657. ? diag::note_constexpr_access_past_end
  2658. : diag::note_constexpr_access_unsized_array)
  2659. << handler.AccessKind;
  2660. else
  2661. Info.FFDiag(E);
  2662. return handler.failed();
  2663. }
  2664. APValue *O = Obj.Value;
  2665. QualType ObjType = Obj.Type;
  2666. const FieldDecl *LastField = nullptr;
  2667. const FieldDecl *VolatileField = nullptr;
  2668. // Walk the designator's path to find the subobject.
  2669. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2670. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2671. if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
  2672. if (!Info.checkingPotentialConstantExpression())
  2673. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2674. << handler.AccessKind << O->isIndeterminate();
  2675. return handler.failed();
  2676. }
  2677. // C++ [class.ctor]p5:
  2678. // const and volatile semantics are not applied on an object under
  2679. // construction.
  2680. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2681. ObjType->isRecordType() &&
  2682. Info.isEvaluatingConstructor(
  2683. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2684. Sub.Entries.begin() + I)) !=
  2685. ConstructionPhase::None) {
  2686. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2687. ObjType.removeLocalConst();
  2688. ObjType.removeLocalVolatile();
  2689. }
  2690. // If this is our last pass, check that the final object type is OK.
  2691. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2692. // Accesses to volatile objects are prohibited.
  2693. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2694. if (Info.getLangOpts().CPlusPlus) {
  2695. int DiagKind;
  2696. SourceLocation Loc;
  2697. const NamedDecl *Decl = nullptr;
  2698. if (VolatileField) {
  2699. DiagKind = 2;
  2700. Loc = VolatileField->getLocation();
  2701. Decl = VolatileField;
  2702. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2703. DiagKind = 1;
  2704. Loc = VD->getLocation();
  2705. Decl = VD;
  2706. } else {
  2707. DiagKind = 0;
  2708. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2709. Loc = E->getExprLoc();
  2710. }
  2711. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2712. << handler.AccessKind << DiagKind << Decl;
  2713. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2714. } else {
  2715. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2716. }
  2717. return handler.failed();
  2718. }
  2719. // If we are reading an object of class type, there may still be more
  2720. // things we need to check: if there are any mutable subobjects, we
  2721. // cannot perform this read. (This only happens when performing a trivial
  2722. // copy or assignment.)
  2723. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2724. !Obj.mayReadMutableMembers(Info) &&
  2725. diagnoseUnreadableFields(Info, E, ObjType))
  2726. return handler.failed();
  2727. }
  2728. if (I == N) {
  2729. if (!handler.found(*O, ObjType))
  2730. return false;
  2731. // If we modified a bit-field, truncate it to the right width.
  2732. if (isModification(handler.AccessKind) &&
  2733. LastField && LastField->isBitField() &&
  2734. !truncateBitfieldValue(Info, E, *O, LastField))
  2735. return false;
  2736. return true;
  2737. }
  2738. LastField = nullptr;
  2739. if (ObjType->isArrayType()) {
  2740. // Next subobject is an array element.
  2741. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2742. assert(CAT && "vla in literal type?");
  2743. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2744. if (CAT->getSize().ule(Index)) {
  2745. // Note, it should not be possible to form a pointer with a valid
  2746. // designator which points more than one past the end of the array.
  2747. if (Info.getLangOpts().CPlusPlus11)
  2748. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2749. << handler.AccessKind;
  2750. else
  2751. Info.FFDiag(E);
  2752. return handler.failed();
  2753. }
  2754. ObjType = CAT->getElementType();
  2755. if (O->getArrayInitializedElts() > Index)
  2756. O = &O->getArrayInitializedElt(Index);
  2757. else if (handler.AccessKind != AK_Read) {
  2758. expandArray(*O, Index);
  2759. O = &O->getArrayInitializedElt(Index);
  2760. } else
  2761. O = &O->getArrayFiller();
  2762. } else if (ObjType->isAnyComplexType()) {
  2763. // Next subobject is a complex number.
  2764. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2765. if (Index > 1) {
  2766. if (Info.getLangOpts().CPlusPlus11)
  2767. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2768. << handler.AccessKind;
  2769. else
  2770. Info.FFDiag(E);
  2771. return handler.failed();
  2772. }
  2773. ObjType = getSubobjectType(
  2774. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2775. assert(I == N - 1 && "extracting subobject of scalar?");
  2776. if (O->isComplexInt()) {
  2777. return handler.found(Index ? O->getComplexIntImag()
  2778. : O->getComplexIntReal(), ObjType);
  2779. } else {
  2780. assert(O->isComplexFloat());
  2781. return handler.found(Index ? O->getComplexFloatImag()
  2782. : O->getComplexFloatReal(), ObjType);
  2783. }
  2784. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2785. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2786. !Obj.mayReadMutableMembers(Info)) {
  2787. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2788. << Field;
  2789. Info.Note(Field->getLocation(), diag::note_declared_at);
  2790. return handler.failed();
  2791. }
  2792. // Next subobject is a class, struct or union field.
  2793. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2794. if (RD->isUnion()) {
  2795. const FieldDecl *UnionField = O->getUnionField();
  2796. if (!UnionField ||
  2797. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2798. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2799. << handler.AccessKind << Field << !UnionField << UnionField;
  2800. return handler.failed();
  2801. }
  2802. O = &O->getUnionValue();
  2803. } else
  2804. O = &O->getStructField(Field->getFieldIndex());
  2805. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2806. LastField = Field;
  2807. if (Field->getType().isVolatileQualified())
  2808. VolatileField = Field;
  2809. } else {
  2810. // Next subobject is a base class.
  2811. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2812. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2813. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2814. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2815. }
  2816. }
  2817. }
  2818. namespace {
  2819. struct ExtractSubobjectHandler {
  2820. EvalInfo &Info;
  2821. APValue &Result;
  2822. static const AccessKinds AccessKind = AK_Read;
  2823. typedef bool result_type;
  2824. bool failed() { return false; }
  2825. bool found(APValue &Subobj, QualType SubobjType) {
  2826. Result = Subobj;
  2827. return true;
  2828. }
  2829. bool found(APSInt &Value, QualType SubobjType) {
  2830. Result = APValue(Value);
  2831. return true;
  2832. }
  2833. bool found(APFloat &Value, QualType SubobjType) {
  2834. Result = APValue(Value);
  2835. return true;
  2836. }
  2837. };
  2838. } // end anonymous namespace
  2839. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2840. /// Extract the designated sub-object of an rvalue.
  2841. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2842. const CompleteObject &Obj,
  2843. const SubobjectDesignator &Sub,
  2844. APValue &Result) {
  2845. ExtractSubobjectHandler Handler = { Info, Result };
  2846. return findSubobject(Info, E, Obj, Sub, Handler);
  2847. }
  2848. namespace {
  2849. struct ModifySubobjectHandler {
  2850. EvalInfo &Info;
  2851. APValue &NewVal;
  2852. const Expr *E;
  2853. typedef bool result_type;
  2854. static const AccessKinds AccessKind = AK_Assign;
  2855. bool checkConst(QualType QT) {
  2856. // Assigning to a const object has undefined behavior.
  2857. if (QT.isConstQualified()) {
  2858. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2859. return false;
  2860. }
  2861. return true;
  2862. }
  2863. bool failed() { return false; }
  2864. bool found(APValue &Subobj, QualType SubobjType) {
  2865. if (!checkConst(SubobjType))
  2866. return false;
  2867. // We've been given ownership of NewVal, so just swap it in.
  2868. Subobj.swap(NewVal);
  2869. return true;
  2870. }
  2871. bool found(APSInt &Value, QualType SubobjType) {
  2872. if (!checkConst(SubobjType))
  2873. return false;
  2874. if (!NewVal.isInt()) {
  2875. // Maybe trying to write a cast pointer value into a complex?
  2876. Info.FFDiag(E);
  2877. return false;
  2878. }
  2879. Value = NewVal.getInt();
  2880. return true;
  2881. }
  2882. bool found(APFloat &Value, QualType SubobjType) {
  2883. if (!checkConst(SubobjType))
  2884. return false;
  2885. Value = NewVal.getFloat();
  2886. return true;
  2887. }
  2888. };
  2889. } // end anonymous namespace
  2890. const AccessKinds ModifySubobjectHandler::AccessKind;
  2891. /// Update the designated sub-object of an rvalue to the given value.
  2892. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2893. const CompleteObject &Obj,
  2894. const SubobjectDesignator &Sub,
  2895. APValue &NewVal) {
  2896. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2897. return findSubobject(Info, E, Obj, Sub, Handler);
  2898. }
  2899. /// Find the position where two subobject designators diverge, or equivalently
  2900. /// the length of the common initial subsequence.
  2901. static unsigned FindDesignatorMismatch(QualType ObjType,
  2902. const SubobjectDesignator &A,
  2903. const SubobjectDesignator &B,
  2904. bool &WasArrayIndex) {
  2905. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2906. for (/**/; I != N; ++I) {
  2907. if (!ObjType.isNull() &&
  2908. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2909. // Next subobject is an array element.
  2910. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  2911. WasArrayIndex = true;
  2912. return I;
  2913. }
  2914. if (ObjType->isAnyComplexType())
  2915. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2916. else
  2917. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2918. } else {
  2919. if (A.Entries[I].getAsBaseOrMember() !=
  2920. B.Entries[I].getAsBaseOrMember()) {
  2921. WasArrayIndex = false;
  2922. return I;
  2923. }
  2924. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2925. // Next subobject is a field.
  2926. ObjType = FD->getType();
  2927. else
  2928. // Next subobject is a base class.
  2929. ObjType = QualType();
  2930. }
  2931. }
  2932. WasArrayIndex = false;
  2933. return I;
  2934. }
  2935. /// Determine whether the given subobject designators refer to elements of the
  2936. /// same array object.
  2937. static bool AreElementsOfSameArray(QualType ObjType,
  2938. const SubobjectDesignator &A,
  2939. const SubobjectDesignator &B) {
  2940. if (A.Entries.size() != B.Entries.size())
  2941. return false;
  2942. bool IsArray = A.MostDerivedIsArrayElement;
  2943. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2944. // A is a subobject of the array element.
  2945. return false;
  2946. // If A (and B) designates an array element, the last entry will be the array
  2947. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2948. // of length 1' case, and the entire path must match.
  2949. bool WasArrayIndex;
  2950. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2951. return CommonLength >= A.Entries.size() - IsArray;
  2952. }
  2953. /// Find the complete object to which an LValue refers.
  2954. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2955. AccessKinds AK, const LValue &LVal,
  2956. QualType LValType) {
  2957. if (LVal.InvalidBase) {
  2958. Info.FFDiag(E);
  2959. return CompleteObject();
  2960. }
  2961. if (!LVal.Base) {
  2962. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2963. return CompleteObject();
  2964. }
  2965. CallStackFrame *Frame = nullptr;
  2966. unsigned Depth = 0;
  2967. if (LVal.getLValueCallIndex()) {
  2968. std::tie(Frame, Depth) =
  2969. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  2970. if (!Frame) {
  2971. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2972. << AK << LVal.Base.is<const ValueDecl*>();
  2973. NoteLValueLocation(Info, LVal.Base);
  2974. return CompleteObject();
  2975. }
  2976. }
  2977. bool IsAccess = isFormalAccess(AK);
  2978. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2979. // is not a constant expression (even if the object is non-volatile). We also
  2980. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2981. // semantics.
  2982. if (IsAccess && LValType.isVolatileQualified()) {
  2983. if (Info.getLangOpts().CPlusPlus)
  2984. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2985. << AK << LValType;
  2986. else
  2987. Info.FFDiag(E);
  2988. return CompleteObject();
  2989. }
  2990. // Compute value storage location and type of base object.
  2991. APValue *BaseVal = nullptr;
  2992. QualType BaseType = getType(LVal.Base);
  2993. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2994. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2995. // In C++11, constexpr, non-volatile variables initialized with constant
  2996. // expressions are constant expressions too. Inside constexpr functions,
  2997. // parameters are constant expressions even if they're non-const.
  2998. // In C++1y, objects local to a constant expression (those with a Frame) are
  2999. // both readable and writable inside constant expressions.
  3000. // In C, such things can also be folded, although they are not ICEs.
  3001. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3002. if (VD) {
  3003. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3004. VD = VDef;
  3005. }
  3006. if (!VD || VD->isInvalidDecl()) {
  3007. Info.FFDiag(E);
  3008. return CompleteObject();
  3009. }
  3010. // Unless we're looking at a local variable or argument in a constexpr call,
  3011. // the variable we're reading must be const.
  3012. if (!Frame) {
  3013. if (Info.getLangOpts().CPlusPlus14 &&
  3014. declaresSameEntity(
  3015. VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
  3016. // OK, we can read and modify an object if we're in the process of
  3017. // evaluating its initializer, because its lifetime began in this
  3018. // evaluation.
  3019. } else if (isModification(AK)) {
  3020. // All the remaining cases do not permit modification of the object.
  3021. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3022. return CompleteObject();
  3023. } else if (VD->isConstexpr()) {
  3024. // OK, we can read this variable.
  3025. } else if (BaseType->isIntegralOrEnumerationType()) {
  3026. // In OpenCL if a variable is in constant address space it is a const
  3027. // value.
  3028. if (!(BaseType.isConstQualified() ||
  3029. (Info.getLangOpts().OpenCL &&
  3030. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  3031. if (!IsAccess)
  3032. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3033. if (Info.getLangOpts().CPlusPlus) {
  3034. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3035. Info.Note(VD->getLocation(), diag::note_declared_at);
  3036. } else {
  3037. Info.FFDiag(E);
  3038. }
  3039. return CompleteObject();
  3040. }
  3041. } else if (!IsAccess) {
  3042. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3043. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  3044. // We support folding of const floating-point types, in order to make
  3045. // static const data members of such types (supported as an extension)
  3046. // more useful.
  3047. if (Info.getLangOpts().CPlusPlus11) {
  3048. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3049. Info.Note(VD->getLocation(), diag::note_declared_at);
  3050. } else {
  3051. Info.CCEDiag(E);
  3052. }
  3053. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3054. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3055. // Keep evaluating to see what we can do.
  3056. } else {
  3057. // FIXME: Allow folding of values of any literal type in all languages.
  3058. if (Info.checkingPotentialConstantExpression() &&
  3059. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3060. // The definition of this variable could be constexpr. We can't
  3061. // access it right now, but may be able to in future.
  3062. } else if (Info.getLangOpts().CPlusPlus11) {
  3063. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3064. Info.Note(VD->getLocation(), diag::note_declared_at);
  3065. } else {
  3066. Info.FFDiag(E);
  3067. }
  3068. return CompleteObject();
  3069. }
  3070. }
  3071. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3072. return CompleteObject();
  3073. } else {
  3074. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3075. if (!Frame) {
  3076. if (const MaterializeTemporaryExpr *MTE =
  3077. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3078. assert(MTE->getStorageDuration() == SD_Static &&
  3079. "should have a frame for a non-global materialized temporary");
  3080. // Per C++1y [expr.const]p2:
  3081. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3082. // - a [...] glvalue of integral or enumeration type that refers to
  3083. // a non-volatile const object [...]
  3084. // [...]
  3085. // - a [...] glvalue of literal type that refers to a non-volatile
  3086. // object whose lifetime began within the evaluation of e.
  3087. //
  3088. // C++11 misses the 'began within the evaluation of e' check and
  3089. // instead allows all temporaries, including things like:
  3090. // int &&r = 1;
  3091. // int x = ++r;
  3092. // constexpr int k = r;
  3093. // Therefore we use the C++14 rules in C++11 too.
  3094. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  3095. const ValueDecl *ED = MTE->getExtendingDecl();
  3096. if (!(BaseType.isConstQualified() &&
  3097. BaseType->isIntegralOrEnumerationType()) &&
  3098. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  3099. if (!IsAccess)
  3100. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3101. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3102. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3103. return CompleteObject();
  3104. }
  3105. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3106. assert(BaseVal && "got reference to unevaluated temporary");
  3107. } else {
  3108. if (!IsAccess)
  3109. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3110. APValue Val;
  3111. LVal.moveInto(Val);
  3112. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3113. << AK
  3114. << Val.getAsString(Info.Ctx,
  3115. Info.Ctx.getLValueReferenceType(LValType));
  3116. NoteLValueLocation(Info, LVal.Base);
  3117. return CompleteObject();
  3118. }
  3119. } else {
  3120. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3121. assert(BaseVal && "missing value for temporary");
  3122. }
  3123. }
  3124. // In C++14, we can't safely access any mutable state when we might be
  3125. // evaluating after an unmodeled side effect.
  3126. //
  3127. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3128. // to be read here (but take care with 'mutable' fields).
  3129. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3130. Info.EvalStatus.HasSideEffects) ||
  3131. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3132. return CompleteObject();
  3133. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3134. }
  3135. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3136. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3137. /// glvalue referred to by an entity of reference type.
  3138. ///
  3139. /// \param Info - Information about the ongoing evaluation.
  3140. /// \param Conv - The expression for which we are performing the conversion.
  3141. /// Used for diagnostics.
  3142. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3143. /// case of a non-class type).
  3144. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3145. /// \param RVal - The produced value will be placed here.
  3146. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  3147. QualType Type,
  3148. const LValue &LVal, APValue &RVal) {
  3149. if (LVal.Designator.Invalid)
  3150. return false;
  3151. // Check for special cases where there is no existing APValue to look at.
  3152. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3153. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3154. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3155. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3156. // initializer until now for such expressions. Such an expression can't be
  3157. // an ICE in C, so this only matters for fold.
  3158. if (Type.isVolatileQualified()) {
  3159. Info.FFDiag(Conv);
  3160. return false;
  3161. }
  3162. APValue Lit;
  3163. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3164. return false;
  3165. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3166. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  3167. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3168. // Special-case character extraction so we don't have to construct an
  3169. // APValue for the whole string.
  3170. assert(LVal.Designator.Entries.size() <= 1 &&
  3171. "Can only read characters from string literals");
  3172. if (LVal.Designator.Entries.empty()) {
  3173. // Fail for now for LValue to RValue conversion of an array.
  3174. // (This shouldn't show up in C/C++, but it could be triggered by a
  3175. // weird EvaluateAsRValue call from a tool.)
  3176. Info.FFDiag(Conv);
  3177. return false;
  3178. }
  3179. if (LVal.Designator.isOnePastTheEnd()) {
  3180. if (Info.getLangOpts().CPlusPlus11)
  3181. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
  3182. else
  3183. Info.FFDiag(Conv);
  3184. return false;
  3185. }
  3186. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3187. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3188. return true;
  3189. }
  3190. }
  3191. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3192. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3193. }
  3194. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3195. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3196. QualType LValType, APValue &Val) {
  3197. if (LVal.Designator.Invalid)
  3198. return false;
  3199. if (!Info.getLangOpts().CPlusPlus14) {
  3200. Info.FFDiag(E);
  3201. return false;
  3202. }
  3203. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3204. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3205. }
  3206. namespace {
  3207. struct CompoundAssignSubobjectHandler {
  3208. EvalInfo &Info;
  3209. const Expr *E;
  3210. QualType PromotedLHSType;
  3211. BinaryOperatorKind Opcode;
  3212. const APValue &RHS;
  3213. static const AccessKinds AccessKind = AK_Assign;
  3214. typedef bool result_type;
  3215. bool checkConst(QualType QT) {
  3216. // Assigning to a const object has undefined behavior.
  3217. if (QT.isConstQualified()) {
  3218. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3219. return false;
  3220. }
  3221. return true;
  3222. }
  3223. bool failed() { return false; }
  3224. bool found(APValue &Subobj, QualType SubobjType) {
  3225. switch (Subobj.getKind()) {
  3226. case APValue::Int:
  3227. return found(Subobj.getInt(), SubobjType);
  3228. case APValue::Float:
  3229. return found(Subobj.getFloat(), SubobjType);
  3230. case APValue::ComplexInt:
  3231. case APValue::ComplexFloat:
  3232. // FIXME: Implement complex compound assignment.
  3233. Info.FFDiag(E);
  3234. return false;
  3235. case APValue::LValue:
  3236. return foundPointer(Subobj, SubobjType);
  3237. default:
  3238. // FIXME: can this happen?
  3239. Info.FFDiag(E);
  3240. return false;
  3241. }
  3242. }
  3243. bool found(APSInt &Value, QualType SubobjType) {
  3244. if (!checkConst(SubobjType))
  3245. return false;
  3246. if (!SubobjType->isIntegerType()) {
  3247. // We don't support compound assignment on integer-cast-to-pointer
  3248. // values.
  3249. Info.FFDiag(E);
  3250. return false;
  3251. }
  3252. if (RHS.isInt()) {
  3253. APSInt LHS =
  3254. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3255. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3256. return false;
  3257. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3258. return true;
  3259. } else if (RHS.isFloat()) {
  3260. APFloat FValue(0.0);
  3261. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3262. FValue) &&
  3263. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3264. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3265. Value);
  3266. }
  3267. Info.FFDiag(E);
  3268. return false;
  3269. }
  3270. bool found(APFloat &Value, QualType SubobjType) {
  3271. return checkConst(SubobjType) &&
  3272. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3273. Value) &&
  3274. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3275. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3276. }
  3277. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3278. if (!checkConst(SubobjType))
  3279. return false;
  3280. QualType PointeeType;
  3281. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3282. PointeeType = PT->getPointeeType();
  3283. if (PointeeType.isNull() || !RHS.isInt() ||
  3284. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3285. Info.FFDiag(E);
  3286. return false;
  3287. }
  3288. APSInt Offset = RHS.getInt();
  3289. if (Opcode == BO_Sub)
  3290. negateAsSigned(Offset);
  3291. LValue LVal;
  3292. LVal.setFrom(Info.Ctx, Subobj);
  3293. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3294. return false;
  3295. LVal.moveInto(Subobj);
  3296. return true;
  3297. }
  3298. };
  3299. } // end anonymous namespace
  3300. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3301. /// Perform a compound assignment of LVal <op>= RVal.
  3302. static bool handleCompoundAssignment(
  3303. EvalInfo &Info, const Expr *E,
  3304. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3305. BinaryOperatorKind Opcode, const APValue &RVal) {
  3306. if (LVal.Designator.Invalid)
  3307. return false;
  3308. if (!Info.getLangOpts().CPlusPlus14) {
  3309. Info.FFDiag(E);
  3310. return false;
  3311. }
  3312. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3313. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3314. RVal };
  3315. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3316. }
  3317. namespace {
  3318. struct IncDecSubobjectHandler {
  3319. EvalInfo &Info;
  3320. const UnaryOperator *E;
  3321. AccessKinds AccessKind;
  3322. APValue *Old;
  3323. typedef bool result_type;
  3324. bool checkConst(QualType QT) {
  3325. // Assigning to a const object has undefined behavior.
  3326. if (QT.isConstQualified()) {
  3327. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3328. return false;
  3329. }
  3330. return true;
  3331. }
  3332. bool failed() { return false; }
  3333. bool found(APValue &Subobj, QualType SubobjType) {
  3334. // Stash the old value. Also clear Old, so we don't clobber it later
  3335. // if we're post-incrementing a complex.
  3336. if (Old) {
  3337. *Old = Subobj;
  3338. Old = nullptr;
  3339. }
  3340. switch (Subobj.getKind()) {
  3341. case APValue::Int:
  3342. return found(Subobj.getInt(), SubobjType);
  3343. case APValue::Float:
  3344. return found(Subobj.getFloat(), SubobjType);
  3345. case APValue::ComplexInt:
  3346. return found(Subobj.getComplexIntReal(),
  3347. SubobjType->castAs<ComplexType>()->getElementType()
  3348. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3349. case APValue::ComplexFloat:
  3350. return found(Subobj.getComplexFloatReal(),
  3351. SubobjType->castAs<ComplexType>()->getElementType()
  3352. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3353. case APValue::LValue:
  3354. return foundPointer(Subobj, SubobjType);
  3355. default:
  3356. // FIXME: can this happen?
  3357. Info.FFDiag(E);
  3358. return false;
  3359. }
  3360. }
  3361. bool found(APSInt &Value, QualType SubobjType) {
  3362. if (!checkConst(SubobjType))
  3363. return false;
  3364. if (!SubobjType->isIntegerType()) {
  3365. // We don't support increment / decrement on integer-cast-to-pointer
  3366. // values.
  3367. Info.FFDiag(E);
  3368. return false;
  3369. }
  3370. if (Old) *Old = APValue(Value);
  3371. // bool arithmetic promotes to int, and the conversion back to bool
  3372. // doesn't reduce mod 2^n, so special-case it.
  3373. if (SubobjType->isBooleanType()) {
  3374. if (AccessKind == AK_Increment)
  3375. Value = 1;
  3376. else
  3377. Value = !Value;
  3378. return true;
  3379. }
  3380. bool WasNegative = Value.isNegative();
  3381. if (AccessKind == AK_Increment) {
  3382. ++Value;
  3383. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3384. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3385. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3386. }
  3387. } else {
  3388. --Value;
  3389. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3390. unsigned BitWidth = Value.getBitWidth();
  3391. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3392. ActualValue.setBit(BitWidth);
  3393. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3394. }
  3395. }
  3396. return true;
  3397. }
  3398. bool found(APFloat &Value, QualType SubobjType) {
  3399. if (!checkConst(SubobjType))
  3400. return false;
  3401. if (Old) *Old = APValue(Value);
  3402. APFloat One(Value.getSemantics(), 1);
  3403. if (AccessKind == AK_Increment)
  3404. Value.add(One, APFloat::rmNearestTiesToEven);
  3405. else
  3406. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3407. return true;
  3408. }
  3409. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3410. if (!checkConst(SubobjType))
  3411. return false;
  3412. QualType PointeeType;
  3413. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3414. PointeeType = PT->getPointeeType();
  3415. else {
  3416. Info.FFDiag(E);
  3417. return false;
  3418. }
  3419. LValue LVal;
  3420. LVal.setFrom(Info.Ctx, Subobj);
  3421. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3422. AccessKind == AK_Increment ? 1 : -1))
  3423. return false;
  3424. LVal.moveInto(Subobj);
  3425. return true;
  3426. }
  3427. };
  3428. } // end anonymous namespace
  3429. /// Perform an increment or decrement on LVal.
  3430. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3431. QualType LValType, bool IsIncrement, APValue *Old) {
  3432. if (LVal.Designator.Invalid)
  3433. return false;
  3434. if (!Info.getLangOpts().CPlusPlus14) {
  3435. Info.FFDiag(E);
  3436. return false;
  3437. }
  3438. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3439. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3440. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3441. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3442. }
  3443. /// Build an lvalue for the object argument of a member function call.
  3444. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3445. LValue &This) {
  3446. if (Object->getType()->isPointerType())
  3447. return EvaluatePointer(Object, This, Info);
  3448. if (Object->isGLValue())
  3449. return EvaluateLValue(Object, This, Info);
  3450. if (Object->getType()->isLiteralType(Info.Ctx))
  3451. return EvaluateTemporary(Object, This, Info);
  3452. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3453. return false;
  3454. }
  3455. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3456. /// lvalue referring to the result.
  3457. ///
  3458. /// \param Info - Information about the ongoing evaluation.
  3459. /// \param LV - An lvalue referring to the base of the member pointer.
  3460. /// \param RHS - The member pointer expression.
  3461. /// \param IncludeMember - Specifies whether the member itself is included in
  3462. /// the resulting LValue subobject designator. This is not possible when
  3463. /// creating a bound member function.
  3464. /// \return The field or method declaration to which the member pointer refers,
  3465. /// or 0 if evaluation fails.
  3466. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3467. QualType LVType,
  3468. LValue &LV,
  3469. const Expr *RHS,
  3470. bool IncludeMember = true) {
  3471. MemberPtr MemPtr;
  3472. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3473. return nullptr;
  3474. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3475. // member value, the behavior is undefined.
  3476. if (!MemPtr.getDecl()) {
  3477. // FIXME: Specific diagnostic.
  3478. Info.FFDiag(RHS);
  3479. return nullptr;
  3480. }
  3481. if (MemPtr.isDerivedMember()) {
  3482. // This is a member of some derived class. Truncate LV appropriately.
  3483. // The end of the derived-to-base path for the base object must match the
  3484. // derived-to-base path for the member pointer.
  3485. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3486. LV.Designator.Entries.size()) {
  3487. Info.FFDiag(RHS);
  3488. return nullptr;
  3489. }
  3490. unsigned PathLengthToMember =
  3491. LV.Designator.Entries.size() - MemPtr.Path.size();
  3492. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3493. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3494. LV.Designator.Entries[PathLengthToMember + I]);
  3495. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3496. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3497. Info.FFDiag(RHS);
  3498. return nullptr;
  3499. }
  3500. }
  3501. // Truncate the lvalue to the appropriate derived class.
  3502. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3503. PathLengthToMember))
  3504. return nullptr;
  3505. } else if (!MemPtr.Path.empty()) {
  3506. // Extend the LValue path with the member pointer's path.
  3507. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3508. MemPtr.Path.size() + IncludeMember);
  3509. // Walk down to the appropriate base class.
  3510. if (const PointerType *PT = LVType->getAs<PointerType>())
  3511. LVType = PT->getPointeeType();
  3512. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3513. assert(RD && "member pointer access on non-class-type expression");
  3514. // The first class in the path is that of the lvalue.
  3515. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3516. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3517. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3518. return nullptr;
  3519. RD = Base;
  3520. }
  3521. // Finally cast to the class containing the member.
  3522. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3523. MemPtr.getContainingRecord()))
  3524. return nullptr;
  3525. }
  3526. // Add the member. Note that we cannot build bound member functions here.
  3527. if (IncludeMember) {
  3528. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3529. if (!HandleLValueMember(Info, RHS, LV, FD))
  3530. return nullptr;
  3531. } else if (const IndirectFieldDecl *IFD =
  3532. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3533. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3534. return nullptr;
  3535. } else {
  3536. llvm_unreachable("can't construct reference to bound member function");
  3537. }
  3538. }
  3539. return MemPtr.getDecl();
  3540. }
  3541. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3542. const BinaryOperator *BO,
  3543. LValue &LV,
  3544. bool IncludeMember = true) {
  3545. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3546. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3547. if (Info.noteFailure()) {
  3548. MemberPtr MemPtr;
  3549. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3550. }
  3551. return nullptr;
  3552. }
  3553. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3554. BO->getRHS(), IncludeMember);
  3555. }
  3556. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3557. /// the provided lvalue, which currently refers to the base object.
  3558. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3559. LValue &Result) {
  3560. SubobjectDesignator &D = Result.Designator;
  3561. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3562. return false;
  3563. QualType TargetQT = E->getType();
  3564. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3565. TargetQT = PT->getPointeeType();
  3566. // Check this cast lands within the final derived-to-base subobject path.
  3567. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3568. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3569. << D.MostDerivedType << TargetQT;
  3570. return false;
  3571. }
  3572. // Check the type of the final cast. We don't need to check the path,
  3573. // since a cast can only be formed if the path is unique.
  3574. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3575. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3576. const CXXRecordDecl *FinalType;
  3577. if (NewEntriesSize == D.MostDerivedPathLength)
  3578. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3579. else
  3580. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3581. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3582. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3583. << D.MostDerivedType << TargetQT;
  3584. return false;
  3585. }
  3586. // Truncate the lvalue to the appropriate derived class.
  3587. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3588. }
  3589. namespace {
  3590. enum EvalStmtResult {
  3591. /// Evaluation failed.
  3592. ESR_Failed,
  3593. /// Hit a 'return' statement.
  3594. ESR_Returned,
  3595. /// Evaluation succeeded.
  3596. ESR_Succeeded,
  3597. /// Hit a 'continue' statement.
  3598. ESR_Continue,
  3599. /// Hit a 'break' statement.
  3600. ESR_Break,
  3601. /// Still scanning for 'case' or 'default' statement.
  3602. ESR_CaseNotFound
  3603. };
  3604. }
  3605. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3606. // We don't need to evaluate the initializer for a static local.
  3607. if (!VD->hasLocalStorage())
  3608. return true;
  3609. LValue Result;
  3610. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3611. const Expr *InitE = VD->getInit();
  3612. if (!InitE) {
  3613. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3614. << false << VD->getType();
  3615. Val = APValue();
  3616. return false;
  3617. }
  3618. if (InitE->isValueDependent())
  3619. return false;
  3620. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3621. // Wipe out any partially-computed value, to allow tracking that this
  3622. // evaluation failed.
  3623. Val = APValue();
  3624. return false;
  3625. }
  3626. return true;
  3627. }
  3628. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3629. bool OK = true;
  3630. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3631. OK &= EvaluateVarDecl(Info, VD);
  3632. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3633. for (auto *BD : DD->bindings())
  3634. if (auto *VD = BD->getHoldingVar())
  3635. OK &= EvaluateDecl(Info, VD);
  3636. return OK;
  3637. }
  3638. /// Evaluate a condition (either a variable declaration or an expression).
  3639. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3640. const Expr *Cond, bool &Result) {
  3641. FullExpressionRAII Scope(Info);
  3642. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3643. return false;
  3644. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3645. }
  3646. namespace {
  3647. /// A location where the result (returned value) of evaluating a
  3648. /// statement should be stored.
  3649. struct StmtResult {
  3650. /// The APValue that should be filled in with the returned value.
  3651. APValue &Value;
  3652. /// The location containing the result, if any (used to support RVO).
  3653. const LValue *Slot;
  3654. };
  3655. struct TempVersionRAII {
  3656. CallStackFrame &Frame;
  3657. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3658. Frame.pushTempVersion();
  3659. }
  3660. ~TempVersionRAII() {
  3661. Frame.popTempVersion();
  3662. }
  3663. };
  3664. }
  3665. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3666. const Stmt *S,
  3667. const SwitchCase *SC = nullptr);
  3668. /// Evaluate the body of a loop, and translate the result as appropriate.
  3669. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3670. const Stmt *Body,
  3671. const SwitchCase *Case = nullptr) {
  3672. BlockScopeRAII Scope(Info);
  3673. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3674. case ESR_Break:
  3675. return ESR_Succeeded;
  3676. case ESR_Succeeded:
  3677. case ESR_Continue:
  3678. return ESR_Continue;
  3679. case ESR_Failed:
  3680. case ESR_Returned:
  3681. case ESR_CaseNotFound:
  3682. return ESR;
  3683. }
  3684. llvm_unreachable("Invalid EvalStmtResult!");
  3685. }
  3686. /// Evaluate a switch statement.
  3687. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3688. const SwitchStmt *SS) {
  3689. BlockScopeRAII Scope(Info);
  3690. // Evaluate the switch condition.
  3691. APSInt Value;
  3692. {
  3693. FullExpressionRAII Scope(Info);
  3694. if (const Stmt *Init = SS->getInit()) {
  3695. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3696. if (ESR != ESR_Succeeded)
  3697. return ESR;
  3698. }
  3699. if (SS->getConditionVariable() &&
  3700. !EvaluateDecl(Info, SS->getConditionVariable()))
  3701. return ESR_Failed;
  3702. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3703. return ESR_Failed;
  3704. }
  3705. // Find the switch case corresponding to the value of the condition.
  3706. // FIXME: Cache this lookup.
  3707. const SwitchCase *Found = nullptr;
  3708. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3709. SC = SC->getNextSwitchCase()) {
  3710. if (isa<DefaultStmt>(SC)) {
  3711. Found = SC;
  3712. continue;
  3713. }
  3714. const CaseStmt *CS = cast<CaseStmt>(SC);
  3715. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3716. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3717. : LHS;
  3718. if (LHS <= Value && Value <= RHS) {
  3719. Found = SC;
  3720. break;
  3721. }
  3722. }
  3723. if (!Found)
  3724. return ESR_Succeeded;
  3725. // Search the switch body for the switch case and evaluate it from there.
  3726. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3727. case ESR_Break:
  3728. return ESR_Succeeded;
  3729. case ESR_Succeeded:
  3730. case ESR_Continue:
  3731. case ESR_Failed:
  3732. case ESR_Returned:
  3733. return ESR;
  3734. case ESR_CaseNotFound:
  3735. // This can only happen if the switch case is nested within a statement
  3736. // expression. We have no intention of supporting that.
  3737. Info.FFDiag(Found->getBeginLoc(),
  3738. diag::note_constexpr_stmt_expr_unsupported);
  3739. return ESR_Failed;
  3740. }
  3741. llvm_unreachable("Invalid EvalStmtResult!");
  3742. }
  3743. // Evaluate a statement.
  3744. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3745. const Stmt *S, const SwitchCase *Case) {
  3746. if (!Info.nextStep(S))
  3747. return ESR_Failed;
  3748. // If we're hunting down a 'case' or 'default' label, recurse through
  3749. // substatements until we hit the label.
  3750. if (Case) {
  3751. // FIXME: We don't start the lifetime of objects whose initialization we
  3752. // jump over. However, such objects must be of class type with a trivial
  3753. // default constructor that initialize all subobjects, so must be empty,
  3754. // so this almost never matters.
  3755. switch (S->getStmtClass()) {
  3756. case Stmt::CompoundStmtClass:
  3757. // FIXME: Precompute which substatement of a compound statement we
  3758. // would jump to, and go straight there rather than performing a
  3759. // linear scan each time.
  3760. case Stmt::LabelStmtClass:
  3761. case Stmt::AttributedStmtClass:
  3762. case Stmt::DoStmtClass:
  3763. break;
  3764. case Stmt::CaseStmtClass:
  3765. case Stmt::DefaultStmtClass:
  3766. if (Case == S)
  3767. Case = nullptr;
  3768. break;
  3769. case Stmt::IfStmtClass: {
  3770. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3771. // straight there rather than scanning both sides.
  3772. const IfStmt *IS = cast<IfStmt>(S);
  3773. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3774. // preceded by our switch label.
  3775. BlockScopeRAII Scope(Info);
  3776. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3777. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3778. return ESR;
  3779. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3780. }
  3781. case Stmt::WhileStmtClass: {
  3782. EvalStmtResult ESR =
  3783. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3784. if (ESR != ESR_Continue)
  3785. return ESR;
  3786. break;
  3787. }
  3788. case Stmt::ForStmtClass: {
  3789. const ForStmt *FS = cast<ForStmt>(S);
  3790. EvalStmtResult ESR =
  3791. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3792. if (ESR != ESR_Continue)
  3793. return ESR;
  3794. if (FS->getInc()) {
  3795. FullExpressionRAII IncScope(Info);
  3796. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3797. return ESR_Failed;
  3798. }
  3799. break;
  3800. }
  3801. case Stmt::DeclStmtClass:
  3802. // FIXME: If the variable has initialization that can't be jumped over,
  3803. // bail out of any immediately-surrounding compound-statement too.
  3804. default:
  3805. return ESR_CaseNotFound;
  3806. }
  3807. }
  3808. switch (S->getStmtClass()) {
  3809. default:
  3810. if (const Expr *E = dyn_cast<Expr>(S)) {
  3811. // Don't bother evaluating beyond an expression-statement which couldn't
  3812. // be evaluated.
  3813. FullExpressionRAII Scope(Info);
  3814. if (!EvaluateIgnoredValue(Info, E))
  3815. return ESR_Failed;
  3816. return ESR_Succeeded;
  3817. }
  3818. Info.FFDiag(S->getBeginLoc());
  3819. return ESR_Failed;
  3820. case Stmt::NullStmtClass:
  3821. return ESR_Succeeded;
  3822. case Stmt::DeclStmtClass: {
  3823. const DeclStmt *DS = cast<DeclStmt>(S);
  3824. for (const auto *DclIt : DS->decls()) {
  3825. // Each declaration initialization is its own full-expression.
  3826. // FIXME: This isn't quite right; if we're performing aggregate
  3827. // initialization, each braced subexpression is its own full-expression.
  3828. FullExpressionRAII Scope(Info);
  3829. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3830. return ESR_Failed;
  3831. }
  3832. return ESR_Succeeded;
  3833. }
  3834. case Stmt::ReturnStmtClass: {
  3835. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3836. FullExpressionRAII Scope(Info);
  3837. if (RetExpr &&
  3838. !(Result.Slot
  3839. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3840. : Evaluate(Result.Value, Info, RetExpr)))
  3841. return ESR_Failed;
  3842. return ESR_Returned;
  3843. }
  3844. case Stmt::CompoundStmtClass: {
  3845. BlockScopeRAII Scope(Info);
  3846. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3847. for (const auto *BI : CS->body()) {
  3848. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3849. if (ESR == ESR_Succeeded)
  3850. Case = nullptr;
  3851. else if (ESR != ESR_CaseNotFound)
  3852. return ESR;
  3853. }
  3854. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3855. }
  3856. case Stmt::IfStmtClass: {
  3857. const IfStmt *IS = cast<IfStmt>(S);
  3858. // Evaluate the condition, as either a var decl or as an expression.
  3859. BlockScopeRAII Scope(Info);
  3860. if (const Stmt *Init = IS->getInit()) {
  3861. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3862. if (ESR != ESR_Succeeded)
  3863. return ESR;
  3864. }
  3865. bool Cond;
  3866. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3867. return ESR_Failed;
  3868. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3869. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3870. if (ESR != ESR_Succeeded)
  3871. return ESR;
  3872. }
  3873. return ESR_Succeeded;
  3874. }
  3875. case Stmt::WhileStmtClass: {
  3876. const WhileStmt *WS = cast<WhileStmt>(S);
  3877. while (true) {
  3878. BlockScopeRAII Scope(Info);
  3879. bool Continue;
  3880. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3881. Continue))
  3882. return ESR_Failed;
  3883. if (!Continue)
  3884. break;
  3885. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3886. if (ESR != ESR_Continue)
  3887. return ESR;
  3888. }
  3889. return ESR_Succeeded;
  3890. }
  3891. case Stmt::DoStmtClass: {
  3892. const DoStmt *DS = cast<DoStmt>(S);
  3893. bool Continue;
  3894. do {
  3895. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3896. if (ESR != ESR_Continue)
  3897. return ESR;
  3898. Case = nullptr;
  3899. FullExpressionRAII CondScope(Info);
  3900. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3901. return ESR_Failed;
  3902. } while (Continue);
  3903. return ESR_Succeeded;
  3904. }
  3905. case Stmt::ForStmtClass: {
  3906. const ForStmt *FS = cast<ForStmt>(S);
  3907. BlockScopeRAII Scope(Info);
  3908. if (FS->getInit()) {
  3909. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3910. if (ESR != ESR_Succeeded)
  3911. return ESR;
  3912. }
  3913. while (true) {
  3914. BlockScopeRAII Scope(Info);
  3915. bool Continue = true;
  3916. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3917. FS->getCond(), Continue))
  3918. return ESR_Failed;
  3919. if (!Continue)
  3920. break;
  3921. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3922. if (ESR != ESR_Continue)
  3923. return ESR;
  3924. if (FS->getInc()) {
  3925. FullExpressionRAII IncScope(Info);
  3926. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3927. return ESR_Failed;
  3928. }
  3929. }
  3930. return ESR_Succeeded;
  3931. }
  3932. case Stmt::CXXForRangeStmtClass: {
  3933. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3934. BlockScopeRAII Scope(Info);
  3935. // Evaluate the init-statement if present.
  3936. if (FS->getInit()) {
  3937. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3938. if (ESR != ESR_Succeeded)
  3939. return ESR;
  3940. }
  3941. // Initialize the __range variable.
  3942. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3943. if (ESR != ESR_Succeeded)
  3944. return ESR;
  3945. // Create the __begin and __end iterators.
  3946. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3947. if (ESR != ESR_Succeeded)
  3948. return ESR;
  3949. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3950. if (ESR != ESR_Succeeded)
  3951. return ESR;
  3952. while (true) {
  3953. // Condition: __begin != __end.
  3954. {
  3955. bool Continue = true;
  3956. FullExpressionRAII CondExpr(Info);
  3957. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3958. return ESR_Failed;
  3959. if (!Continue)
  3960. break;
  3961. }
  3962. // User's variable declaration, initialized by *__begin.
  3963. BlockScopeRAII InnerScope(Info);
  3964. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3965. if (ESR != ESR_Succeeded)
  3966. return ESR;
  3967. // Loop body.
  3968. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3969. if (ESR != ESR_Continue)
  3970. return ESR;
  3971. // Increment: ++__begin
  3972. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3973. return ESR_Failed;
  3974. }
  3975. return ESR_Succeeded;
  3976. }
  3977. case Stmt::SwitchStmtClass:
  3978. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3979. case Stmt::ContinueStmtClass:
  3980. return ESR_Continue;
  3981. case Stmt::BreakStmtClass:
  3982. return ESR_Break;
  3983. case Stmt::LabelStmtClass:
  3984. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3985. case Stmt::AttributedStmtClass:
  3986. // As a general principle, C++11 attributes can be ignored without
  3987. // any semantic impact.
  3988. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3989. Case);
  3990. case Stmt::CaseStmtClass:
  3991. case Stmt::DefaultStmtClass:
  3992. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3993. case Stmt::CXXTryStmtClass:
  3994. // Evaluate try blocks by evaluating all sub statements.
  3995. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  3996. }
  3997. }
  3998. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3999. /// default constructor. If so, we'll fold it whether or not it's marked as
  4000. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4001. /// so we need special handling.
  4002. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4003. const CXXConstructorDecl *CD,
  4004. bool IsValueInitialization) {
  4005. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4006. return false;
  4007. // Value-initialization does not call a trivial default constructor, so such a
  4008. // call is a core constant expression whether or not the constructor is
  4009. // constexpr.
  4010. if (!CD->isConstexpr() && !IsValueInitialization) {
  4011. if (Info.getLangOpts().CPlusPlus11) {
  4012. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4013. // we should be much more explicit about why it's not constexpr.
  4014. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4015. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4016. Info.Note(CD->getLocation(), diag::note_declared_at);
  4017. } else {
  4018. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4019. }
  4020. }
  4021. return true;
  4022. }
  4023. /// CheckConstexprFunction - Check that a function can be called in a constant
  4024. /// expression.
  4025. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4026. const FunctionDecl *Declaration,
  4027. const FunctionDecl *Definition,
  4028. const Stmt *Body) {
  4029. // Potential constant expressions can contain calls to declared, but not yet
  4030. // defined, constexpr functions.
  4031. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4032. Declaration->isConstexpr())
  4033. return false;
  4034. // Bail out if the function declaration itself is invalid. We will
  4035. // have produced a relevant diagnostic while parsing it, so just
  4036. // note the problematic sub-expression.
  4037. if (Declaration->isInvalidDecl()) {
  4038. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4039. return false;
  4040. }
  4041. // DR1872: An instantiated virtual constexpr function can't be called in a
  4042. // constant expression (prior to C++20). We can still constant-fold such a
  4043. // call.
  4044. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  4045. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4046. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4047. if (Definition && Definition->isInvalidDecl()) {
  4048. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4049. return false;
  4050. }
  4051. // Can we evaluate this function call?
  4052. if (Definition && Definition->isConstexpr() && Body)
  4053. return true;
  4054. if (Info.getLangOpts().CPlusPlus11) {
  4055. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4056. // If this function is not constexpr because it is an inherited
  4057. // non-constexpr constructor, diagnose that directly.
  4058. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4059. if (CD && CD->isInheritingConstructor()) {
  4060. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4061. if (!Inherited->isConstexpr())
  4062. DiagDecl = CD = Inherited;
  4063. }
  4064. // FIXME: If DiagDecl is an implicitly-declared special member function
  4065. // or an inheriting constructor, we should be much more explicit about why
  4066. // it's not constexpr.
  4067. if (CD && CD->isInheritingConstructor())
  4068. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4069. << CD->getInheritedConstructor().getConstructor()->getParent();
  4070. else
  4071. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4072. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4073. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4074. } else {
  4075. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4076. }
  4077. return false;
  4078. }
  4079. namespace {
  4080. struct CheckDynamicTypeHandler {
  4081. AccessKinds AccessKind;
  4082. typedef bool result_type;
  4083. bool failed() { return false; }
  4084. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4085. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4086. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4087. };
  4088. } // end anonymous namespace
  4089. /// Check that we can access the notional vptr of an object / determine its
  4090. /// dynamic type.
  4091. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4092. AccessKinds AK, bool Polymorphic) {
  4093. if (This.Designator.Invalid)
  4094. return false;
  4095. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4096. if (!Obj)
  4097. return false;
  4098. if (!Obj.Value) {
  4099. // The object is not usable in constant expressions, so we can't inspect
  4100. // its value to see if it's in-lifetime or what the active union members
  4101. // are. We can still check for a one-past-the-end lvalue.
  4102. if (This.Designator.isOnePastTheEnd() ||
  4103. This.Designator.isMostDerivedAnUnsizedArray()) {
  4104. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4105. ? diag::note_constexpr_access_past_end
  4106. : diag::note_constexpr_access_unsized_array)
  4107. << AK;
  4108. return false;
  4109. } else if (Polymorphic) {
  4110. // Conservatively refuse to perform a polymorphic operation if we would
  4111. // not be able to read a notional 'vptr' value.
  4112. APValue Val;
  4113. This.moveInto(Val);
  4114. QualType StarThisType =
  4115. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4116. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4117. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4118. return false;
  4119. }
  4120. return true;
  4121. }
  4122. CheckDynamicTypeHandler Handler{AK};
  4123. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4124. }
  4125. /// Check that the pointee of the 'this' pointer in a member function call is
  4126. /// either within its lifetime or in its period of construction or destruction.
  4127. static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4128. const LValue &This) {
  4129. return checkDynamicType(Info, E, This, AK_MemberCall, false);
  4130. }
  4131. struct DynamicType {
  4132. /// The dynamic class type of the object.
  4133. const CXXRecordDecl *Type;
  4134. /// The corresponding path length in the lvalue.
  4135. unsigned PathLength;
  4136. };
  4137. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4138. unsigned PathLength) {
  4139. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4140. Designator.Entries.size() && "invalid path length");
  4141. return (PathLength == Designator.MostDerivedPathLength)
  4142. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4143. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4144. }
  4145. /// Determine the dynamic type of an object.
  4146. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4147. LValue &This, AccessKinds AK) {
  4148. // If we don't have an lvalue denoting an object of class type, there is no
  4149. // meaningful dynamic type. (We consider objects of non-class type to have no
  4150. // dynamic type.)
  4151. if (!checkDynamicType(Info, E, This, AK, true))
  4152. return None;
  4153. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4154. // shouldn't happen other than in constant-folding situations, since literal
  4155. // types can't have virtual bases.
  4156. //
  4157. // Note that consumers of DynamicType assume that the type has no virtual
  4158. // bases, and will need modifications if this restriction is relaxed.
  4159. const CXXRecordDecl *Class =
  4160. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4161. if (!Class || Class->getNumVBases()) {
  4162. Info.FFDiag(E);
  4163. return None;
  4164. }
  4165. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4166. // binary search here instead. But the overwhelmingly common case is that
  4167. // we're not in the middle of a constructor, so it probably doesn't matter
  4168. // in practice.
  4169. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4170. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4171. PathLength <= Path.size(); ++PathLength) {
  4172. switch (Info.isEvaluatingConstructor(This.getLValueBase(),
  4173. Path.slice(0, PathLength))) {
  4174. case ConstructionPhase::Bases:
  4175. // We're constructing a base class. This is not the dynamic type.
  4176. break;
  4177. case ConstructionPhase::None:
  4178. case ConstructionPhase::AfterBases:
  4179. // We've finished constructing the base classes, so this is the dynamic
  4180. // type.
  4181. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4182. PathLength};
  4183. }
  4184. }
  4185. // CWG issue 1517: we're constructing a base class of the object described by
  4186. // 'This', so that object has not yet begun its period of construction and
  4187. // any polymorphic operation on it results in undefined behavior.
  4188. Info.FFDiag(E);
  4189. return None;
  4190. }
  4191. /// Perform virtual dispatch.
  4192. static const CXXMethodDecl *HandleVirtualDispatch(
  4193. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4194. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4195. Optional<DynamicType> DynType =
  4196. ComputeDynamicType(Info, E, This, AK_MemberCall);
  4197. if (!DynType)
  4198. return nullptr;
  4199. // Find the final overrider. It must be declared in one of the classes on the
  4200. // path from the dynamic type to the static type.
  4201. // FIXME: If we ever allow literal types to have virtual base classes, that
  4202. // won't be true.
  4203. const CXXMethodDecl *Callee = Found;
  4204. unsigned PathLength = DynType->PathLength;
  4205. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4206. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4207. const CXXMethodDecl *Overrider =
  4208. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4209. if (Overrider) {
  4210. Callee = Overrider;
  4211. break;
  4212. }
  4213. }
  4214. // C++2a [class.abstract]p6:
  4215. // the effect of making a virtual call to a pure virtual function [...] is
  4216. // undefined
  4217. if (Callee->isPure()) {
  4218. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4219. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4220. return nullptr;
  4221. }
  4222. // If necessary, walk the rest of the path to determine the sequence of
  4223. // covariant adjustment steps to apply.
  4224. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4225. Found->getReturnType())) {
  4226. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4227. for (unsigned CovariantPathLength = PathLength + 1;
  4228. CovariantPathLength != This.Designator.Entries.size();
  4229. ++CovariantPathLength) {
  4230. const CXXRecordDecl *NextClass =
  4231. getBaseClassType(This.Designator, CovariantPathLength);
  4232. const CXXMethodDecl *Next =
  4233. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4234. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4235. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4236. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4237. }
  4238. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4239. CovariantAdjustmentPath.back()))
  4240. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4241. }
  4242. // Perform 'this' adjustment.
  4243. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4244. return nullptr;
  4245. return Callee;
  4246. }
  4247. /// Perform the adjustment from a value returned by a virtual function to
  4248. /// a value of the statically expected type, which may be a pointer or
  4249. /// reference to a base class of the returned type.
  4250. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4251. APValue &Result,
  4252. ArrayRef<QualType> Path) {
  4253. assert(Result.isLValue() &&
  4254. "unexpected kind of APValue for covariant return");
  4255. if (Result.isNullPointer())
  4256. return true;
  4257. LValue LVal;
  4258. LVal.setFrom(Info.Ctx, Result);
  4259. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4260. for (unsigned I = 1; I != Path.size(); ++I) {
  4261. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4262. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4263. if (OldClass != NewClass &&
  4264. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4265. return false;
  4266. OldClass = NewClass;
  4267. }
  4268. LVal.moveInto(Result);
  4269. return true;
  4270. }
  4271. /// Determine whether \p Base, which is known to be a direct base class of
  4272. /// \p Derived, is a public base class.
  4273. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4274. const CXXRecordDecl *Base) {
  4275. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4276. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4277. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4278. return BaseSpec.getAccessSpecifier() == AS_public;
  4279. }
  4280. llvm_unreachable("Base is not a direct base of Derived");
  4281. }
  4282. /// Apply the given dynamic cast operation on the provided lvalue.
  4283. ///
  4284. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4285. /// to find a suitable target subobject.
  4286. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4287. LValue &Ptr) {
  4288. // We can't do anything with a non-symbolic pointer value.
  4289. SubobjectDesignator &D = Ptr.Designator;
  4290. if (D.Invalid)
  4291. return false;
  4292. // C++ [expr.dynamic.cast]p6:
  4293. // If v is a null pointer value, the result is a null pointer value.
  4294. if (Ptr.isNullPointer() && !E->isGLValue())
  4295. return true;
  4296. // For all the other cases, we need the pointer to point to an object within
  4297. // its lifetime / period of construction / destruction, and we need to know
  4298. // its dynamic type.
  4299. Optional<DynamicType> DynType =
  4300. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4301. if (!DynType)
  4302. return false;
  4303. // C++ [expr.dynamic.cast]p7:
  4304. // If T is "pointer to cv void", then the result is a pointer to the most
  4305. // derived object
  4306. if (E->getType()->isVoidPointerType())
  4307. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4308. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4309. assert(C && "dynamic_cast target is not void pointer nor class");
  4310. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4311. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4312. // C++ [expr.dynamic.cast]p9:
  4313. if (!E->isGLValue()) {
  4314. // The value of a failed cast to pointer type is the null pointer value
  4315. // of the required result type.
  4316. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4317. Ptr.setNull(E->getType(), TargetVal);
  4318. return true;
  4319. }
  4320. // A failed cast to reference type throws [...] std::bad_cast.
  4321. unsigned DiagKind;
  4322. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4323. DynType->Type->isDerivedFrom(C)))
  4324. DiagKind = 0;
  4325. else if (!Paths || Paths->begin() == Paths->end())
  4326. DiagKind = 1;
  4327. else if (Paths->isAmbiguous(CQT))
  4328. DiagKind = 2;
  4329. else {
  4330. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4331. DiagKind = 3;
  4332. }
  4333. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4334. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4335. << Info.Ctx.getRecordType(DynType->Type)
  4336. << E->getType().getUnqualifiedType();
  4337. return false;
  4338. };
  4339. // Runtime check, phase 1:
  4340. // Walk from the base subobject towards the derived object looking for the
  4341. // target type.
  4342. for (int PathLength = Ptr.Designator.Entries.size();
  4343. PathLength >= (int)DynType->PathLength; --PathLength) {
  4344. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4345. if (declaresSameEntity(Class, C))
  4346. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4347. // We can only walk across public inheritance edges.
  4348. if (PathLength > (int)DynType->PathLength &&
  4349. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4350. Class))
  4351. return RuntimeCheckFailed(nullptr);
  4352. }
  4353. // Runtime check, phase 2:
  4354. // Search the dynamic type for an unambiguous public base of type C.
  4355. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4356. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4357. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4358. Paths.front().Access == AS_public) {
  4359. // Downcast to the dynamic type...
  4360. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4361. return false;
  4362. // ... then upcast to the chosen base class subobject.
  4363. for (CXXBasePathElement &Elem : Paths.front())
  4364. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4365. return false;
  4366. return true;
  4367. }
  4368. // Otherwise, the runtime check fails.
  4369. return RuntimeCheckFailed(&Paths);
  4370. }
  4371. namespace {
  4372. struct StartLifetimeOfUnionMemberHandler {
  4373. const FieldDecl *Field;
  4374. static const AccessKinds AccessKind = AK_Assign;
  4375. APValue getDefaultInitValue(QualType SubobjType) {
  4376. if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
  4377. if (RD->isUnion())
  4378. return APValue((const FieldDecl*)nullptr);
  4379. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  4380. std::distance(RD->field_begin(), RD->field_end()));
  4381. unsigned Index = 0;
  4382. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  4383. End = RD->bases_end(); I != End; ++I, ++Index)
  4384. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  4385. for (const auto *I : RD->fields()) {
  4386. if (I->isUnnamedBitfield())
  4387. continue;
  4388. Struct.getStructField(I->getFieldIndex()) =
  4389. getDefaultInitValue(I->getType());
  4390. }
  4391. return Struct;
  4392. }
  4393. if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
  4394. SubobjType->getAsArrayTypeUnsafe())) {
  4395. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  4396. if (Array.hasArrayFiller())
  4397. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  4398. return Array;
  4399. }
  4400. return APValue::IndeterminateValue();
  4401. }
  4402. typedef bool result_type;
  4403. bool failed() { return false; }
  4404. bool found(APValue &Subobj, QualType SubobjType) {
  4405. // We are supposed to perform no initialization but begin the lifetime of
  4406. // the object. We interpret that as meaning to do what default
  4407. // initialization of the object would do if all constructors involved were
  4408. // trivial:
  4409. // * All base, non-variant member, and array element subobjects' lifetimes
  4410. // begin
  4411. // * No variant members' lifetimes begin
  4412. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4413. assert(SubobjType->isUnionType());
  4414. if (!declaresSameEntity(Subobj.getUnionField(), Field))
  4415. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4416. return true;
  4417. }
  4418. bool found(APSInt &Value, QualType SubobjType) {
  4419. llvm_unreachable("wrong value kind for union object");
  4420. }
  4421. bool found(APFloat &Value, QualType SubobjType) {
  4422. llvm_unreachable("wrong value kind for union object");
  4423. }
  4424. };
  4425. } // end anonymous namespace
  4426. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4427. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4428. /// operator whose left-hand side might involve a union member access. If it
  4429. /// does, implicitly start the lifetime of any accessed union elements per
  4430. /// C++20 [class.union]5.
  4431. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4432. const LValue &LHS) {
  4433. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4434. return false;
  4435. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4436. // C++ [class.union]p5:
  4437. // define the set S(E) of subexpressions of E as follows:
  4438. unsigned PathLength = LHS.Designator.Entries.size();
  4439. for (const Expr *E = LHSExpr; E != nullptr;) {
  4440. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4441. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4442. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4443. if (!FD)
  4444. break;
  4445. // ... and also contains A.B if B names a union member
  4446. if (FD->getParent()->isUnion())
  4447. UnionPathLengths.push_back({PathLength - 1, FD});
  4448. E = ME->getBase();
  4449. --PathLength;
  4450. assert(declaresSameEntity(FD,
  4451. LHS.Designator.Entries[PathLength]
  4452. .getAsBaseOrMember().getPointer()));
  4453. // -- If E is of the form A[B] and is interpreted as a built-in array
  4454. // subscripting operator, S(E) is [S(the array operand, if any)].
  4455. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4456. // Step over an ArrayToPointerDecay implicit cast.
  4457. auto *Base = ASE->getBase()->IgnoreImplicit();
  4458. if (!Base->getType()->isArrayType())
  4459. break;
  4460. E = Base;
  4461. --PathLength;
  4462. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4463. // Step over a derived-to-base conversion.
  4464. E = ICE->getSubExpr();
  4465. if (ICE->getCastKind() == CK_NoOp)
  4466. continue;
  4467. if (ICE->getCastKind() != CK_DerivedToBase &&
  4468. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4469. break;
  4470. // Walk path backwards as we walk up from the base to the derived class.
  4471. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4472. --PathLength;
  4473. (void)Elt;
  4474. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4475. LHS.Designator.Entries[PathLength]
  4476. .getAsBaseOrMember().getPointer()));
  4477. }
  4478. // -- Otherwise, S(E) is empty.
  4479. } else {
  4480. break;
  4481. }
  4482. }
  4483. // Common case: no unions' lifetimes are started.
  4484. if (UnionPathLengths.empty())
  4485. return true;
  4486. // if modification of X [would access an inactive union member], an object
  4487. // of the type of X is implicitly created
  4488. CompleteObject Obj =
  4489. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4490. if (!Obj)
  4491. return false;
  4492. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4493. llvm::reverse(UnionPathLengths)) {
  4494. // Form a designator for the union object.
  4495. SubobjectDesignator D = LHS.Designator;
  4496. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4497. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4498. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4499. return false;
  4500. }
  4501. return true;
  4502. }
  4503. /// Determine if a class has any fields that might need to be copied by a
  4504. /// trivial copy or move operation.
  4505. static bool hasFields(const CXXRecordDecl *RD) {
  4506. if (!RD || RD->isEmpty())
  4507. return false;
  4508. for (auto *FD : RD->fields()) {
  4509. if (FD->isUnnamedBitfield())
  4510. continue;
  4511. return true;
  4512. }
  4513. for (auto &Base : RD->bases())
  4514. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4515. return true;
  4516. return false;
  4517. }
  4518. namespace {
  4519. typedef SmallVector<APValue, 8> ArgVector;
  4520. }
  4521. /// EvaluateArgs - Evaluate the arguments to a function call.
  4522. static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
  4523. EvalInfo &Info, const FunctionDecl *Callee) {
  4524. bool Success = true;
  4525. llvm::SmallBitVector ForbiddenNullArgs;
  4526. if (Callee->hasAttr<NonNullAttr>()) {
  4527. ForbiddenNullArgs.resize(Args.size());
  4528. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  4529. if (!Attr->args_size()) {
  4530. ForbiddenNullArgs.set();
  4531. break;
  4532. } else
  4533. for (auto Idx : Attr->args()) {
  4534. unsigned ASTIdx = Idx.getASTIndex();
  4535. if (ASTIdx >= Args.size())
  4536. continue;
  4537. ForbiddenNullArgs[ASTIdx] = 1;
  4538. }
  4539. }
  4540. }
  4541. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4542. I != E; ++I) {
  4543. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4544. // If we're checking for a potential constant expression, evaluate all
  4545. // initializers even if some of them fail.
  4546. if (!Info.noteFailure())
  4547. return false;
  4548. Success = false;
  4549. } else if (!ForbiddenNullArgs.empty() &&
  4550. ForbiddenNullArgs[I - Args.begin()] &&
  4551. ArgValues[I - Args.begin()].isNullPointer()) {
  4552. Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
  4553. if (!Info.noteFailure())
  4554. return false;
  4555. Success = false;
  4556. }
  4557. }
  4558. return Success;
  4559. }
  4560. /// Evaluate a function call.
  4561. static bool HandleFunctionCall(SourceLocation CallLoc,
  4562. const FunctionDecl *Callee, const LValue *This,
  4563. ArrayRef<const Expr*> Args, const Stmt *Body,
  4564. EvalInfo &Info, APValue &Result,
  4565. const LValue *ResultSlot) {
  4566. ArgVector ArgValues(Args.size());
  4567. if (!EvaluateArgs(Args, ArgValues, Info, Callee))
  4568. return false;
  4569. if (!Info.CheckCallLimit(CallLoc))
  4570. return false;
  4571. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4572. // For a trivial copy or move assignment, perform an APValue copy. This is
  4573. // essential for unions, where the operations performed by the assignment
  4574. // operator cannot be represented as statements.
  4575. //
  4576. // Skip this for non-union classes with no fields; in that case, the defaulted
  4577. // copy/move does not actually read the object.
  4578. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4579. if (MD && MD->isDefaulted() &&
  4580. (MD->getParent()->isUnion() ||
  4581. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4582. assert(This &&
  4583. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4584. LValue RHS;
  4585. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4586. APValue RHSValue;
  4587. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  4588. RHS, RHSValue))
  4589. return false;
  4590. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4591. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4592. return false;
  4593. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4594. RHSValue))
  4595. return false;
  4596. This->moveInto(Result);
  4597. return true;
  4598. } else if (MD && isLambdaCallOperator(MD)) {
  4599. // We're in a lambda; determine the lambda capture field maps unless we're
  4600. // just constexpr checking a lambda's call operator. constexpr checking is
  4601. // done before the captures have been added to the closure object (unless
  4602. // we're inferring constexpr-ness), so we don't have access to them in this
  4603. // case. But since we don't need the captures to constexpr check, we can
  4604. // just ignore them.
  4605. if (!Info.checkingPotentialConstantExpression())
  4606. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4607. Frame.LambdaThisCaptureField);
  4608. }
  4609. StmtResult Ret = {Result, ResultSlot};
  4610. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4611. if (ESR == ESR_Succeeded) {
  4612. if (Callee->getReturnType()->isVoidType())
  4613. return true;
  4614. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4615. }
  4616. return ESR == ESR_Returned;
  4617. }
  4618. /// Evaluate a constructor call.
  4619. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4620. APValue *ArgValues,
  4621. const CXXConstructorDecl *Definition,
  4622. EvalInfo &Info, APValue &Result) {
  4623. SourceLocation CallLoc = E->getExprLoc();
  4624. if (!Info.CheckCallLimit(CallLoc))
  4625. return false;
  4626. const CXXRecordDecl *RD = Definition->getParent();
  4627. if (RD->getNumVBases()) {
  4628. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4629. return false;
  4630. }
  4631. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4632. Info,
  4633. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4634. RD->getNumBases());
  4635. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4636. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4637. // wasteful.
  4638. APValue RetVal;
  4639. StmtResult Ret = {RetVal, nullptr};
  4640. // If it's a delegating constructor, delegate.
  4641. if (Definition->isDelegatingConstructor()) {
  4642. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4643. {
  4644. FullExpressionRAII InitScope(Info);
  4645. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  4646. return false;
  4647. }
  4648. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4649. }
  4650. // For a trivial copy or move constructor, perform an APValue copy. This is
  4651. // essential for unions (or classes with anonymous union members), where the
  4652. // operations performed by the constructor cannot be represented by
  4653. // ctor-initializers.
  4654. //
  4655. // Skip this for empty non-union classes; we should not perform an
  4656. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4657. // actually read them.
  4658. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4659. (Definition->getParent()->isUnion() ||
  4660. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4661. LValue RHS;
  4662. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4663. return handleLValueToRValueConversion(
  4664. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4665. RHS, Result);
  4666. }
  4667. // Reserve space for the struct members.
  4668. if (!RD->isUnion() && !Result.hasValue())
  4669. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4670. std::distance(RD->field_begin(), RD->field_end()));
  4671. if (RD->isInvalidDecl()) return false;
  4672. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4673. // A scope for temporaries lifetime-extended by reference members.
  4674. BlockScopeRAII LifetimeExtendedScope(Info);
  4675. bool Success = true;
  4676. unsigned BasesSeen = 0;
  4677. #ifndef NDEBUG
  4678. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4679. #endif
  4680. for (const auto *I : Definition->inits()) {
  4681. LValue Subobject = This;
  4682. LValue SubobjectParent = This;
  4683. APValue *Value = &Result;
  4684. // Determine the subobject to initialize.
  4685. FieldDecl *FD = nullptr;
  4686. if (I->isBaseInitializer()) {
  4687. QualType BaseType(I->getBaseClass(), 0);
  4688. #ifndef NDEBUG
  4689. // Non-virtual base classes are initialized in the order in the class
  4690. // definition. We have already checked for virtual base classes.
  4691. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4692. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4693. "base class initializers not in expected order");
  4694. ++BaseIt;
  4695. #endif
  4696. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4697. BaseType->getAsCXXRecordDecl(), &Layout))
  4698. return false;
  4699. Value = &Result.getStructBase(BasesSeen++);
  4700. } else if ((FD = I->getMember())) {
  4701. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4702. return false;
  4703. if (RD->isUnion()) {
  4704. Result = APValue(FD);
  4705. Value = &Result.getUnionValue();
  4706. } else {
  4707. Value = &Result.getStructField(FD->getFieldIndex());
  4708. }
  4709. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4710. // Walk the indirect field decl's chain to find the object to initialize,
  4711. // and make sure we've initialized every step along it.
  4712. auto IndirectFieldChain = IFD->chain();
  4713. for (auto *C : IndirectFieldChain) {
  4714. FD = cast<FieldDecl>(C);
  4715. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4716. // Switch the union field if it differs. This happens if we had
  4717. // preceding zero-initialization, and we're now initializing a union
  4718. // subobject other than the first.
  4719. // FIXME: In this case, the values of the other subobjects are
  4720. // specified, since zero-initialization sets all padding bits to zero.
  4721. if (!Value->hasValue() ||
  4722. (Value->isUnion() && Value->getUnionField() != FD)) {
  4723. if (CD->isUnion())
  4724. *Value = APValue(FD);
  4725. else
  4726. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4727. std::distance(CD->field_begin(), CD->field_end()));
  4728. }
  4729. // Store Subobject as its parent before updating it for the last element
  4730. // in the chain.
  4731. if (C == IndirectFieldChain.back())
  4732. SubobjectParent = Subobject;
  4733. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4734. return false;
  4735. if (CD->isUnion())
  4736. Value = &Value->getUnionValue();
  4737. else
  4738. Value = &Value->getStructField(FD->getFieldIndex());
  4739. }
  4740. } else {
  4741. llvm_unreachable("unknown base initializer kind");
  4742. }
  4743. // Need to override This for implicit field initializers as in this case
  4744. // This refers to innermost anonymous struct/union containing initializer,
  4745. // not to currently constructed class.
  4746. const Expr *Init = I->getInit();
  4747. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4748. isa<CXXDefaultInitExpr>(Init));
  4749. FullExpressionRAII InitScope(Info);
  4750. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4751. (FD && FD->isBitField() &&
  4752. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4753. // If we're checking for a potential constant expression, evaluate all
  4754. // initializers even if some of them fail.
  4755. if (!Info.noteFailure())
  4756. return false;
  4757. Success = false;
  4758. }
  4759. // This is the point at which the dynamic type of the object becomes this
  4760. // class type.
  4761. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  4762. EvalObj.finishedConstructingBases();
  4763. }
  4764. return Success &&
  4765. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4766. }
  4767. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4768. ArrayRef<const Expr*> Args,
  4769. const CXXConstructorDecl *Definition,
  4770. EvalInfo &Info, APValue &Result) {
  4771. ArgVector ArgValues(Args.size());
  4772. if (!EvaluateArgs(Args, ArgValues, Info, Definition))
  4773. return false;
  4774. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4775. Info, Result);
  4776. }
  4777. //===----------------------------------------------------------------------===//
  4778. // Generic Evaluation
  4779. //===----------------------------------------------------------------------===//
  4780. namespace {
  4781. class BitCastBuffer {
  4782. // FIXME: We're going to need bit-level granularity when we support
  4783. // bit-fields.
  4784. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  4785. // we don't support a host or target where that is the case. Still, we should
  4786. // use a more generic type in case we ever do.
  4787. SmallVector<Optional<unsigned char>, 32> Bytes;
  4788. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  4789. "Need at least 8 bit unsigned char");
  4790. bool TargetIsLittleEndian;
  4791. public:
  4792. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  4793. : Bytes(Width.getQuantity()),
  4794. TargetIsLittleEndian(TargetIsLittleEndian) {}
  4795. LLVM_NODISCARD
  4796. bool readObject(CharUnits Offset, CharUnits Width,
  4797. SmallVectorImpl<unsigned char> &Output) const {
  4798. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  4799. // If a byte of an integer is uninitialized, then the whole integer is
  4800. // uninitalized.
  4801. if (!Bytes[I.getQuantity()])
  4802. return false;
  4803. Output.push_back(*Bytes[I.getQuantity()]);
  4804. }
  4805. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  4806. std::reverse(Output.begin(), Output.end());
  4807. return true;
  4808. }
  4809. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  4810. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  4811. std::reverse(Input.begin(), Input.end());
  4812. size_t Index = 0;
  4813. for (unsigned char Byte : Input) {
  4814. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  4815. Bytes[Offset.getQuantity() + Index] = Byte;
  4816. ++Index;
  4817. }
  4818. }
  4819. size_t size() { return Bytes.size(); }
  4820. };
  4821. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  4822. /// target would represent the value at runtime.
  4823. class APValueToBufferConverter {
  4824. EvalInfo &Info;
  4825. BitCastBuffer Buffer;
  4826. const CastExpr *BCE;
  4827. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  4828. const CastExpr *BCE)
  4829. : Info(Info),
  4830. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  4831. BCE(BCE) {}
  4832. bool visit(const APValue &Val, QualType Ty) {
  4833. return visit(Val, Ty, CharUnits::fromQuantity(0));
  4834. }
  4835. // Write out Val with type Ty into Buffer starting at Offset.
  4836. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  4837. assert((size_t)Offset.getQuantity() <= Buffer.size());
  4838. // As a special case, nullptr_t has an indeterminate value.
  4839. if (Ty->isNullPtrType())
  4840. return true;
  4841. // Dig through Src to find the byte at SrcOffset.
  4842. switch (Val.getKind()) {
  4843. case APValue::Indeterminate:
  4844. case APValue::None:
  4845. return true;
  4846. case APValue::Int:
  4847. return visitInt(Val.getInt(), Ty, Offset);
  4848. case APValue::Float:
  4849. return visitFloat(Val.getFloat(), Ty, Offset);
  4850. case APValue::Array:
  4851. return visitArray(Val, Ty, Offset);
  4852. case APValue::Struct:
  4853. return visitRecord(Val, Ty, Offset);
  4854. case APValue::ComplexInt:
  4855. case APValue::ComplexFloat:
  4856. case APValue::Vector:
  4857. case APValue::FixedPoint:
  4858. // FIXME: We should support these.
  4859. case APValue::Union:
  4860. case APValue::MemberPointer:
  4861. case APValue::AddrLabelDiff: {
  4862. Info.FFDiag(BCE->getBeginLoc(),
  4863. diag::note_constexpr_bit_cast_unsupported_type)
  4864. << Ty;
  4865. return false;
  4866. }
  4867. case APValue::LValue:
  4868. llvm_unreachable("LValue subobject in bit_cast?");
  4869. }
  4870. }
  4871. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  4872. const RecordDecl *RD = Ty->getAsRecordDecl();
  4873. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4874. // Visit the base classes.
  4875. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4876. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  4877. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  4878. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  4879. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  4880. Layout.getBaseClassOffset(BaseDecl) + Offset))
  4881. return false;
  4882. }
  4883. }
  4884. // Visit the fields.
  4885. unsigned FieldIdx = 0;
  4886. for (FieldDecl *FD : RD->fields()) {
  4887. if (FD->isBitField()) {
  4888. Info.FFDiag(BCE->getBeginLoc(),
  4889. diag::note_constexpr_bit_cast_unsupported_bitfield);
  4890. return false;
  4891. }
  4892. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  4893. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  4894. "only bit-fields can have sub-char alignment");
  4895. CharUnits FieldOffset =
  4896. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  4897. QualType FieldTy = FD->getType();
  4898. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  4899. return false;
  4900. ++FieldIdx;
  4901. }
  4902. return true;
  4903. }
  4904. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  4905. const auto *CAT =
  4906. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  4907. if (!CAT)
  4908. return false;
  4909. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  4910. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  4911. unsigned ArraySize = Val.getArraySize();
  4912. // First, initialize the initialized elements.
  4913. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  4914. const APValue &SubObj = Val.getArrayInitializedElt(I);
  4915. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  4916. return false;
  4917. }
  4918. // Next, initialize the rest of the array using the filler.
  4919. if (Val.hasArrayFiller()) {
  4920. const APValue &Filler = Val.getArrayFiller();
  4921. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  4922. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  4923. return false;
  4924. }
  4925. }
  4926. return true;
  4927. }
  4928. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  4929. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  4930. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  4931. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  4932. Buffer.writeObject(Offset, Bytes);
  4933. return true;
  4934. }
  4935. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  4936. APSInt AsInt(Val.bitcastToAPInt());
  4937. return visitInt(AsInt, Ty, Offset);
  4938. }
  4939. public:
  4940. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  4941. const CastExpr *BCE) {
  4942. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  4943. APValueToBufferConverter Converter(Info, DstSize, BCE);
  4944. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  4945. return None;
  4946. return Converter.Buffer;
  4947. }
  4948. };
  4949. /// Write an BitCastBuffer into an APValue.
  4950. class BufferToAPValueConverter {
  4951. EvalInfo &Info;
  4952. const BitCastBuffer &Buffer;
  4953. const CastExpr *BCE;
  4954. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  4955. const CastExpr *BCE)
  4956. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  4957. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  4958. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  4959. // Ideally this will be unreachable.
  4960. llvm::NoneType unsupportedType(QualType Ty) {
  4961. Info.FFDiag(BCE->getBeginLoc(),
  4962. diag::note_constexpr_bit_cast_unsupported_type)
  4963. << Ty;
  4964. return None;
  4965. }
  4966. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  4967. const EnumType *EnumSugar = nullptr) {
  4968. if (T->isNullPtrType()) {
  4969. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  4970. return APValue((Expr *)nullptr,
  4971. /*Offset=*/CharUnits::fromQuantity(NullValue),
  4972. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  4973. }
  4974. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  4975. SmallVector<uint8_t, 8> Bytes;
  4976. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  4977. // If this is std::byte or unsigned char, then its okay to store an
  4978. // indeterminate value.
  4979. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  4980. bool IsUChar =
  4981. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  4982. T->isSpecificBuiltinType(BuiltinType::Char_U));
  4983. if (!IsStdByte && !IsUChar) {
  4984. QualType DisplayType(EnumSugar ? (Type *)EnumSugar : T, 0);
  4985. Info.FFDiag(BCE->getExprLoc(),
  4986. diag::note_constexpr_bit_cast_indet_dest)
  4987. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  4988. return None;
  4989. }
  4990. return APValue::IndeterminateValue();
  4991. }
  4992. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  4993. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  4994. if (T->isIntegralOrEnumerationType()) {
  4995. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  4996. return APValue(Val);
  4997. }
  4998. if (T->isRealFloatingType()) {
  4999. const llvm::fltSemantics &Semantics =
  5000. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  5001. return APValue(APFloat(Semantics, Val));
  5002. }
  5003. return unsupportedType(QualType(T, 0));
  5004. }
  5005. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  5006. const RecordDecl *RD = RTy->getAsRecordDecl();
  5007. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5008. unsigned NumBases = 0;
  5009. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5010. NumBases = CXXRD->getNumBases();
  5011. APValue ResultVal(APValue::UninitStruct(), NumBases,
  5012. std::distance(RD->field_begin(), RD->field_end()));
  5013. // Visit the base classes.
  5014. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5015. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5016. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5017. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5018. if (BaseDecl->isEmpty() ||
  5019. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  5020. continue;
  5021. Optional<APValue> SubObj = visitType(
  5022. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  5023. if (!SubObj)
  5024. return None;
  5025. ResultVal.getStructBase(I) = *SubObj;
  5026. }
  5027. }
  5028. // Visit the fields.
  5029. unsigned FieldIdx = 0;
  5030. for (FieldDecl *FD : RD->fields()) {
  5031. // FIXME: We don't currently support bit-fields. A lot of the logic for
  5032. // this is in CodeGen, so we need to factor it around.
  5033. if (FD->isBitField()) {
  5034. Info.FFDiag(BCE->getBeginLoc(),
  5035. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5036. return None;
  5037. }
  5038. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5039. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  5040. CharUnits FieldOffset =
  5041. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  5042. Offset;
  5043. QualType FieldTy = FD->getType();
  5044. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  5045. if (!SubObj)
  5046. return None;
  5047. ResultVal.getStructField(FieldIdx) = *SubObj;
  5048. ++FieldIdx;
  5049. }
  5050. return ResultVal;
  5051. }
  5052. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  5053. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  5054. assert(!RepresentationType.isNull() &&
  5055. "enum forward decl should be caught by Sema");
  5056. const BuiltinType *AsBuiltin =
  5057. RepresentationType.getCanonicalType()->getAs<BuiltinType>();
  5058. assert(AsBuiltin && "non-integral enum underlying type?");
  5059. // Recurse into the underlying type. Treat std::byte transparently as
  5060. // unsigned char.
  5061. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  5062. }
  5063. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  5064. size_t Size = Ty->getSize().getLimitedValue();
  5065. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  5066. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  5067. for (size_t I = 0; I != Size; ++I) {
  5068. Optional<APValue> ElementValue =
  5069. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  5070. if (!ElementValue)
  5071. return None;
  5072. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  5073. }
  5074. return ArrayValue;
  5075. }
  5076. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  5077. return unsupportedType(QualType(Ty, 0));
  5078. }
  5079. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  5080. QualType Can = Ty.getCanonicalType();
  5081. switch (Can->getTypeClass()) {
  5082. #define TYPE(Class, Base) \
  5083. case Type::Class: \
  5084. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  5085. #define ABSTRACT_TYPE(Class, Base)
  5086. #define NON_CANONICAL_TYPE(Class, Base) \
  5087. case Type::Class: \
  5088. llvm_unreachable("non-canonical type should be impossible!");
  5089. #define DEPENDENT_TYPE(Class, Base) \
  5090. case Type::Class: \
  5091. llvm_unreachable( \
  5092. "dependent types aren't supported in the constant evaluator!");
  5093. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  5094. case Type::Class: \
  5095. llvm_unreachable("either dependent or not canonical!");
  5096. #include "clang/AST/TypeNodes.def"
  5097. }
  5098. }
  5099. public:
  5100. // Pull out a full value of type DstType.
  5101. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  5102. const CastExpr *BCE) {
  5103. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  5104. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  5105. }
  5106. };
  5107. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  5108. QualType Ty, EvalInfo *Info,
  5109. const ASTContext &Ctx,
  5110. bool CheckingDest) {
  5111. Ty = Ty.getCanonicalType();
  5112. auto diag = [&](int Reason) {
  5113. if (Info)
  5114. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  5115. << CheckingDest << (Reason == 4) << Reason;
  5116. return false;
  5117. };
  5118. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  5119. if (Info)
  5120. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  5121. << NoteTy << Construct << Ty;
  5122. return false;
  5123. };
  5124. if (Ty->isUnionType())
  5125. return diag(0);
  5126. if (Ty->isPointerType())
  5127. return diag(1);
  5128. if (Ty->isMemberPointerType())
  5129. return diag(2);
  5130. if (Ty.isVolatileQualified())
  5131. return diag(3);
  5132. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  5133. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  5134. for (CXXBaseSpecifier &BS : CXXRD->bases())
  5135. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  5136. CheckingDest))
  5137. return note(1, BS.getType(), BS.getBeginLoc());
  5138. }
  5139. for (FieldDecl *FD : Record->fields()) {
  5140. if (FD->getType()->isReferenceType())
  5141. return diag(4);
  5142. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5143. CheckingDest))
  5144. return note(0, FD->getType(), FD->getBeginLoc());
  5145. }
  5146. }
  5147. if (Ty->isArrayType() &&
  5148. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5149. Info, Ctx, CheckingDest))
  5150. return false;
  5151. return true;
  5152. }
  5153. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5154. const ASTContext &Ctx,
  5155. const CastExpr *BCE) {
  5156. bool DestOK = checkBitCastConstexprEligibilityType(
  5157. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5158. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5159. BCE->getBeginLoc(),
  5160. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5161. return SourceOK;
  5162. }
  5163. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5164. APValue &SourceValue,
  5165. const CastExpr *BCE) {
  5166. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5167. "no host or target supports non 8-bit chars");
  5168. assert(SourceValue.isLValue() &&
  5169. "LValueToRValueBitcast requires an lvalue operand!");
  5170. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5171. return false;
  5172. LValue SourceLValue;
  5173. APValue SourceRValue;
  5174. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5175. if (!handleLValueToRValueConversion(Info, BCE,
  5176. BCE->getSubExpr()->getType().withConst(),
  5177. SourceLValue, SourceRValue))
  5178. return false;
  5179. // Read out SourceValue into a char buffer.
  5180. Optional<BitCastBuffer> Buffer =
  5181. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5182. if (!Buffer)
  5183. return false;
  5184. // Write out the buffer into a new APValue.
  5185. Optional<APValue> MaybeDestValue =
  5186. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5187. if (!MaybeDestValue)
  5188. return false;
  5189. DestValue = std::move(*MaybeDestValue);
  5190. return true;
  5191. }
  5192. template <class Derived>
  5193. class ExprEvaluatorBase
  5194. : public ConstStmtVisitor<Derived, bool> {
  5195. private:
  5196. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5197. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5198. return getDerived().Success(V, E);
  5199. }
  5200. bool DerivedZeroInitialization(const Expr *E) {
  5201. return getDerived().ZeroInitialization(E);
  5202. }
  5203. // Check whether a conditional operator with a non-constant condition is a
  5204. // potential constant expression. If neither arm is a potential constant
  5205. // expression, then the conditional operator is not either.
  5206. template<typename ConditionalOperator>
  5207. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5208. assert(Info.checkingPotentialConstantExpression());
  5209. // Speculatively evaluate both arms.
  5210. SmallVector<PartialDiagnosticAt, 8> Diag;
  5211. {
  5212. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5213. StmtVisitorTy::Visit(E->getFalseExpr());
  5214. if (Diag.empty())
  5215. return;
  5216. }
  5217. {
  5218. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5219. Diag.clear();
  5220. StmtVisitorTy::Visit(E->getTrueExpr());
  5221. if (Diag.empty())
  5222. return;
  5223. }
  5224. Error(E, diag::note_constexpr_conditional_never_const);
  5225. }
  5226. template<typename ConditionalOperator>
  5227. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5228. bool BoolResult;
  5229. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5230. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5231. CheckPotentialConstantConditional(E);
  5232. return false;
  5233. }
  5234. if (Info.noteFailure()) {
  5235. StmtVisitorTy::Visit(E->getTrueExpr());
  5236. StmtVisitorTy::Visit(E->getFalseExpr());
  5237. }
  5238. return false;
  5239. }
  5240. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5241. return StmtVisitorTy::Visit(EvalExpr);
  5242. }
  5243. protected:
  5244. EvalInfo &Info;
  5245. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5246. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5247. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5248. return Info.CCEDiag(E, D);
  5249. }
  5250. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5251. public:
  5252. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5253. EvalInfo &getEvalInfo() { return Info; }
  5254. /// Report an evaluation error. This should only be called when an error is
  5255. /// first discovered. When propagating an error, just return false.
  5256. bool Error(const Expr *E, diag::kind D) {
  5257. Info.FFDiag(E, D);
  5258. return false;
  5259. }
  5260. bool Error(const Expr *E) {
  5261. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5262. }
  5263. bool VisitStmt(const Stmt *) {
  5264. llvm_unreachable("Expression evaluator should not be called on stmts");
  5265. }
  5266. bool VisitExpr(const Expr *E) {
  5267. return Error(E);
  5268. }
  5269. bool VisitConstantExpr(const ConstantExpr *E)
  5270. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5271. bool VisitParenExpr(const ParenExpr *E)
  5272. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5273. bool VisitUnaryExtension(const UnaryOperator *E)
  5274. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5275. bool VisitUnaryPlus(const UnaryOperator *E)
  5276. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5277. bool VisitChooseExpr(const ChooseExpr *E)
  5278. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5279. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5280. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5281. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5282. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5283. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5284. TempVersionRAII RAII(*Info.CurrentCall);
  5285. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5286. return StmtVisitorTy::Visit(E->getExpr());
  5287. }
  5288. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5289. TempVersionRAII RAII(*Info.CurrentCall);
  5290. // The initializer may not have been parsed yet, or might be erroneous.
  5291. if (!E->getExpr())
  5292. return Error(E);
  5293. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5294. return StmtVisitorTy::Visit(E->getExpr());
  5295. }
  5296. // We cannot create any objects for which cleanups are required, so there is
  5297. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  5298. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  5299. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5300. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5301. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5302. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5303. }
  5304. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5305. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5306. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5307. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5308. }
  5309. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5310. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5311. }
  5312. bool VisitBinaryOperator(const BinaryOperator *E) {
  5313. switch (E->getOpcode()) {
  5314. default:
  5315. return Error(E);
  5316. case BO_Comma:
  5317. VisitIgnoredValue(E->getLHS());
  5318. return StmtVisitorTy::Visit(E->getRHS());
  5319. case BO_PtrMemD:
  5320. case BO_PtrMemI: {
  5321. LValue Obj;
  5322. if (!HandleMemberPointerAccess(Info, E, Obj))
  5323. return false;
  5324. APValue Result;
  5325. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5326. return false;
  5327. return DerivedSuccess(Result, E);
  5328. }
  5329. }
  5330. }
  5331. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5332. // Evaluate and cache the common expression. We treat it as a temporary,
  5333. // even though it's not quite the same thing.
  5334. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  5335. Info, E->getCommon()))
  5336. return false;
  5337. return HandleConditionalOperator(E);
  5338. }
  5339. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5340. bool IsBcpCall = false;
  5341. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5342. // the result is a constant expression if it can be folded without
  5343. // side-effects. This is an important GNU extension. See GCC PR38377
  5344. // for discussion.
  5345. if (const CallExpr *CallCE =
  5346. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  5347. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  5348. IsBcpCall = true;
  5349. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  5350. // constant expression; we can't check whether it's potentially foldable.
  5351. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  5352. return false;
  5353. FoldConstant Fold(Info, IsBcpCall);
  5354. if (!HandleConditionalOperator(E)) {
  5355. Fold.keepDiagnostics();
  5356. return false;
  5357. }
  5358. return true;
  5359. }
  5360. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  5361. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  5362. return DerivedSuccess(*Value, E);
  5363. const Expr *Source = E->getSourceExpr();
  5364. if (!Source)
  5365. return Error(E);
  5366. if (Source == E) { // sanity checking.
  5367. assert(0 && "OpaqueValueExpr recursively refers to itself");
  5368. return Error(E);
  5369. }
  5370. return StmtVisitorTy::Visit(Source);
  5371. }
  5372. bool VisitCallExpr(const CallExpr *E) {
  5373. APValue Result;
  5374. if (!handleCallExpr(E, Result, nullptr))
  5375. return false;
  5376. return DerivedSuccess(Result, E);
  5377. }
  5378. bool handleCallExpr(const CallExpr *E, APValue &Result,
  5379. const LValue *ResultSlot) {
  5380. const Expr *Callee = E->getCallee()->IgnoreParens();
  5381. QualType CalleeType = Callee->getType();
  5382. const FunctionDecl *FD = nullptr;
  5383. LValue *This = nullptr, ThisVal;
  5384. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5385. bool HasQualifier = false;
  5386. // Extract function decl and 'this' pointer from the callee.
  5387. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  5388. const CXXMethodDecl *Member = nullptr;
  5389. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  5390. // Explicit bound member calls, such as x.f() or p->g();
  5391. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  5392. return false;
  5393. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  5394. if (!Member)
  5395. return Error(Callee);
  5396. This = &ThisVal;
  5397. HasQualifier = ME->hasQualifier();
  5398. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  5399. // Indirect bound member calls ('.*' or '->*').
  5400. Member = dyn_cast_or_null<CXXMethodDecl>(
  5401. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  5402. if (!Member)
  5403. return Error(Callee);
  5404. This = &ThisVal;
  5405. } else
  5406. return Error(Callee);
  5407. FD = Member;
  5408. } else if (CalleeType->isFunctionPointerType()) {
  5409. LValue Call;
  5410. if (!EvaluatePointer(Callee, Call, Info))
  5411. return false;
  5412. if (!Call.getLValueOffset().isZero())
  5413. return Error(Callee);
  5414. FD = dyn_cast_or_null<FunctionDecl>(
  5415. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  5416. if (!FD)
  5417. return Error(Callee);
  5418. // Don't call function pointers which have been cast to some other type.
  5419. // Per DR (no number yet), the caller and callee can differ in noexcept.
  5420. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  5421. CalleeType->getPointeeType(), FD->getType())) {
  5422. return Error(E);
  5423. }
  5424. // Overloaded operator calls to member functions are represented as normal
  5425. // calls with '*this' as the first argument.
  5426. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5427. if (MD && !MD->isStatic()) {
  5428. // FIXME: When selecting an implicit conversion for an overloaded
  5429. // operator delete, we sometimes try to evaluate calls to conversion
  5430. // operators without a 'this' parameter!
  5431. if (Args.empty())
  5432. return Error(E);
  5433. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  5434. return false;
  5435. This = &ThisVal;
  5436. Args = Args.slice(1);
  5437. } else if (MD && MD->isLambdaStaticInvoker()) {
  5438. // Map the static invoker for the lambda back to the call operator.
  5439. // Conveniently, we don't have to slice out the 'this' argument (as is
  5440. // being done for the non-static case), since a static member function
  5441. // doesn't have an implicit argument passed in.
  5442. const CXXRecordDecl *ClosureClass = MD->getParent();
  5443. assert(
  5444. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  5445. "Number of captures must be zero for conversion to function-ptr");
  5446. const CXXMethodDecl *LambdaCallOp =
  5447. ClosureClass->getLambdaCallOperator();
  5448. // Set 'FD', the function that will be called below, to the call
  5449. // operator. If the closure object represents a generic lambda, find
  5450. // the corresponding specialization of the call operator.
  5451. if (ClosureClass->isGenericLambda()) {
  5452. assert(MD->isFunctionTemplateSpecialization() &&
  5453. "A generic lambda's static-invoker function must be a "
  5454. "template specialization");
  5455. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  5456. FunctionTemplateDecl *CallOpTemplate =
  5457. LambdaCallOp->getDescribedFunctionTemplate();
  5458. void *InsertPos = nullptr;
  5459. FunctionDecl *CorrespondingCallOpSpecialization =
  5460. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  5461. assert(CorrespondingCallOpSpecialization &&
  5462. "We must always have a function call operator specialization "
  5463. "that corresponds to our static invoker specialization");
  5464. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  5465. } else
  5466. FD = LambdaCallOp;
  5467. }
  5468. } else
  5469. return Error(E);
  5470. SmallVector<QualType, 4> CovariantAdjustmentPath;
  5471. if (This) {
  5472. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  5473. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  5474. // Perform virtual dispatch, if necessary.
  5475. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  5476. CovariantAdjustmentPath);
  5477. if (!FD)
  5478. return false;
  5479. } else {
  5480. // Check that the 'this' pointer points to an object of the right type.
  5481. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
  5482. return false;
  5483. }
  5484. }
  5485. const FunctionDecl *Definition = nullptr;
  5486. Stmt *Body = FD->getBody(Definition);
  5487. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  5488. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  5489. Result, ResultSlot))
  5490. return false;
  5491. if (!CovariantAdjustmentPath.empty() &&
  5492. !HandleCovariantReturnAdjustment(Info, E, Result,
  5493. CovariantAdjustmentPath))
  5494. return false;
  5495. return true;
  5496. }
  5497. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5498. return StmtVisitorTy::Visit(E->getInitializer());
  5499. }
  5500. bool VisitInitListExpr(const InitListExpr *E) {
  5501. if (E->getNumInits() == 0)
  5502. return DerivedZeroInitialization(E);
  5503. if (E->getNumInits() == 1)
  5504. return StmtVisitorTy::Visit(E->getInit(0));
  5505. return Error(E);
  5506. }
  5507. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  5508. return DerivedZeroInitialization(E);
  5509. }
  5510. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  5511. return DerivedZeroInitialization(E);
  5512. }
  5513. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  5514. return DerivedZeroInitialization(E);
  5515. }
  5516. /// A member expression where the object is a prvalue is itself a prvalue.
  5517. bool VisitMemberExpr(const MemberExpr *E) {
  5518. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  5519. "missing temporary materialization conversion");
  5520. assert(!E->isArrow() && "missing call to bound member function?");
  5521. APValue Val;
  5522. if (!Evaluate(Val, Info, E->getBase()))
  5523. return false;
  5524. QualType BaseTy = E->getBase()->getType();
  5525. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  5526. if (!FD) return Error(E);
  5527. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  5528. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5529. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5530. // Note: there is no lvalue base here. But this case should only ever
  5531. // happen in C or in C++98, where we cannot be evaluating a constexpr
  5532. // constructor, which is the only case the base matters.
  5533. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  5534. SubobjectDesignator Designator(BaseTy);
  5535. Designator.addDeclUnchecked(FD);
  5536. APValue Result;
  5537. return extractSubobject(Info, E, Obj, Designator, Result) &&
  5538. DerivedSuccess(Result, E);
  5539. }
  5540. bool VisitCastExpr(const CastExpr *E) {
  5541. switch (E->getCastKind()) {
  5542. default:
  5543. break;
  5544. case CK_AtomicToNonAtomic: {
  5545. APValue AtomicVal;
  5546. // This does not need to be done in place even for class/array types:
  5547. // atomic-to-non-atomic conversion implies copying the object
  5548. // representation.
  5549. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  5550. return false;
  5551. return DerivedSuccess(AtomicVal, E);
  5552. }
  5553. case CK_NoOp:
  5554. case CK_UserDefinedConversion:
  5555. return StmtVisitorTy::Visit(E->getSubExpr());
  5556. case CK_LValueToRValue: {
  5557. LValue LVal;
  5558. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  5559. return false;
  5560. APValue RVal;
  5561. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5562. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5563. LVal, RVal))
  5564. return false;
  5565. return DerivedSuccess(RVal, E);
  5566. }
  5567. case CK_LValueToRValueBitCast: {
  5568. APValue DestValue, SourceValue;
  5569. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  5570. return false;
  5571. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  5572. return false;
  5573. return DerivedSuccess(DestValue, E);
  5574. }
  5575. }
  5576. return Error(E);
  5577. }
  5578. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  5579. return VisitUnaryPostIncDec(UO);
  5580. }
  5581. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  5582. return VisitUnaryPostIncDec(UO);
  5583. }
  5584. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  5585. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5586. return Error(UO);
  5587. LValue LVal;
  5588. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  5589. return false;
  5590. APValue RVal;
  5591. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  5592. UO->isIncrementOp(), &RVal))
  5593. return false;
  5594. return DerivedSuccess(RVal, UO);
  5595. }
  5596. bool VisitStmtExpr(const StmtExpr *E) {
  5597. // We will have checked the full-expressions inside the statement expression
  5598. // when they were completed, and don't need to check them again now.
  5599. if (Info.checkingForOverflow())
  5600. return Error(E);
  5601. BlockScopeRAII Scope(Info);
  5602. const CompoundStmt *CS = E->getSubStmt();
  5603. if (CS->body_empty())
  5604. return true;
  5605. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  5606. BE = CS->body_end();
  5607. /**/; ++BI) {
  5608. if (BI + 1 == BE) {
  5609. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  5610. if (!FinalExpr) {
  5611. Info.FFDiag((*BI)->getBeginLoc(),
  5612. diag::note_constexpr_stmt_expr_unsupported);
  5613. return false;
  5614. }
  5615. return this->Visit(FinalExpr);
  5616. }
  5617. APValue ReturnValue;
  5618. StmtResult Result = { ReturnValue, nullptr };
  5619. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  5620. if (ESR != ESR_Succeeded) {
  5621. // FIXME: If the statement-expression terminated due to 'return',
  5622. // 'break', or 'continue', it would be nice to propagate that to
  5623. // the outer statement evaluation rather than bailing out.
  5624. if (ESR != ESR_Failed)
  5625. Info.FFDiag((*BI)->getBeginLoc(),
  5626. diag::note_constexpr_stmt_expr_unsupported);
  5627. return false;
  5628. }
  5629. }
  5630. llvm_unreachable("Return from function from the loop above.");
  5631. }
  5632. /// Visit a value which is evaluated, but whose value is ignored.
  5633. void VisitIgnoredValue(const Expr *E) {
  5634. EvaluateIgnoredValue(Info, E);
  5635. }
  5636. /// Potentially visit a MemberExpr's base expression.
  5637. void VisitIgnoredBaseExpression(const Expr *E) {
  5638. // While MSVC doesn't evaluate the base expression, it does diagnose the
  5639. // presence of side-effecting behavior.
  5640. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  5641. return;
  5642. VisitIgnoredValue(E);
  5643. }
  5644. };
  5645. } // namespace
  5646. //===----------------------------------------------------------------------===//
  5647. // Common base class for lvalue and temporary evaluation.
  5648. //===----------------------------------------------------------------------===//
  5649. namespace {
  5650. template<class Derived>
  5651. class LValueExprEvaluatorBase
  5652. : public ExprEvaluatorBase<Derived> {
  5653. protected:
  5654. LValue &Result;
  5655. bool InvalidBaseOK;
  5656. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  5657. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  5658. bool Success(APValue::LValueBase B) {
  5659. Result.set(B);
  5660. return true;
  5661. }
  5662. bool evaluatePointer(const Expr *E, LValue &Result) {
  5663. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  5664. }
  5665. public:
  5666. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  5667. : ExprEvaluatorBaseTy(Info), Result(Result),
  5668. InvalidBaseOK(InvalidBaseOK) {}
  5669. bool Success(const APValue &V, const Expr *E) {
  5670. Result.setFrom(this->Info.Ctx, V);
  5671. return true;
  5672. }
  5673. bool VisitMemberExpr(const MemberExpr *E) {
  5674. // Handle non-static data members.
  5675. QualType BaseTy;
  5676. bool EvalOK;
  5677. if (E->isArrow()) {
  5678. EvalOK = evaluatePointer(E->getBase(), Result);
  5679. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  5680. } else if (E->getBase()->isRValue()) {
  5681. assert(E->getBase()->getType()->isRecordType());
  5682. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  5683. BaseTy = E->getBase()->getType();
  5684. } else {
  5685. EvalOK = this->Visit(E->getBase());
  5686. BaseTy = E->getBase()->getType();
  5687. }
  5688. if (!EvalOK) {
  5689. if (!InvalidBaseOK)
  5690. return false;
  5691. Result.setInvalid(E);
  5692. return true;
  5693. }
  5694. const ValueDecl *MD = E->getMemberDecl();
  5695. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  5696. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5697. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5698. (void)BaseTy;
  5699. if (!HandleLValueMember(this->Info, E, Result, FD))
  5700. return false;
  5701. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  5702. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  5703. return false;
  5704. } else
  5705. return this->Error(E);
  5706. if (MD->getType()->isReferenceType()) {
  5707. APValue RefValue;
  5708. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  5709. RefValue))
  5710. return false;
  5711. return Success(RefValue, E);
  5712. }
  5713. return true;
  5714. }
  5715. bool VisitBinaryOperator(const BinaryOperator *E) {
  5716. switch (E->getOpcode()) {
  5717. default:
  5718. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5719. case BO_PtrMemD:
  5720. case BO_PtrMemI:
  5721. return HandleMemberPointerAccess(this->Info, E, Result);
  5722. }
  5723. }
  5724. bool VisitCastExpr(const CastExpr *E) {
  5725. switch (E->getCastKind()) {
  5726. default:
  5727. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5728. case CK_DerivedToBase:
  5729. case CK_UncheckedDerivedToBase:
  5730. if (!this->Visit(E->getSubExpr()))
  5731. return false;
  5732. // Now figure out the necessary offset to add to the base LV to get from
  5733. // the derived class to the base class.
  5734. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  5735. Result);
  5736. }
  5737. }
  5738. };
  5739. }
  5740. //===----------------------------------------------------------------------===//
  5741. // LValue Evaluation
  5742. //
  5743. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  5744. // function designators (in C), decl references to void objects (in C), and
  5745. // temporaries (if building with -Wno-address-of-temporary).
  5746. //
  5747. // LValue evaluation produces values comprising a base expression of one of the
  5748. // following types:
  5749. // - Declarations
  5750. // * VarDecl
  5751. // * FunctionDecl
  5752. // - Literals
  5753. // * CompoundLiteralExpr in C (and in global scope in C++)
  5754. // * StringLiteral
  5755. // * PredefinedExpr
  5756. // * ObjCStringLiteralExpr
  5757. // * ObjCEncodeExpr
  5758. // * AddrLabelExpr
  5759. // * BlockExpr
  5760. // * CallExpr for a MakeStringConstant builtin
  5761. // - typeid(T) expressions, as TypeInfoLValues
  5762. // - Locals and temporaries
  5763. // * MaterializeTemporaryExpr
  5764. // * Any Expr, with a CallIndex indicating the function in which the temporary
  5765. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  5766. // from the AST (FIXME).
  5767. // * A MaterializeTemporaryExpr that has static storage duration, with no
  5768. // CallIndex, for a lifetime-extended temporary.
  5769. // plus an offset in bytes.
  5770. //===----------------------------------------------------------------------===//
  5771. namespace {
  5772. class LValueExprEvaluator
  5773. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  5774. public:
  5775. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  5776. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  5777. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  5778. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  5779. bool VisitDeclRefExpr(const DeclRefExpr *E);
  5780. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  5781. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  5782. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  5783. bool VisitMemberExpr(const MemberExpr *E);
  5784. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  5785. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  5786. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  5787. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  5788. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  5789. bool VisitUnaryDeref(const UnaryOperator *E);
  5790. bool VisitUnaryReal(const UnaryOperator *E);
  5791. bool VisitUnaryImag(const UnaryOperator *E);
  5792. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  5793. return VisitUnaryPreIncDec(UO);
  5794. }
  5795. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  5796. return VisitUnaryPreIncDec(UO);
  5797. }
  5798. bool VisitBinAssign(const BinaryOperator *BO);
  5799. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  5800. bool VisitCastExpr(const CastExpr *E) {
  5801. switch (E->getCastKind()) {
  5802. default:
  5803. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  5804. case CK_LValueBitCast:
  5805. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5806. if (!Visit(E->getSubExpr()))
  5807. return false;
  5808. Result.Designator.setInvalid();
  5809. return true;
  5810. case CK_BaseToDerived:
  5811. if (!Visit(E->getSubExpr()))
  5812. return false;
  5813. return HandleBaseToDerivedCast(Info, E, Result);
  5814. case CK_Dynamic:
  5815. if (!Visit(E->getSubExpr()))
  5816. return false;
  5817. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  5818. }
  5819. }
  5820. };
  5821. } // end anonymous namespace
  5822. /// Evaluate an expression as an lvalue. This can be legitimately called on
  5823. /// expressions which are not glvalues, in three cases:
  5824. /// * function designators in C, and
  5825. /// * "extern void" objects
  5826. /// * @selector() expressions in Objective-C
  5827. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  5828. bool InvalidBaseOK) {
  5829. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  5830. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  5831. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5832. }
  5833. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  5834. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  5835. return Success(FD);
  5836. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  5837. return VisitVarDecl(E, VD);
  5838. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  5839. return Visit(BD->getBinding());
  5840. return Error(E);
  5841. }
  5842. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  5843. // If we are within a lambda's call operator, check whether the 'VD' referred
  5844. // to within 'E' actually represents a lambda-capture that maps to a
  5845. // data-member/field within the closure object, and if so, evaluate to the
  5846. // field or what the field refers to.
  5847. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  5848. isa<DeclRefExpr>(E) &&
  5849. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  5850. // We don't always have a complete capture-map when checking or inferring if
  5851. // the function call operator meets the requirements of a constexpr function
  5852. // - but we don't need to evaluate the captures to determine constexprness
  5853. // (dcl.constexpr C++17).
  5854. if (Info.checkingPotentialConstantExpression())
  5855. return false;
  5856. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  5857. // Start with 'Result' referring to the complete closure object...
  5858. Result = *Info.CurrentCall->This;
  5859. // ... then update it to refer to the field of the closure object
  5860. // that represents the capture.
  5861. if (!HandleLValueMember(Info, E, Result, FD))
  5862. return false;
  5863. // And if the field is of reference type, update 'Result' to refer to what
  5864. // the field refers to.
  5865. if (FD->getType()->isReferenceType()) {
  5866. APValue RVal;
  5867. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  5868. RVal))
  5869. return false;
  5870. Result.setFrom(Info.Ctx, RVal);
  5871. }
  5872. return true;
  5873. }
  5874. }
  5875. CallStackFrame *Frame = nullptr;
  5876. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  5877. // Only if a local variable was declared in the function currently being
  5878. // evaluated, do we expect to be able to find its value in the current
  5879. // frame. (Otherwise it was likely declared in an enclosing context and
  5880. // could either have a valid evaluatable value (for e.g. a constexpr
  5881. // variable) or be ill-formed (and trigger an appropriate evaluation
  5882. // diagnostic)).
  5883. if (Info.CurrentCall->Callee &&
  5884. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  5885. Frame = Info.CurrentCall;
  5886. }
  5887. }
  5888. if (!VD->getType()->isReferenceType()) {
  5889. if (Frame) {
  5890. Result.set({VD, Frame->Index,
  5891. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  5892. return true;
  5893. }
  5894. return Success(VD);
  5895. }
  5896. APValue *V;
  5897. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  5898. return false;
  5899. if (!V->hasValue()) {
  5900. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  5901. // adjust the diagnostic to say that.
  5902. if (!Info.checkingPotentialConstantExpression())
  5903. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  5904. return false;
  5905. }
  5906. return Success(*V, E);
  5907. }
  5908. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  5909. const MaterializeTemporaryExpr *E) {
  5910. // Walk through the expression to find the materialized temporary itself.
  5911. SmallVector<const Expr *, 2> CommaLHSs;
  5912. SmallVector<SubobjectAdjustment, 2> Adjustments;
  5913. const Expr *Inner = E->GetTemporaryExpr()->
  5914. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  5915. // If we passed any comma operators, evaluate their LHSs.
  5916. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  5917. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  5918. return false;
  5919. // A materialized temporary with static storage duration can appear within the
  5920. // result of a constant expression evaluation, so we need to preserve its
  5921. // value for use outside this evaluation.
  5922. APValue *Value;
  5923. if (E->getStorageDuration() == SD_Static) {
  5924. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  5925. *Value = APValue();
  5926. Result.set(E);
  5927. } else {
  5928. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  5929. *Info.CurrentCall);
  5930. }
  5931. QualType Type = Inner->getType();
  5932. // Materialize the temporary itself.
  5933. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  5934. (E->getStorageDuration() == SD_Static &&
  5935. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  5936. *Value = APValue();
  5937. return false;
  5938. }
  5939. // Adjust our lvalue to refer to the desired subobject.
  5940. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  5941. --I;
  5942. switch (Adjustments[I].Kind) {
  5943. case SubobjectAdjustment::DerivedToBaseAdjustment:
  5944. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  5945. Type, Result))
  5946. return false;
  5947. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  5948. break;
  5949. case SubobjectAdjustment::FieldAdjustment:
  5950. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  5951. return false;
  5952. Type = Adjustments[I].Field->getType();
  5953. break;
  5954. case SubobjectAdjustment::MemberPointerAdjustment:
  5955. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  5956. Adjustments[I].Ptr.RHS))
  5957. return false;
  5958. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  5959. break;
  5960. }
  5961. }
  5962. return true;
  5963. }
  5964. bool
  5965. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5966. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  5967. "lvalue compound literal in c++?");
  5968. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  5969. // only see this when folding in C, so there's no standard to follow here.
  5970. return Success(E);
  5971. }
  5972. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  5973. TypeInfoLValue TypeInfo;
  5974. if (!E->isPotentiallyEvaluated()) {
  5975. if (E->isTypeOperand())
  5976. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  5977. else
  5978. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  5979. } else {
  5980. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  5981. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  5982. << E->getExprOperand()->getType()
  5983. << E->getExprOperand()->getSourceRange();
  5984. }
  5985. if (!Visit(E->getExprOperand()))
  5986. return false;
  5987. Optional<DynamicType> DynType =
  5988. ComputeDynamicType(Info, E, Result, AK_TypeId);
  5989. if (!DynType)
  5990. return false;
  5991. TypeInfo =
  5992. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  5993. }
  5994. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  5995. }
  5996. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  5997. return Success(E);
  5998. }
  5999. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  6000. // Handle static data members.
  6001. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  6002. VisitIgnoredBaseExpression(E->getBase());
  6003. return VisitVarDecl(E, VD);
  6004. }
  6005. // Handle static member functions.
  6006. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  6007. if (MD->isStatic()) {
  6008. VisitIgnoredBaseExpression(E->getBase());
  6009. return Success(MD);
  6010. }
  6011. }
  6012. // Handle non-static data members.
  6013. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  6014. }
  6015. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  6016. // FIXME: Deal with vectors as array subscript bases.
  6017. if (E->getBase()->getType()->isVectorType())
  6018. return Error(E);
  6019. bool Success = true;
  6020. if (!evaluatePointer(E->getBase(), Result)) {
  6021. if (!Info.noteFailure())
  6022. return false;
  6023. Success = false;
  6024. }
  6025. APSInt Index;
  6026. if (!EvaluateInteger(E->getIdx(), Index, Info))
  6027. return false;
  6028. return Success &&
  6029. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  6030. }
  6031. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  6032. return evaluatePointer(E->getSubExpr(), Result);
  6033. }
  6034. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6035. if (!Visit(E->getSubExpr()))
  6036. return false;
  6037. // __real is a no-op on scalar lvalues.
  6038. if (E->getSubExpr()->getType()->isAnyComplexType())
  6039. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  6040. return true;
  6041. }
  6042. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6043. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  6044. "lvalue __imag__ on scalar?");
  6045. if (!Visit(E->getSubExpr()))
  6046. return false;
  6047. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  6048. return true;
  6049. }
  6050. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  6051. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6052. return Error(UO);
  6053. if (!this->Visit(UO->getSubExpr()))
  6054. return false;
  6055. return handleIncDec(
  6056. this->Info, UO, Result, UO->getSubExpr()->getType(),
  6057. UO->isIncrementOp(), nullptr);
  6058. }
  6059. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  6060. const CompoundAssignOperator *CAO) {
  6061. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6062. return Error(CAO);
  6063. APValue RHS;
  6064. // The overall lvalue result is the result of evaluating the LHS.
  6065. if (!this->Visit(CAO->getLHS())) {
  6066. if (Info.noteFailure())
  6067. Evaluate(RHS, this->Info, CAO->getRHS());
  6068. return false;
  6069. }
  6070. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  6071. return false;
  6072. return handleCompoundAssignment(
  6073. this->Info, CAO,
  6074. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  6075. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  6076. }
  6077. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  6078. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6079. return Error(E);
  6080. APValue NewVal;
  6081. if (!this->Visit(E->getLHS())) {
  6082. if (Info.noteFailure())
  6083. Evaluate(NewVal, this->Info, E->getRHS());
  6084. return false;
  6085. }
  6086. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  6087. return false;
  6088. if (Info.getLangOpts().CPlusPlus2a &&
  6089. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  6090. return false;
  6091. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  6092. NewVal);
  6093. }
  6094. //===----------------------------------------------------------------------===//
  6095. // Pointer Evaluation
  6096. //===----------------------------------------------------------------------===//
  6097. /// Attempts to compute the number of bytes available at the pointer
  6098. /// returned by a function with the alloc_size attribute. Returns true if we
  6099. /// were successful. Places an unsigned number into `Result`.
  6100. ///
  6101. /// This expects the given CallExpr to be a call to a function with an
  6102. /// alloc_size attribute.
  6103. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6104. const CallExpr *Call,
  6105. llvm::APInt &Result) {
  6106. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  6107. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  6108. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  6109. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  6110. if (Call->getNumArgs() <= SizeArgNo)
  6111. return false;
  6112. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  6113. Expr::EvalResult ExprResult;
  6114. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  6115. return false;
  6116. Into = ExprResult.Val.getInt();
  6117. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  6118. return false;
  6119. Into = Into.zextOrSelf(BitsInSizeT);
  6120. return true;
  6121. };
  6122. APSInt SizeOfElem;
  6123. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  6124. return false;
  6125. if (!AllocSize->getNumElemsParam().isValid()) {
  6126. Result = std::move(SizeOfElem);
  6127. return true;
  6128. }
  6129. APSInt NumberOfElems;
  6130. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  6131. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  6132. return false;
  6133. bool Overflow;
  6134. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  6135. if (Overflow)
  6136. return false;
  6137. Result = std::move(BytesAvailable);
  6138. return true;
  6139. }
  6140. /// Convenience function. LVal's base must be a call to an alloc_size
  6141. /// function.
  6142. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6143. const LValue &LVal,
  6144. llvm::APInt &Result) {
  6145. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6146. "Can't get the size of a non alloc_size function");
  6147. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6148. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6149. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6150. }
  6151. /// Attempts to evaluate the given LValueBase as the result of a call to
  6152. /// a function with the alloc_size attribute. If it was possible to do so, this
  6153. /// function will return true, make Result's Base point to said function call,
  6154. /// and mark Result's Base as invalid.
  6155. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6156. LValue &Result) {
  6157. if (Base.isNull())
  6158. return false;
  6159. // Because we do no form of static analysis, we only support const variables.
  6160. //
  6161. // Additionally, we can't support parameters, nor can we support static
  6162. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6163. // we have no clue what they'll be assigned to).
  6164. const auto *VD =
  6165. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6166. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6167. return false;
  6168. const Expr *Init = VD->getAnyInitializer();
  6169. if (!Init)
  6170. return false;
  6171. const Expr *E = Init->IgnoreParens();
  6172. if (!tryUnwrapAllocSizeCall(E))
  6173. return false;
  6174. // Store E instead of E unwrapped so that the type of the LValue's base is
  6175. // what the user wanted.
  6176. Result.setInvalid(E);
  6177. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6178. Result.addUnsizedArray(Info, E, Pointee);
  6179. return true;
  6180. }
  6181. namespace {
  6182. class PointerExprEvaluator
  6183. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6184. LValue &Result;
  6185. bool InvalidBaseOK;
  6186. bool Success(const Expr *E) {
  6187. Result.set(E);
  6188. return true;
  6189. }
  6190. bool evaluateLValue(const Expr *E, LValue &Result) {
  6191. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6192. }
  6193. bool evaluatePointer(const Expr *E, LValue &Result) {
  6194. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6195. }
  6196. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6197. public:
  6198. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6199. : ExprEvaluatorBaseTy(info), Result(Result),
  6200. InvalidBaseOK(InvalidBaseOK) {}
  6201. bool Success(const APValue &V, const Expr *E) {
  6202. Result.setFrom(Info.Ctx, V);
  6203. return true;
  6204. }
  6205. bool ZeroInitialization(const Expr *E) {
  6206. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  6207. Result.setNull(E->getType(), TargetVal);
  6208. return true;
  6209. }
  6210. bool VisitBinaryOperator(const BinaryOperator *E);
  6211. bool VisitCastExpr(const CastExpr* E);
  6212. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6213. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6214. { return Success(E); }
  6215. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6216. if (E->isExpressibleAsConstantInitializer())
  6217. return Success(E);
  6218. if (Info.noteFailure())
  6219. EvaluateIgnoredValue(Info, E->getSubExpr());
  6220. return Error(E);
  6221. }
  6222. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6223. { return Success(E); }
  6224. bool VisitCallExpr(const CallExpr *E);
  6225. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6226. bool VisitBlockExpr(const BlockExpr *E) {
  6227. if (!E->getBlockDecl()->hasCaptures())
  6228. return Success(E);
  6229. return Error(E);
  6230. }
  6231. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6232. // Can't look at 'this' when checking a potential constant expression.
  6233. if (Info.checkingPotentialConstantExpression())
  6234. return false;
  6235. if (!Info.CurrentCall->This) {
  6236. if (Info.getLangOpts().CPlusPlus11)
  6237. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6238. else
  6239. Info.FFDiag(E);
  6240. return false;
  6241. }
  6242. Result = *Info.CurrentCall->This;
  6243. // If we are inside a lambda's call operator, the 'this' expression refers
  6244. // to the enclosing '*this' object (either by value or reference) which is
  6245. // either copied into the closure object's field that represents the '*this'
  6246. // or refers to '*this'.
  6247. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6248. // Update 'Result' to refer to the data member/field of the closure object
  6249. // that represents the '*this' capture.
  6250. if (!HandleLValueMember(Info, E, Result,
  6251. Info.CurrentCall->LambdaThisCaptureField))
  6252. return false;
  6253. // If we captured '*this' by reference, replace the field with its referent.
  6254. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6255. ->isPointerType()) {
  6256. APValue RVal;
  6257. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6258. RVal))
  6259. return false;
  6260. Result.setFrom(Info.Ctx, RVal);
  6261. }
  6262. }
  6263. return true;
  6264. }
  6265. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6266. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6267. APValue LValResult = E->EvaluateInContext(
  6268. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6269. Result.setFrom(Info.Ctx, LValResult);
  6270. return true;
  6271. }
  6272. // FIXME: Missing: @protocol, @selector
  6273. };
  6274. } // end anonymous namespace
  6275. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6276. bool InvalidBaseOK) {
  6277. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6278. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6279. }
  6280. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6281. if (E->getOpcode() != BO_Add &&
  6282. E->getOpcode() != BO_Sub)
  6283. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6284. const Expr *PExp = E->getLHS();
  6285. const Expr *IExp = E->getRHS();
  6286. if (IExp->getType()->isPointerType())
  6287. std::swap(PExp, IExp);
  6288. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6289. if (!EvalPtrOK && !Info.noteFailure())
  6290. return false;
  6291. llvm::APSInt Offset;
  6292. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6293. return false;
  6294. if (E->getOpcode() == BO_Sub)
  6295. negateAsSigned(Offset);
  6296. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6297. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6298. }
  6299. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6300. return evaluateLValue(E->getSubExpr(), Result);
  6301. }
  6302. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6303. const Expr *SubExpr = E->getSubExpr();
  6304. switch (E->getCastKind()) {
  6305. default:
  6306. break;
  6307. case CK_BitCast:
  6308. case CK_CPointerToObjCPointerCast:
  6309. case CK_BlockPointerToObjCPointerCast:
  6310. case CK_AnyPointerToBlockPointerCast:
  6311. case CK_AddressSpaceConversion:
  6312. if (!Visit(SubExpr))
  6313. return false;
  6314. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  6315. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  6316. // also static_casts, but we disallow them as a resolution to DR1312.
  6317. if (!E->getType()->isVoidPointerType()) {
  6318. Result.Designator.setInvalid();
  6319. if (SubExpr->getType()->isVoidPointerType())
  6320. CCEDiag(E, diag::note_constexpr_invalid_cast)
  6321. << 3 << SubExpr->getType();
  6322. else
  6323. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6324. }
  6325. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  6326. ZeroInitialization(E);
  6327. return true;
  6328. case CK_DerivedToBase:
  6329. case CK_UncheckedDerivedToBase:
  6330. if (!evaluatePointer(E->getSubExpr(), Result))
  6331. return false;
  6332. if (!Result.Base && Result.Offset.isZero())
  6333. return true;
  6334. // Now figure out the necessary offset to add to the base LV to get from
  6335. // the derived class to the base class.
  6336. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  6337. castAs<PointerType>()->getPointeeType(),
  6338. Result);
  6339. case CK_BaseToDerived:
  6340. if (!Visit(E->getSubExpr()))
  6341. return false;
  6342. if (!Result.Base && Result.Offset.isZero())
  6343. return true;
  6344. return HandleBaseToDerivedCast(Info, E, Result);
  6345. case CK_Dynamic:
  6346. if (!Visit(E->getSubExpr()))
  6347. return false;
  6348. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6349. case CK_NullToPointer:
  6350. VisitIgnoredValue(E->getSubExpr());
  6351. return ZeroInitialization(E);
  6352. case CK_IntegralToPointer: {
  6353. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6354. APValue Value;
  6355. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  6356. break;
  6357. if (Value.isInt()) {
  6358. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  6359. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  6360. Result.Base = (Expr*)nullptr;
  6361. Result.InvalidBase = false;
  6362. Result.Offset = CharUnits::fromQuantity(N);
  6363. Result.Designator.setInvalid();
  6364. Result.IsNullPtr = false;
  6365. return true;
  6366. } else {
  6367. // Cast is of an lvalue, no need to change value.
  6368. Result.setFrom(Info.Ctx, Value);
  6369. return true;
  6370. }
  6371. }
  6372. case CK_ArrayToPointerDecay: {
  6373. if (SubExpr->isGLValue()) {
  6374. if (!evaluateLValue(SubExpr, Result))
  6375. return false;
  6376. } else {
  6377. APValue &Value = createTemporary(SubExpr, false, Result,
  6378. *Info.CurrentCall);
  6379. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  6380. return false;
  6381. }
  6382. // The result is a pointer to the first element of the array.
  6383. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  6384. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  6385. Result.addArray(Info, E, CAT);
  6386. else
  6387. Result.addUnsizedArray(Info, E, AT->getElementType());
  6388. return true;
  6389. }
  6390. case CK_FunctionToPointerDecay:
  6391. return evaluateLValue(SubExpr, Result);
  6392. case CK_LValueToRValue: {
  6393. LValue LVal;
  6394. if (!evaluateLValue(E->getSubExpr(), LVal))
  6395. return false;
  6396. APValue RVal;
  6397. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6398. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6399. LVal, RVal))
  6400. return InvalidBaseOK &&
  6401. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  6402. return Success(RVal, E);
  6403. }
  6404. }
  6405. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6406. }
  6407. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  6408. UnaryExprOrTypeTrait ExprKind) {
  6409. // C++ [expr.alignof]p3:
  6410. // When alignof is applied to a reference type, the result is the
  6411. // alignment of the referenced type.
  6412. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  6413. T = Ref->getPointeeType();
  6414. if (T.getQualifiers().hasUnaligned())
  6415. return CharUnits::One();
  6416. const bool AlignOfReturnsPreferred =
  6417. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  6418. // __alignof is defined to return the preferred alignment.
  6419. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  6420. // as well.
  6421. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  6422. return Info.Ctx.toCharUnitsFromBits(
  6423. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  6424. // alignof and _Alignof are defined to return the ABI alignment.
  6425. else if (ExprKind == UETT_AlignOf)
  6426. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  6427. else
  6428. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  6429. }
  6430. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  6431. UnaryExprOrTypeTrait ExprKind) {
  6432. E = E->IgnoreParens();
  6433. // The kinds of expressions that we have special-case logic here for
  6434. // should be kept up to date with the special checks for those
  6435. // expressions in Sema.
  6436. // alignof decl is always accepted, even if it doesn't make sense: we default
  6437. // to 1 in those cases.
  6438. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6439. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  6440. /*RefAsPointee*/true);
  6441. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  6442. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  6443. /*RefAsPointee*/true);
  6444. return GetAlignOfType(Info, E->getType(), ExprKind);
  6445. }
  6446. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  6447. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  6448. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  6449. return true;
  6450. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  6451. return false;
  6452. Result.setInvalid(E);
  6453. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  6454. Result.addUnsizedArray(Info, E, PointeeTy);
  6455. return true;
  6456. }
  6457. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6458. if (IsStringLiteralCall(E))
  6459. return Success(E);
  6460. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6461. return VisitBuiltinCallExpr(E, BuiltinOp);
  6462. return visitNonBuiltinCallExpr(E);
  6463. }
  6464. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6465. unsigned BuiltinOp) {
  6466. switch (BuiltinOp) {
  6467. case Builtin::BI__builtin_addressof:
  6468. return evaluateLValue(E->getArg(0), Result);
  6469. case Builtin::BI__builtin_assume_aligned: {
  6470. // We need to be very careful here because: if the pointer does not have the
  6471. // asserted alignment, then the behavior is undefined, and undefined
  6472. // behavior is non-constant.
  6473. if (!evaluatePointer(E->getArg(0), Result))
  6474. return false;
  6475. LValue OffsetResult(Result);
  6476. APSInt Alignment;
  6477. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  6478. return false;
  6479. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  6480. if (E->getNumArgs() > 2) {
  6481. APSInt Offset;
  6482. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  6483. return false;
  6484. int64_t AdditionalOffset = -Offset.getZExtValue();
  6485. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  6486. }
  6487. // If there is a base object, then it must have the correct alignment.
  6488. if (OffsetResult.Base) {
  6489. CharUnits BaseAlignment;
  6490. if (const ValueDecl *VD =
  6491. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  6492. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  6493. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  6494. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  6495. } else {
  6496. BaseAlignment = GetAlignOfType(
  6497. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  6498. }
  6499. if (BaseAlignment < Align) {
  6500. Result.Designator.setInvalid();
  6501. // FIXME: Add support to Diagnostic for long / long long.
  6502. CCEDiag(E->getArg(0),
  6503. diag::note_constexpr_baa_insufficient_alignment) << 0
  6504. << (unsigned)BaseAlignment.getQuantity()
  6505. << (unsigned)Align.getQuantity();
  6506. return false;
  6507. }
  6508. }
  6509. // The offset must also have the correct alignment.
  6510. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  6511. Result.Designator.setInvalid();
  6512. (OffsetResult.Base
  6513. ? CCEDiag(E->getArg(0),
  6514. diag::note_constexpr_baa_insufficient_alignment) << 1
  6515. : CCEDiag(E->getArg(0),
  6516. diag::note_constexpr_baa_value_insufficient_alignment))
  6517. << (int)OffsetResult.Offset.getQuantity()
  6518. << (unsigned)Align.getQuantity();
  6519. return false;
  6520. }
  6521. return true;
  6522. }
  6523. case Builtin::BI__builtin_launder:
  6524. return evaluatePointer(E->getArg(0), Result);
  6525. case Builtin::BIstrchr:
  6526. case Builtin::BIwcschr:
  6527. case Builtin::BImemchr:
  6528. case Builtin::BIwmemchr:
  6529. if (Info.getLangOpts().CPlusPlus11)
  6530. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6531. << /*isConstexpr*/0 << /*isConstructor*/0
  6532. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6533. else
  6534. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6535. LLVM_FALLTHROUGH;
  6536. case Builtin::BI__builtin_strchr:
  6537. case Builtin::BI__builtin_wcschr:
  6538. case Builtin::BI__builtin_memchr:
  6539. case Builtin::BI__builtin_char_memchr:
  6540. case Builtin::BI__builtin_wmemchr: {
  6541. if (!Visit(E->getArg(0)))
  6542. return false;
  6543. APSInt Desired;
  6544. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  6545. return false;
  6546. uint64_t MaxLength = uint64_t(-1);
  6547. if (BuiltinOp != Builtin::BIstrchr &&
  6548. BuiltinOp != Builtin::BIwcschr &&
  6549. BuiltinOp != Builtin::BI__builtin_strchr &&
  6550. BuiltinOp != Builtin::BI__builtin_wcschr) {
  6551. APSInt N;
  6552. if (!EvaluateInteger(E->getArg(2), N, Info))
  6553. return false;
  6554. MaxLength = N.getExtValue();
  6555. }
  6556. // We cannot find the value if there are no candidates to match against.
  6557. if (MaxLength == 0u)
  6558. return ZeroInitialization(E);
  6559. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  6560. Result.Designator.Invalid)
  6561. return false;
  6562. QualType CharTy = Result.Designator.getType(Info.Ctx);
  6563. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  6564. BuiltinOp == Builtin::BI__builtin_memchr;
  6565. assert(IsRawByte ||
  6566. Info.Ctx.hasSameUnqualifiedType(
  6567. CharTy, E->getArg(0)->getType()->getPointeeType()));
  6568. // Pointers to const void may point to objects of incomplete type.
  6569. if (IsRawByte && CharTy->isIncompleteType()) {
  6570. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  6571. return false;
  6572. }
  6573. // Give up on byte-oriented matching against multibyte elements.
  6574. // FIXME: We can compare the bytes in the correct order.
  6575. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  6576. return false;
  6577. // Figure out what value we're actually looking for (after converting to
  6578. // the corresponding unsigned type if necessary).
  6579. uint64_t DesiredVal;
  6580. bool StopAtNull = false;
  6581. switch (BuiltinOp) {
  6582. case Builtin::BIstrchr:
  6583. case Builtin::BI__builtin_strchr:
  6584. // strchr compares directly to the passed integer, and therefore
  6585. // always fails if given an int that is not a char.
  6586. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  6587. E->getArg(1)->getType(),
  6588. Desired),
  6589. Desired))
  6590. return ZeroInitialization(E);
  6591. StopAtNull = true;
  6592. LLVM_FALLTHROUGH;
  6593. case Builtin::BImemchr:
  6594. case Builtin::BI__builtin_memchr:
  6595. case Builtin::BI__builtin_char_memchr:
  6596. // memchr compares by converting both sides to unsigned char. That's also
  6597. // correct for strchr if we get this far (to cope with plain char being
  6598. // unsigned in the strchr case).
  6599. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  6600. break;
  6601. case Builtin::BIwcschr:
  6602. case Builtin::BI__builtin_wcschr:
  6603. StopAtNull = true;
  6604. LLVM_FALLTHROUGH;
  6605. case Builtin::BIwmemchr:
  6606. case Builtin::BI__builtin_wmemchr:
  6607. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  6608. DesiredVal = Desired.getZExtValue();
  6609. break;
  6610. }
  6611. for (; MaxLength; --MaxLength) {
  6612. APValue Char;
  6613. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  6614. !Char.isInt())
  6615. return false;
  6616. if (Char.getInt().getZExtValue() == DesiredVal)
  6617. return true;
  6618. if (StopAtNull && !Char.getInt())
  6619. break;
  6620. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  6621. return false;
  6622. }
  6623. // Not found: return nullptr.
  6624. return ZeroInitialization(E);
  6625. }
  6626. case Builtin::BImemcpy:
  6627. case Builtin::BImemmove:
  6628. case Builtin::BIwmemcpy:
  6629. case Builtin::BIwmemmove:
  6630. if (Info.getLangOpts().CPlusPlus11)
  6631. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6632. << /*isConstexpr*/0 << /*isConstructor*/0
  6633. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6634. else
  6635. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6636. LLVM_FALLTHROUGH;
  6637. case Builtin::BI__builtin_memcpy:
  6638. case Builtin::BI__builtin_memmove:
  6639. case Builtin::BI__builtin_wmemcpy:
  6640. case Builtin::BI__builtin_wmemmove: {
  6641. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  6642. BuiltinOp == Builtin::BIwmemmove ||
  6643. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  6644. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6645. bool Move = BuiltinOp == Builtin::BImemmove ||
  6646. BuiltinOp == Builtin::BIwmemmove ||
  6647. BuiltinOp == Builtin::BI__builtin_memmove ||
  6648. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6649. // The result of mem* is the first argument.
  6650. if (!Visit(E->getArg(0)))
  6651. return false;
  6652. LValue Dest = Result;
  6653. LValue Src;
  6654. if (!EvaluatePointer(E->getArg(1), Src, Info))
  6655. return false;
  6656. APSInt N;
  6657. if (!EvaluateInteger(E->getArg(2), N, Info))
  6658. return false;
  6659. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  6660. // If the size is zero, we treat this as always being a valid no-op.
  6661. // (Even if one of the src and dest pointers is null.)
  6662. if (!N)
  6663. return true;
  6664. // Otherwise, if either of the operands is null, we can't proceed. Don't
  6665. // try to determine the type of the copied objects, because there aren't
  6666. // any.
  6667. if (!Src.Base || !Dest.Base) {
  6668. APValue Val;
  6669. (!Src.Base ? Src : Dest).moveInto(Val);
  6670. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  6671. << Move << WChar << !!Src.Base
  6672. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  6673. return false;
  6674. }
  6675. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  6676. return false;
  6677. // We require that Src and Dest are both pointers to arrays of
  6678. // trivially-copyable type. (For the wide version, the designator will be
  6679. // invalid if the designated object is not a wchar_t.)
  6680. QualType T = Dest.Designator.getType(Info.Ctx);
  6681. QualType SrcT = Src.Designator.getType(Info.Ctx);
  6682. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  6683. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  6684. return false;
  6685. }
  6686. if (T->isIncompleteType()) {
  6687. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  6688. return false;
  6689. }
  6690. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  6691. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  6692. return false;
  6693. }
  6694. // Figure out how many T's we're copying.
  6695. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  6696. if (!WChar) {
  6697. uint64_t Remainder;
  6698. llvm::APInt OrigN = N;
  6699. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  6700. if (Remainder) {
  6701. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6702. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  6703. << (unsigned)TSize;
  6704. return false;
  6705. }
  6706. }
  6707. // Check that the copying will remain within the arrays, just so that we
  6708. // can give a more meaningful diagnostic. This implicitly also checks that
  6709. // N fits into 64 bits.
  6710. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  6711. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  6712. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  6713. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6714. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  6715. << N.toString(10, /*Signed*/false);
  6716. return false;
  6717. }
  6718. uint64_t NElems = N.getZExtValue();
  6719. uint64_t NBytes = NElems * TSize;
  6720. // Check for overlap.
  6721. int Direction = 1;
  6722. if (HasSameBase(Src, Dest)) {
  6723. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  6724. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  6725. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  6726. // Dest is inside the source region.
  6727. if (!Move) {
  6728. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6729. return false;
  6730. }
  6731. // For memmove and friends, copy backwards.
  6732. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  6733. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  6734. return false;
  6735. Direction = -1;
  6736. } else if (!Move && SrcOffset >= DestOffset &&
  6737. SrcOffset - DestOffset < NBytes) {
  6738. // Src is inside the destination region for memcpy: invalid.
  6739. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6740. return false;
  6741. }
  6742. }
  6743. while (true) {
  6744. APValue Val;
  6745. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  6746. !handleAssignment(Info, E, Dest, T, Val))
  6747. return false;
  6748. // Do not iterate past the last element; if we're copying backwards, that
  6749. // might take us off the start of the array.
  6750. if (--NElems == 0)
  6751. return true;
  6752. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  6753. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  6754. return false;
  6755. }
  6756. }
  6757. default:
  6758. return visitNonBuiltinCallExpr(E);
  6759. }
  6760. }
  6761. //===----------------------------------------------------------------------===//
  6762. // Member Pointer Evaluation
  6763. //===----------------------------------------------------------------------===//
  6764. namespace {
  6765. class MemberPointerExprEvaluator
  6766. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  6767. MemberPtr &Result;
  6768. bool Success(const ValueDecl *D) {
  6769. Result = MemberPtr(D);
  6770. return true;
  6771. }
  6772. public:
  6773. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  6774. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  6775. bool Success(const APValue &V, const Expr *E) {
  6776. Result.setFrom(V);
  6777. return true;
  6778. }
  6779. bool ZeroInitialization(const Expr *E) {
  6780. return Success((const ValueDecl*)nullptr);
  6781. }
  6782. bool VisitCastExpr(const CastExpr *E);
  6783. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6784. };
  6785. } // end anonymous namespace
  6786. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  6787. EvalInfo &Info) {
  6788. assert(E->isRValue() && E->getType()->isMemberPointerType());
  6789. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  6790. }
  6791. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6792. switch (E->getCastKind()) {
  6793. default:
  6794. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6795. case CK_NullToMemberPointer:
  6796. VisitIgnoredValue(E->getSubExpr());
  6797. return ZeroInitialization(E);
  6798. case CK_BaseToDerivedMemberPointer: {
  6799. if (!Visit(E->getSubExpr()))
  6800. return false;
  6801. if (E->path_empty())
  6802. return true;
  6803. // Base-to-derived member pointer casts store the path in derived-to-base
  6804. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  6805. // the wrong end of the derived->base arc, so stagger the path by one class.
  6806. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  6807. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  6808. PathI != PathE; ++PathI) {
  6809. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6810. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  6811. if (!Result.castToDerived(Derived))
  6812. return Error(E);
  6813. }
  6814. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  6815. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  6816. return Error(E);
  6817. return true;
  6818. }
  6819. case CK_DerivedToBaseMemberPointer:
  6820. if (!Visit(E->getSubExpr()))
  6821. return false;
  6822. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6823. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6824. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6825. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6826. if (!Result.castToBase(Base))
  6827. return Error(E);
  6828. }
  6829. return true;
  6830. }
  6831. }
  6832. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6833. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  6834. // member can be formed.
  6835. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  6836. }
  6837. //===----------------------------------------------------------------------===//
  6838. // Record Evaluation
  6839. //===----------------------------------------------------------------------===//
  6840. namespace {
  6841. class RecordExprEvaluator
  6842. : public ExprEvaluatorBase<RecordExprEvaluator> {
  6843. const LValue &This;
  6844. APValue &Result;
  6845. public:
  6846. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  6847. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  6848. bool Success(const APValue &V, const Expr *E) {
  6849. Result = V;
  6850. return true;
  6851. }
  6852. bool ZeroInitialization(const Expr *E) {
  6853. return ZeroInitialization(E, E->getType());
  6854. }
  6855. bool ZeroInitialization(const Expr *E, QualType T);
  6856. bool VisitCallExpr(const CallExpr *E) {
  6857. return handleCallExpr(E, Result, &This);
  6858. }
  6859. bool VisitCastExpr(const CastExpr *E);
  6860. bool VisitInitListExpr(const InitListExpr *E);
  6861. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6862. return VisitCXXConstructExpr(E, E->getType());
  6863. }
  6864. bool VisitLambdaExpr(const LambdaExpr *E);
  6865. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  6866. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  6867. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  6868. bool VisitBinCmp(const BinaryOperator *E);
  6869. };
  6870. }
  6871. /// Perform zero-initialization on an object of non-union class type.
  6872. /// C++11 [dcl.init]p5:
  6873. /// To zero-initialize an object or reference of type T means:
  6874. /// [...]
  6875. /// -- if T is a (possibly cv-qualified) non-union class type,
  6876. /// each non-static data member and each base-class subobject is
  6877. /// zero-initialized
  6878. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  6879. const RecordDecl *RD,
  6880. const LValue &This, APValue &Result) {
  6881. assert(!RD->isUnion() && "Expected non-union class type");
  6882. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  6883. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  6884. std::distance(RD->field_begin(), RD->field_end()));
  6885. if (RD->isInvalidDecl()) return false;
  6886. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6887. if (CD) {
  6888. unsigned Index = 0;
  6889. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  6890. End = CD->bases_end(); I != End; ++I, ++Index) {
  6891. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  6892. LValue Subobject = This;
  6893. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  6894. return false;
  6895. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  6896. Result.getStructBase(Index)))
  6897. return false;
  6898. }
  6899. }
  6900. for (const auto *I : RD->fields()) {
  6901. // -- if T is a reference type, no initialization is performed.
  6902. if (I->getType()->isReferenceType())
  6903. continue;
  6904. LValue Subobject = This;
  6905. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  6906. return false;
  6907. ImplicitValueInitExpr VIE(I->getType());
  6908. if (!EvaluateInPlace(
  6909. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  6910. return false;
  6911. }
  6912. return true;
  6913. }
  6914. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  6915. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  6916. if (RD->isInvalidDecl()) return false;
  6917. if (RD->isUnion()) {
  6918. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  6919. // object's first non-static named data member is zero-initialized
  6920. RecordDecl::field_iterator I = RD->field_begin();
  6921. if (I == RD->field_end()) {
  6922. Result = APValue((const FieldDecl*)nullptr);
  6923. return true;
  6924. }
  6925. LValue Subobject = This;
  6926. if (!HandleLValueMember(Info, E, Subobject, *I))
  6927. return false;
  6928. Result = APValue(*I);
  6929. ImplicitValueInitExpr VIE(I->getType());
  6930. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  6931. }
  6932. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  6933. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  6934. return false;
  6935. }
  6936. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  6937. }
  6938. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6939. switch (E->getCastKind()) {
  6940. default:
  6941. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6942. case CK_ConstructorConversion:
  6943. return Visit(E->getSubExpr());
  6944. case CK_DerivedToBase:
  6945. case CK_UncheckedDerivedToBase: {
  6946. APValue DerivedObject;
  6947. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  6948. return false;
  6949. if (!DerivedObject.isStruct())
  6950. return Error(E->getSubExpr());
  6951. // Derived-to-base rvalue conversion: just slice off the derived part.
  6952. APValue *Value = &DerivedObject;
  6953. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  6954. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6955. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6956. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  6957. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6958. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  6959. RD = Base;
  6960. }
  6961. Result = *Value;
  6962. return true;
  6963. }
  6964. }
  6965. }
  6966. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6967. if (E->isTransparent())
  6968. return Visit(E->getInit(0));
  6969. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  6970. if (RD->isInvalidDecl()) return false;
  6971. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6972. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  6973. EvalInfo::EvaluatingConstructorRAII EvalObj(
  6974. Info,
  6975. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  6976. CXXRD && CXXRD->getNumBases());
  6977. if (RD->isUnion()) {
  6978. const FieldDecl *Field = E->getInitializedFieldInUnion();
  6979. Result = APValue(Field);
  6980. if (!Field)
  6981. return true;
  6982. // If the initializer list for a union does not contain any elements, the
  6983. // first element of the union is value-initialized.
  6984. // FIXME: The element should be initialized from an initializer list.
  6985. // Is this difference ever observable for initializer lists which
  6986. // we don't build?
  6987. ImplicitValueInitExpr VIE(Field->getType());
  6988. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  6989. LValue Subobject = This;
  6990. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  6991. return false;
  6992. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6993. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6994. isa<CXXDefaultInitExpr>(InitExpr));
  6995. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  6996. }
  6997. if (!Result.hasValue())
  6998. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  6999. std::distance(RD->field_begin(), RD->field_end()));
  7000. unsigned ElementNo = 0;
  7001. bool Success = true;
  7002. // Initialize base classes.
  7003. if (CXXRD && CXXRD->getNumBases()) {
  7004. for (const auto &Base : CXXRD->bases()) {
  7005. assert(ElementNo < E->getNumInits() && "missing init for base class");
  7006. const Expr *Init = E->getInit(ElementNo);
  7007. LValue Subobject = This;
  7008. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  7009. return false;
  7010. APValue &FieldVal = Result.getStructBase(ElementNo);
  7011. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  7012. if (!Info.noteFailure())
  7013. return false;
  7014. Success = false;
  7015. }
  7016. ++ElementNo;
  7017. }
  7018. EvalObj.finishedConstructingBases();
  7019. }
  7020. // Initialize members.
  7021. for (const auto *Field : RD->fields()) {
  7022. // Anonymous bit-fields are not considered members of the class for
  7023. // purposes of aggregate initialization.
  7024. if (Field->isUnnamedBitfield())
  7025. continue;
  7026. LValue Subobject = This;
  7027. bool HaveInit = ElementNo < E->getNumInits();
  7028. // FIXME: Diagnostics here should point to the end of the initializer
  7029. // list, not the start.
  7030. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  7031. Subobject, Field, &Layout))
  7032. return false;
  7033. // Perform an implicit value-initialization for members beyond the end of
  7034. // the initializer list.
  7035. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  7036. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  7037. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7038. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7039. isa<CXXDefaultInitExpr>(Init));
  7040. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7041. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  7042. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  7043. FieldVal, Field))) {
  7044. if (!Info.noteFailure())
  7045. return false;
  7046. Success = false;
  7047. }
  7048. }
  7049. return Success;
  7050. }
  7051. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7052. QualType T) {
  7053. // Note that E's type is not necessarily the type of our class here; we might
  7054. // be initializing an array element instead.
  7055. const CXXConstructorDecl *FD = E->getConstructor();
  7056. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  7057. bool ZeroInit = E->requiresZeroInitialization();
  7058. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  7059. // If we've already performed zero-initialization, we're already done.
  7060. if (Result.hasValue())
  7061. return true;
  7062. // We can get here in two different ways:
  7063. // 1) We're performing value-initialization, and should zero-initialize
  7064. // the object, or
  7065. // 2) We're performing default-initialization of an object with a trivial
  7066. // constexpr default constructor, in which case we should start the
  7067. // lifetimes of all the base subobjects (there can be no data member
  7068. // subobjects in this case) per [basic.life]p1.
  7069. // Either way, ZeroInitialization is appropriate.
  7070. return ZeroInitialization(E, T);
  7071. }
  7072. const FunctionDecl *Definition = nullptr;
  7073. auto Body = FD->getBody(Definition);
  7074. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7075. return false;
  7076. // Avoid materializing a temporary for an elidable copy/move constructor.
  7077. if (E->isElidable() && !ZeroInit)
  7078. if (const MaterializeTemporaryExpr *ME
  7079. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  7080. return Visit(ME->GetTemporaryExpr());
  7081. if (ZeroInit && !ZeroInitialization(E, T))
  7082. return false;
  7083. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  7084. return HandleConstructorCall(E, This, Args,
  7085. cast<CXXConstructorDecl>(Definition), Info,
  7086. Result);
  7087. }
  7088. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  7089. const CXXInheritedCtorInitExpr *E) {
  7090. if (!Info.CurrentCall) {
  7091. assert(Info.checkingPotentialConstantExpression());
  7092. return false;
  7093. }
  7094. const CXXConstructorDecl *FD = E->getConstructor();
  7095. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  7096. return false;
  7097. const FunctionDecl *Definition = nullptr;
  7098. auto Body = FD->getBody(Definition);
  7099. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7100. return false;
  7101. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  7102. cast<CXXConstructorDecl>(Definition), Info,
  7103. Result);
  7104. }
  7105. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  7106. const CXXStdInitializerListExpr *E) {
  7107. const ConstantArrayType *ArrayType =
  7108. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  7109. LValue Array;
  7110. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  7111. return false;
  7112. // Get a pointer to the first element of the array.
  7113. Array.addArray(Info, E, ArrayType);
  7114. // FIXME: Perform the checks on the field types in SemaInit.
  7115. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  7116. RecordDecl::field_iterator Field = Record->field_begin();
  7117. if (Field == Record->field_end())
  7118. return Error(E);
  7119. // Start pointer.
  7120. if (!Field->getType()->isPointerType() ||
  7121. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7122. ArrayType->getElementType()))
  7123. return Error(E);
  7124. // FIXME: What if the initializer_list type has base classes, etc?
  7125. Result = APValue(APValue::UninitStruct(), 0, 2);
  7126. Array.moveInto(Result.getStructField(0));
  7127. if (++Field == Record->field_end())
  7128. return Error(E);
  7129. if (Field->getType()->isPointerType() &&
  7130. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7131. ArrayType->getElementType())) {
  7132. // End pointer.
  7133. if (!HandleLValueArrayAdjustment(Info, E, Array,
  7134. ArrayType->getElementType(),
  7135. ArrayType->getSize().getZExtValue()))
  7136. return false;
  7137. Array.moveInto(Result.getStructField(1));
  7138. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  7139. // Length.
  7140. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  7141. else
  7142. return Error(E);
  7143. if (++Field != Record->field_end())
  7144. return Error(E);
  7145. return true;
  7146. }
  7147. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  7148. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  7149. if (ClosureClass->isInvalidDecl()) return false;
  7150. if (Info.checkingPotentialConstantExpression()) return true;
  7151. const size_t NumFields =
  7152. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  7153. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  7154. E->capture_init_end()) &&
  7155. "The number of lambda capture initializers should equal the number of "
  7156. "fields within the closure type");
  7157. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  7158. // Iterate through all the lambda's closure object's fields and initialize
  7159. // them.
  7160. auto *CaptureInitIt = E->capture_init_begin();
  7161. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  7162. bool Success = true;
  7163. for (const auto *Field : ClosureClass->fields()) {
  7164. assert(CaptureInitIt != E->capture_init_end());
  7165. // Get the initializer for this field
  7166. Expr *const CurFieldInit = *CaptureInitIt++;
  7167. // If there is no initializer, either this is a VLA or an error has
  7168. // occurred.
  7169. if (!CurFieldInit)
  7170. return Error(E);
  7171. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7172. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  7173. if (!Info.keepEvaluatingAfterFailure())
  7174. return false;
  7175. Success = false;
  7176. }
  7177. ++CaptureIt;
  7178. }
  7179. return Success;
  7180. }
  7181. static bool EvaluateRecord(const Expr *E, const LValue &This,
  7182. APValue &Result, EvalInfo &Info) {
  7183. assert(E->isRValue() && E->getType()->isRecordType() &&
  7184. "can't evaluate expression as a record rvalue");
  7185. return RecordExprEvaluator(Info, This, Result).Visit(E);
  7186. }
  7187. //===----------------------------------------------------------------------===//
  7188. // Temporary Evaluation
  7189. //
  7190. // Temporaries are represented in the AST as rvalues, but generally behave like
  7191. // lvalues. The full-object of which the temporary is a subobject is implicitly
  7192. // materialized so that a reference can bind to it.
  7193. //===----------------------------------------------------------------------===//
  7194. namespace {
  7195. class TemporaryExprEvaluator
  7196. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  7197. public:
  7198. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  7199. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  7200. /// Visit an expression which constructs the value of this temporary.
  7201. bool VisitConstructExpr(const Expr *E) {
  7202. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  7203. return EvaluateInPlace(Value, Info, Result, E);
  7204. }
  7205. bool VisitCastExpr(const CastExpr *E) {
  7206. switch (E->getCastKind()) {
  7207. default:
  7208. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7209. case CK_ConstructorConversion:
  7210. return VisitConstructExpr(E->getSubExpr());
  7211. }
  7212. }
  7213. bool VisitInitListExpr(const InitListExpr *E) {
  7214. return VisitConstructExpr(E);
  7215. }
  7216. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7217. return VisitConstructExpr(E);
  7218. }
  7219. bool VisitCallExpr(const CallExpr *E) {
  7220. return VisitConstructExpr(E);
  7221. }
  7222. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  7223. return VisitConstructExpr(E);
  7224. }
  7225. bool VisitLambdaExpr(const LambdaExpr *E) {
  7226. return VisitConstructExpr(E);
  7227. }
  7228. };
  7229. } // end anonymous namespace
  7230. /// Evaluate an expression of record type as a temporary.
  7231. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  7232. assert(E->isRValue() && E->getType()->isRecordType());
  7233. return TemporaryExprEvaluator(Info, Result).Visit(E);
  7234. }
  7235. //===----------------------------------------------------------------------===//
  7236. // Vector Evaluation
  7237. //===----------------------------------------------------------------------===//
  7238. namespace {
  7239. class VectorExprEvaluator
  7240. : public ExprEvaluatorBase<VectorExprEvaluator> {
  7241. APValue &Result;
  7242. public:
  7243. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  7244. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7245. bool Success(ArrayRef<APValue> V, const Expr *E) {
  7246. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  7247. // FIXME: remove this APValue copy.
  7248. Result = APValue(V.data(), V.size());
  7249. return true;
  7250. }
  7251. bool Success(const APValue &V, const Expr *E) {
  7252. assert(V.isVector());
  7253. Result = V;
  7254. return true;
  7255. }
  7256. bool ZeroInitialization(const Expr *E);
  7257. bool VisitUnaryReal(const UnaryOperator *E)
  7258. { return Visit(E->getSubExpr()); }
  7259. bool VisitCastExpr(const CastExpr* E);
  7260. bool VisitInitListExpr(const InitListExpr *E);
  7261. bool VisitUnaryImag(const UnaryOperator *E);
  7262. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  7263. // binary comparisons, binary and/or/xor,
  7264. // shufflevector, ExtVectorElementExpr
  7265. };
  7266. } // end anonymous namespace
  7267. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  7268. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  7269. return VectorExprEvaluator(Info, Result).Visit(E);
  7270. }
  7271. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7272. const VectorType *VTy = E->getType()->castAs<VectorType>();
  7273. unsigned NElts = VTy->getNumElements();
  7274. const Expr *SE = E->getSubExpr();
  7275. QualType SETy = SE->getType();
  7276. switch (E->getCastKind()) {
  7277. case CK_VectorSplat: {
  7278. APValue Val = APValue();
  7279. if (SETy->isIntegerType()) {
  7280. APSInt IntResult;
  7281. if (!EvaluateInteger(SE, IntResult, Info))
  7282. return false;
  7283. Val = APValue(std::move(IntResult));
  7284. } else if (SETy->isRealFloatingType()) {
  7285. APFloat FloatResult(0.0);
  7286. if (!EvaluateFloat(SE, FloatResult, Info))
  7287. return false;
  7288. Val = APValue(std::move(FloatResult));
  7289. } else {
  7290. return Error(E);
  7291. }
  7292. // Splat and create vector APValue.
  7293. SmallVector<APValue, 4> Elts(NElts, Val);
  7294. return Success(Elts, E);
  7295. }
  7296. case CK_BitCast: {
  7297. // Evaluate the operand into an APInt we can extract from.
  7298. llvm::APInt SValInt;
  7299. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  7300. return false;
  7301. // Extract the elements
  7302. QualType EltTy = VTy->getElementType();
  7303. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  7304. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  7305. SmallVector<APValue, 4> Elts;
  7306. if (EltTy->isRealFloatingType()) {
  7307. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  7308. unsigned FloatEltSize = EltSize;
  7309. if (&Sem == &APFloat::x87DoubleExtended())
  7310. FloatEltSize = 80;
  7311. for (unsigned i = 0; i < NElts; i++) {
  7312. llvm::APInt Elt;
  7313. if (BigEndian)
  7314. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  7315. else
  7316. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  7317. Elts.push_back(APValue(APFloat(Sem, Elt)));
  7318. }
  7319. } else if (EltTy->isIntegerType()) {
  7320. for (unsigned i = 0; i < NElts; i++) {
  7321. llvm::APInt Elt;
  7322. if (BigEndian)
  7323. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  7324. else
  7325. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  7326. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  7327. }
  7328. } else {
  7329. return Error(E);
  7330. }
  7331. return Success(Elts, E);
  7332. }
  7333. default:
  7334. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7335. }
  7336. }
  7337. bool
  7338. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7339. const VectorType *VT = E->getType()->castAs<VectorType>();
  7340. unsigned NumInits = E->getNumInits();
  7341. unsigned NumElements = VT->getNumElements();
  7342. QualType EltTy = VT->getElementType();
  7343. SmallVector<APValue, 4> Elements;
  7344. // The number of initializers can be less than the number of
  7345. // vector elements. For OpenCL, this can be due to nested vector
  7346. // initialization. For GCC compatibility, missing trailing elements
  7347. // should be initialized with zeroes.
  7348. unsigned CountInits = 0, CountElts = 0;
  7349. while (CountElts < NumElements) {
  7350. // Handle nested vector initialization.
  7351. if (CountInits < NumInits
  7352. && E->getInit(CountInits)->getType()->isVectorType()) {
  7353. APValue v;
  7354. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  7355. return Error(E);
  7356. unsigned vlen = v.getVectorLength();
  7357. for (unsigned j = 0; j < vlen; j++)
  7358. Elements.push_back(v.getVectorElt(j));
  7359. CountElts += vlen;
  7360. } else if (EltTy->isIntegerType()) {
  7361. llvm::APSInt sInt(32);
  7362. if (CountInits < NumInits) {
  7363. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  7364. return false;
  7365. } else // trailing integer zero.
  7366. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  7367. Elements.push_back(APValue(sInt));
  7368. CountElts++;
  7369. } else {
  7370. llvm::APFloat f(0.0);
  7371. if (CountInits < NumInits) {
  7372. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  7373. return false;
  7374. } else // trailing float zero.
  7375. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  7376. Elements.push_back(APValue(f));
  7377. CountElts++;
  7378. }
  7379. CountInits++;
  7380. }
  7381. return Success(Elements, E);
  7382. }
  7383. bool
  7384. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  7385. const VectorType *VT = E->getType()->getAs<VectorType>();
  7386. QualType EltTy = VT->getElementType();
  7387. APValue ZeroElement;
  7388. if (EltTy->isIntegerType())
  7389. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  7390. else
  7391. ZeroElement =
  7392. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  7393. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  7394. return Success(Elements, E);
  7395. }
  7396. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7397. VisitIgnoredValue(E->getSubExpr());
  7398. return ZeroInitialization(E);
  7399. }
  7400. //===----------------------------------------------------------------------===//
  7401. // Array Evaluation
  7402. //===----------------------------------------------------------------------===//
  7403. namespace {
  7404. class ArrayExprEvaluator
  7405. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  7406. const LValue &This;
  7407. APValue &Result;
  7408. public:
  7409. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  7410. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  7411. bool Success(const APValue &V, const Expr *E) {
  7412. assert(V.isArray() && "expected array");
  7413. Result = V;
  7414. return true;
  7415. }
  7416. bool ZeroInitialization(const Expr *E) {
  7417. const ConstantArrayType *CAT =
  7418. Info.Ctx.getAsConstantArrayType(E->getType());
  7419. if (!CAT)
  7420. return Error(E);
  7421. Result = APValue(APValue::UninitArray(), 0,
  7422. CAT->getSize().getZExtValue());
  7423. if (!Result.hasArrayFiller()) return true;
  7424. // Zero-initialize all elements.
  7425. LValue Subobject = This;
  7426. Subobject.addArray(Info, E, CAT);
  7427. ImplicitValueInitExpr VIE(CAT->getElementType());
  7428. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  7429. }
  7430. bool VisitCallExpr(const CallExpr *E) {
  7431. return handleCallExpr(E, Result, &This);
  7432. }
  7433. bool VisitInitListExpr(const InitListExpr *E);
  7434. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  7435. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  7436. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  7437. const LValue &Subobject,
  7438. APValue *Value, QualType Type);
  7439. bool VisitStringLiteral(const StringLiteral *E) {
  7440. expandStringLiteral(Info, E, Result);
  7441. return true;
  7442. }
  7443. };
  7444. } // end anonymous namespace
  7445. static bool EvaluateArray(const Expr *E, const LValue &This,
  7446. APValue &Result, EvalInfo &Info) {
  7447. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  7448. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  7449. }
  7450. // Return true iff the given array filler may depend on the element index.
  7451. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  7452. // For now, just whitelist non-class value-initialization and initialization
  7453. // lists comprised of them.
  7454. if (isa<ImplicitValueInitExpr>(FillerExpr))
  7455. return false;
  7456. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  7457. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  7458. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  7459. return true;
  7460. }
  7461. return false;
  7462. }
  7463. return true;
  7464. }
  7465. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7466. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  7467. if (!CAT)
  7468. return Error(E);
  7469. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  7470. // an appropriately-typed string literal enclosed in braces.
  7471. if (E->isStringLiteralInit())
  7472. return Visit(E->getInit(0));
  7473. bool Success = true;
  7474. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  7475. "zero-initialized array shouldn't have any initialized elts");
  7476. APValue Filler;
  7477. if (Result.isArray() && Result.hasArrayFiller())
  7478. Filler = Result.getArrayFiller();
  7479. unsigned NumEltsToInit = E->getNumInits();
  7480. unsigned NumElts = CAT->getSize().getZExtValue();
  7481. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  7482. // If the initializer might depend on the array index, run it for each
  7483. // array element.
  7484. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  7485. NumEltsToInit = NumElts;
  7486. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  7487. << NumEltsToInit << ".\n");
  7488. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  7489. // If the array was previously zero-initialized, preserve the
  7490. // zero-initialized values.
  7491. if (Filler.hasValue()) {
  7492. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  7493. Result.getArrayInitializedElt(I) = Filler;
  7494. if (Result.hasArrayFiller())
  7495. Result.getArrayFiller() = Filler;
  7496. }
  7497. LValue Subobject = This;
  7498. Subobject.addArray(Info, E, CAT);
  7499. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  7500. const Expr *Init =
  7501. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  7502. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7503. Info, Subobject, Init) ||
  7504. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  7505. CAT->getElementType(), 1)) {
  7506. if (!Info.noteFailure())
  7507. return false;
  7508. Success = false;
  7509. }
  7510. }
  7511. if (!Result.hasArrayFiller())
  7512. return Success;
  7513. // If we get here, we have a trivial filler, which we can just evaluate
  7514. // once and splat over the rest of the array elements.
  7515. assert(FillerExpr && "no array filler for incomplete init list");
  7516. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  7517. FillerExpr) && Success;
  7518. }
  7519. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  7520. if (E->getCommonExpr() &&
  7521. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  7522. Info, E->getCommonExpr()->getSourceExpr()))
  7523. return false;
  7524. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  7525. uint64_t Elements = CAT->getSize().getZExtValue();
  7526. Result = APValue(APValue::UninitArray(), Elements, Elements);
  7527. LValue Subobject = This;
  7528. Subobject.addArray(Info, E, CAT);
  7529. bool Success = true;
  7530. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  7531. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7532. Info, Subobject, E->getSubExpr()) ||
  7533. !HandleLValueArrayAdjustment(Info, E, Subobject,
  7534. CAT->getElementType(), 1)) {
  7535. if (!Info.noteFailure())
  7536. return false;
  7537. Success = false;
  7538. }
  7539. }
  7540. return Success;
  7541. }
  7542. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7543. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  7544. }
  7545. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7546. const LValue &Subobject,
  7547. APValue *Value,
  7548. QualType Type) {
  7549. bool HadZeroInit = Value->hasValue();
  7550. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  7551. unsigned N = CAT->getSize().getZExtValue();
  7552. // Preserve the array filler if we had prior zero-initialization.
  7553. APValue Filler =
  7554. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  7555. : APValue();
  7556. *Value = APValue(APValue::UninitArray(), N, N);
  7557. if (HadZeroInit)
  7558. for (unsigned I = 0; I != N; ++I)
  7559. Value->getArrayInitializedElt(I) = Filler;
  7560. // Initialize the elements.
  7561. LValue ArrayElt = Subobject;
  7562. ArrayElt.addArray(Info, E, CAT);
  7563. for (unsigned I = 0; I != N; ++I)
  7564. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  7565. CAT->getElementType()) ||
  7566. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  7567. CAT->getElementType(), 1))
  7568. return false;
  7569. return true;
  7570. }
  7571. if (!Type->isRecordType())
  7572. return Error(E);
  7573. return RecordExprEvaluator(Info, Subobject, *Value)
  7574. .VisitCXXConstructExpr(E, Type);
  7575. }
  7576. //===----------------------------------------------------------------------===//
  7577. // Integer Evaluation
  7578. //
  7579. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  7580. // types and back in constant folding. Integer values are thus represented
  7581. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  7582. //===----------------------------------------------------------------------===//
  7583. namespace {
  7584. class IntExprEvaluator
  7585. : public ExprEvaluatorBase<IntExprEvaluator> {
  7586. APValue &Result;
  7587. public:
  7588. IntExprEvaluator(EvalInfo &info, APValue &result)
  7589. : ExprEvaluatorBaseTy(info), Result(result) {}
  7590. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  7591. assert(E->getType()->isIntegralOrEnumerationType() &&
  7592. "Invalid evaluation result.");
  7593. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  7594. "Invalid evaluation result.");
  7595. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7596. "Invalid evaluation result.");
  7597. Result = APValue(SI);
  7598. return true;
  7599. }
  7600. bool Success(const llvm::APSInt &SI, const Expr *E) {
  7601. return Success(SI, E, Result);
  7602. }
  7603. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  7604. assert(E->getType()->isIntegralOrEnumerationType() &&
  7605. "Invalid evaluation result.");
  7606. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7607. "Invalid evaluation result.");
  7608. Result = APValue(APSInt(I));
  7609. Result.getInt().setIsUnsigned(
  7610. E->getType()->isUnsignedIntegerOrEnumerationType());
  7611. return true;
  7612. }
  7613. bool Success(const llvm::APInt &I, const Expr *E) {
  7614. return Success(I, E, Result);
  7615. }
  7616. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7617. assert(E->getType()->isIntegralOrEnumerationType() &&
  7618. "Invalid evaluation result.");
  7619. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  7620. return true;
  7621. }
  7622. bool Success(uint64_t Value, const Expr *E) {
  7623. return Success(Value, E, Result);
  7624. }
  7625. bool Success(CharUnits Size, const Expr *E) {
  7626. return Success(Size.getQuantity(), E);
  7627. }
  7628. bool Success(const APValue &V, const Expr *E) {
  7629. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  7630. Result = V;
  7631. return true;
  7632. }
  7633. return Success(V.getInt(), E);
  7634. }
  7635. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  7636. //===--------------------------------------------------------------------===//
  7637. // Visitor Methods
  7638. //===--------------------------------------------------------------------===//
  7639. bool VisitConstantExpr(const ConstantExpr *E);
  7640. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  7641. return Success(E->getValue(), E);
  7642. }
  7643. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  7644. return Success(E->getValue(), E);
  7645. }
  7646. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  7647. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  7648. if (CheckReferencedDecl(E, E->getDecl()))
  7649. return true;
  7650. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  7651. }
  7652. bool VisitMemberExpr(const MemberExpr *E) {
  7653. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  7654. VisitIgnoredBaseExpression(E->getBase());
  7655. return true;
  7656. }
  7657. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  7658. }
  7659. bool VisitCallExpr(const CallExpr *E);
  7660. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  7661. bool VisitBinaryOperator(const BinaryOperator *E);
  7662. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  7663. bool VisitUnaryOperator(const UnaryOperator *E);
  7664. bool VisitCastExpr(const CastExpr* E);
  7665. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  7666. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  7667. return Success(E->getValue(), E);
  7668. }
  7669. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  7670. return Success(E->getValue(), E);
  7671. }
  7672. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  7673. if (Info.ArrayInitIndex == uint64_t(-1)) {
  7674. // We were asked to evaluate this subexpression independent of the
  7675. // enclosing ArrayInitLoopExpr. We can't do that.
  7676. Info.FFDiag(E);
  7677. return false;
  7678. }
  7679. return Success(Info.ArrayInitIndex, E);
  7680. }
  7681. // Note, GNU defines __null as an integer, not a pointer.
  7682. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  7683. return ZeroInitialization(E);
  7684. }
  7685. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  7686. return Success(E->getValue(), E);
  7687. }
  7688. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  7689. return Success(E->getValue(), E);
  7690. }
  7691. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  7692. return Success(E->getValue(), E);
  7693. }
  7694. bool VisitUnaryReal(const UnaryOperator *E);
  7695. bool VisitUnaryImag(const UnaryOperator *E);
  7696. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  7697. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  7698. bool VisitSourceLocExpr(const SourceLocExpr *E);
  7699. // FIXME: Missing: array subscript of vector, member of vector
  7700. };
  7701. class FixedPointExprEvaluator
  7702. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  7703. APValue &Result;
  7704. public:
  7705. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  7706. : ExprEvaluatorBaseTy(info), Result(result) {}
  7707. bool Success(const llvm::APInt &I, const Expr *E) {
  7708. return Success(
  7709. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7710. }
  7711. bool Success(uint64_t Value, const Expr *E) {
  7712. return Success(
  7713. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7714. }
  7715. bool Success(const APValue &V, const Expr *E) {
  7716. return Success(V.getFixedPoint(), E);
  7717. }
  7718. bool Success(const APFixedPoint &V, const Expr *E) {
  7719. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  7720. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7721. "Invalid evaluation result.");
  7722. Result = APValue(V);
  7723. return true;
  7724. }
  7725. //===--------------------------------------------------------------------===//
  7726. // Visitor Methods
  7727. //===--------------------------------------------------------------------===//
  7728. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  7729. return Success(E->getValue(), E);
  7730. }
  7731. bool VisitCastExpr(const CastExpr *E);
  7732. bool VisitUnaryOperator(const UnaryOperator *E);
  7733. bool VisitBinaryOperator(const BinaryOperator *E);
  7734. };
  7735. } // end anonymous namespace
  7736. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  7737. /// produce either the integer value or a pointer.
  7738. ///
  7739. /// GCC has a heinous extension which folds casts between pointer types and
  7740. /// pointer-sized integral types. We support this by allowing the evaluation of
  7741. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  7742. /// Some simple arithmetic on such values is supported (they are treated much
  7743. /// like char*).
  7744. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  7745. EvalInfo &Info) {
  7746. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  7747. return IntExprEvaluator(Info, Result).Visit(E);
  7748. }
  7749. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  7750. APValue Val;
  7751. if (!EvaluateIntegerOrLValue(E, Val, Info))
  7752. return false;
  7753. if (!Val.isInt()) {
  7754. // FIXME: It would be better to produce the diagnostic for casting
  7755. // a pointer to an integer.
  7756. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7757. return false;
  7758. }
  7759. Result = Val.getInt();
  7760. return true;
  7761. }
  7762. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  7763. APValue Evaluated = E->EvaluateInContext(
  7764. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  7765. return Success(Evaluated, E);
  7766. }
  7767. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  7768. EvalInfo &Info) {
  7769. if (E->getType()->isFixedPointType()) {
  7770. APValue Val;
  7771. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  7772. return false;
  7773. if (!Val.isFixedPoint())
  7774. return false;
  7775. Result = Val.getFixedPoint();
  7776. return true;
  7777. }
  7778. return false;
  7779. }
  7780. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  7781. EvalInfo &Info) {
  7782. if (E->getType()->isIntegerType()) {
  7783. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  7784. APSInt Val;
  7785. if (!EvaluateInteger(E, Val, Info))
  7786. return false;
  7787. Result = APFixedPoint(Val, FXSema);
  7788. return true;
  7789. } else if (E->getType()->isFixedPointType()) {
  7790. return EvaluateFixedPoint(E, Result, Info);
  7791. }
  7792. return false;
  7793. }
  7794. /// Check whether the given declaration can be directly converted to an integral
  7795. /// rvalue. If not, no diagnostic is produced; there are other things we can
  7796. /// try.
  7797. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  7798. // Enums are integer constant exprs.
  7799. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  7800. // Check for signedness/width mismatches between E type and ECD value.
  7801. bool SameSign = (ECD->getInitVal().isSigned()
  7802. == E->getType()->isSignedIntegerOrEnumerationType());
  7803. bool SameWidth = (ECD->getInitVal().getBitWidth()
  7804. == Info.Ctx.getIntWidth(E->getType()));
  7805. if (SameSign && SameWidth)
  7806. return Success(ECD->getInitVal(), E);
  7807. else {
  7808. // Get rid of mismatch (otherwise Success assertions will fail)
  7809. // by computing a new value matching the type of E.
  7810. llvm::APSInt Val = ECD->getInitVal();
  7811. if (!SameSign)
  7812. Val.setIsSigned(!ECD->getInitVal().isSigned());
  7813. if (!SameWidth)
  7814. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  7815. return Success(Val, E);
  7816. }
  7817. }
  7818. return false;
  7819. }
  7820. /// Values returned by __builtin_classify_type, chosen to match the values
  7821. /// produced by GCC's builtin.
  7822. enum class GCCTypeClass {
  7823. None = -1,
  7824. Void = 0,
  7825. Integer = 1,
  7826. // GCC reserves 2 for character types, but instead classifies them as
  7827. // integers.
  7828. Enum = 3,
  7829. Bool = 4,
  7830. Pointer = 5,
  7831. // GCC reserves 6 for references, but appears to never use it (because
  7832. // expressions never have reference type, presumably).
  7833. PointerToDataMember = 7,
  7834. RealFloat = 8,
  7835. Complex = 9,
  7836. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  7837. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7838. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  7839. // uses 12 for that purpose, same as for a class or struct. Maybe it
  7840. // internally implements a pointer to member as a struct? Who knows.
  7841. PointerToMemberFunction = 12, // Not a bug, see above.
  7842. ClassOrStruct = 12,
  7843. Union = 13,
  7844. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  7845. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7846. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  7847. // literals.
  7848. };
  7849. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7850. /// as GCC.
  7851. static GCCTypeClass
  7852. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  7853. assert(!T->isDependentType() && "unexpected dependent type");
  7854. QualType CanTy = T.getCanonicalType();
  7855. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  7856. switch (CanTy->getTypeClass()) {
  7857. #define TYPE(ID, BASE)
  7858. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7859. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  7860. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7861. #include "clang/AST/TypeNodes.def"
  7862. case Type::Auto:
  7863. case Type::DeducedTemplateSpecialization:
  7864. llvm_unreachable("unexpected non-canonical or dependent type");
  7865. case Type::Builtin:
  7866. switch (BT->getKind()) {
  7867. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  7868. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  7869. case BuiltinType::ID: return GCCTypeClass::Integer;
  7870. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  7871. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  7872. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  7873. case BuiltinType::ID: break;
  7874. #include "clang/AST/BuiltinTypes.def"
  7875. case BuiltinType::Void:
  7876. return GCCTypeClass::Void;
  7877. case BuiltinType::Bool:
  7878. return GCCTypeClass::Bool;
  7879. case BuiltinType::Char_U:
  7880. case BuiltinType::UChar:
  7881. case BuiltinType::WChar_U:
  7882. case BuiltinType::Char8:
  7883. case BuiltinType::Char16:
  7884. case BuiltinType::Char32:
  7885. case BuiltinType::UShort:
  7886. case BuiltinType::UInt:
  7887. case BuiltinType::ULong:
  7888. case BuiltinType::ULongLong:
  7889. case BuiltinType::UInt128:
  7890. return GCCTypeClass::Integer;
  7891. case BuiltinType::UShortAccum:
  7892. case BuiltinType::UAccum:
  7893. case BuiltinType::ULongAccum:
  7894. case BuiltinType::UShortFract:
  7895. case BuiltinType::UFract:
  7896. case BuiltinType::ULongFract:
  7897. case BuiltinType::SatUShortAccum:
  7898. case BuiltinType::SatUAccum:
  7899. case BuiltinType::SatULongAccum:
  7900. case BuiltinType::SatUShortFract:
  7901. case BuiltinType::SatUFract:
  7902. case BuiltinType::SatULongFract:
  7903. return GCCTypeClass::None;
  7904. case BuiltinType::NullPtr:
  7905. case BuiltinType::ObjCId:
  7906. case BuiltinType::ObjCClass:
  7907. case BuiltinType::ObjCSel:
  7908. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  7909. case BuiltinType::Id:
  7910. #include "clang/Basic/OpenCLImageTypes.def"
  7911. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  7912. case BuiltinType::Id:
  7913. #include "clang/Basic/OpenCLExtensionTypes.def"
  7914. case BuiltinType::OCLSampler:
  7915. case BuiltinType::OCLEvent:
  7916. case BuiltinType::OCLClkEvent:
  7917. case BuiltinType::OCLQueue:
  7918. case BuiltinType::OCLReserveID:
  7919. return GCCTypeClass::None;
  7920. case BuiltinType::Dependent:
  7921. llvm_unreachable("unexpected dependent type");
  7922. };
  7923. llvm_unreachable("unexpected placeholder type");
  7924. case Type::Enum:
  7925. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  7926. case Type::Pointer:
  7927. case Type::ConstantArray:
  7928. case Type::VariableArray:
  7929. case Type::IncompleteArray:
  7930. case Type::FunctionNoProto:
  7931. case Type::FunctionProto:
  7932. return GCCTypeClass::Pointer;
  7933. case Type::MemberPointer:
  7934. return CanTy->isMemberDataPointerType()
  7935. ? GCCTypeClass::PointerToDataMember
  7936. : GCCTypeClass::PointerToMemberFunction;
  7937. case Type::Complex:
  7938. return GCCTypeClass::Complex;
  7939. case Type::Record:
  7940. return CanTy->isUnionType() ? GCCTypeClass::Union
  7941. : GCCTypeClass::ClassOrStruct;
  7942. case Type::Atomic:
  7943. // GCC classifies _Atomic T the same as T.
  7944. return EvaluateBuiltinClassifyType(
  7945. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  7946. case Type::BlockPointer:
  7947. case Type::Vector:
  7948. case Type::ExtVector:
  7949. case Type::ObjCObject:
  7950. case Type::ObjCInterface:
  7951. case Type::ObjCObjectPointer:
  7952. case Type::Pipe:
  7953. // GCC classifies vectors as None. We follow its lead and classify all
  7954. // other types that don't fit into the regular classification the same way.
  7955. return GCCTypeClass::None;
  7956. case Type::LValueReference:
  7957. case Type::RValueReference:
  7958. llvm_unreachable("invalid type for expression");
  7959. }
  7960. llvm_unreachable("unexpected type class");
  7961. }
  7962. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7963. /// as GCC.
  7964. static GCCTypeClass
  7965. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  7966. // If no argument was supplied, default to None. This isn't
  7967. // ideal, however it is what gcc does.
  7968. if (E->getNumArgs() == 0)
  7969. return GCCTypeClass::None;
  7970. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  7971. // being an ICE, but still folds it to a constant using the type of the first
  7972. // argument.
  7973. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  7974. }
  7975. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  7976. /// __builtin_constant_p when applied to the given pointer.
  7977. ///
  7978. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  7979. /// or it points to the first character of a string literal.
  7980. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  7981. APValue::LValueBase Base = LV.getLValueBase();
  7982. if (Base.isNull()) {
  7983. // A null base is acceptable.
  7984. return true;
  7985. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  7986. if (!isa<StringLiteral>(E))
  7987. return false;
  7988. return LV.getLValueOffset().isZero();
  7989. } else if (Base.is<TypeInfoLValue>()) {
  7990. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  7991. // evaluate to true.
  7992. return true;
  7993. } else {
  7994. // Any other base is not constant enough for GCC.
  7995. return false;
  7996. }
  7997. }
  7998. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  7999. /// GCC as we can manage.
  8000. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  8001. // This evaluation is not permitted to have side-effects, so evaluate it in
  8002. // a speculative evaluation context.
  8003. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8004. // Constant-folding is always enabled for the operand of __builtin_constant_p
  8005. // (even when the enclosing evaluation context otherwise requires a strict
  8006. // language-specific constant expression).
  8007. FoldConstant Fold(Info, true);
  8008. QualType ArgType = Arg->getType();
  8009. // __builtin_constant_p always has one operand. The rules which gcc follows
  8010. // are not precisely documented, but are as follows:
  8011. //
  8012. // - If the operand is of integral, floating, complex or enumeration type,
  8013. // and can be folded to a known value of that type, it returns 1.
  8014. // - If the operand can be folded to a pointer to the first character
  8015. // of a string literal (or such a pointer cast to an integral type)
  8016. // or to a null pointer or an integer cast to a pointer, it returns 1.
  8017. //
  8018. // Otherwise, it returns 0.
  8019. //
  8020. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  8021. // its support for this did not work prior to GCC 9 and is not yet well
  8022. // understood.
  8023. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  8024. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  8025. ArgType->isNullPtrType()) {
  8026. APValue V;
  8027. if (!::EvaluateAsRValue(Info, Arg, V)) {
  8028. Fold.keepDiagnostics();
  8029. return false;
  8030. }
  8031. // For a pointer (possibly cast to integer), there are special rules.
  8032. if (V.getKind() == APValue::LValue)
  8033. return EvaluateBuiltinConstantPForLValue(V);
  8034. // Otherwise, any constant value is good enough.
  8035. return V.hasValue();
  8036. }
  8037. // Anything else isn't considered to be sufficiently constant.
  8038. return false;
  8039. }
  8040. /// Retrieves the "underlying object type" of the given expression,
  8041. /// as used by __builtin_object_size.
  8042. static QualType getObjectType(APValue::LValueBase B) {
  8043. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  8044. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  8045. return VD->getType();
  8046. } else if (const Expr *E = B.get<const Expr*>()) {
  8047. if (isa<CompoundLiteralExpr>(E))
  8048. return E->getType();
  8049. } else if (B.is<TypeInfoLValue>()) {
  8050. return B.getTypeInfoType();
  8051. }
  8052. return QualType();
  8053. }
  8054. /// A more selective version of E->IgnoreParenCasts for
  8055. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  8056. /// to change the type of E.
  8057. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  8058. ///
  8059. /// Always returns an RValue with a pointer representation.
  8060. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  8061. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  8062. auto *NoParens = E->IgnoreParens();
  8063. auto *Cast = dyn_cast<CastExpr>(NoParens);
  8064. if (Cast == nullptr)
  8065. return NoParens;
  8066. // We only conservatively allow a few kinds of casts, because this code is
  8067. // inherently a simple solution that seeks to support the common case.
  8068. auto CastKind = Cast->getCastKind();
  8069. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  8070. CastKind != CK_AddressSpaceConversion)
  8071. return NoParens;
  8072. auto *SubExpr = Cast->getSubExpr();
  8073. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  8074. return NoParens;
  8075. return ignorePointerCastsAndParens(SubExpr);
  8076. }
  8077. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  8078. /// record layout. e.g.
  8079. /// struct { struct { int a, b; } fst, snd; } obj;
  8080. /// obj.fst // no
  8081. /// obj.snd // yes
  8082. /// obj.fst.a // no
  8083. /// obj.fst.b // no
  8084. /// obj.snd.a // no
  8085. /// obj.snd.b // yes
  8086. ///
  8087. /// Please note: this function is specialized for how __builtin_object_size
  8088. /// views "objects".
  8089. ///
  8090. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  8091. /// correct result, it will always return true.
  8092. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  8093. assert(!LVal.Designator.Invalid);
  8094. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  8095. const RecordDecl *Parent = FD->getParent();
  8096. Invalid = Parent->isInvalidDecl();
  8097. if (Invalid || Parent->isUnion())
  8098. return true;
  8099. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  8100. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  8101. };
  8102. auto &Base = LVal.getLValueBase();
  8103. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  8104. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  8105. bool Invalid;
  8106. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8107. return Invalid;
  8108. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  8109. for (auto *FD : IFD->chain()) {
  8110. bool Invalid;
  8111. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  8112. return Invalid;
  8113. }
  8114. }
  8115. }
  8116. unsigned I = 0;
  8117. QualType BaseType = getType(Base);
  8118. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  8119. // If we don't know the array bound, conservatively assume we're looking at
  8120. // the final array element.
  8121. ++I;
  8122. if (BaseType->isIncompleteArrayType())
  8123. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  8124. else
  8125. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  8126. }
  8127. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  8128. const auto &Entry = LVal.Designator.Entries[I];
  8129. if (BaseType->isArrayType()) {
  8130. // Because __builtin_object_size treats arrays as objects, we can ignore
  8131. // the index iff this is the last array in the Designator.
  8132. if (I + 1 == E)
  8133. return true;
  8134. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  8135. uint64_t Index = Entry.getAsArrayIndex();
  8136. if (Index + 1 != CAT->getSize())
  8137. return false;
  8138. BaseType = CAT->getElementType();
  8139. } else if (BaseType->isAnyComplexType()) {
  8140. const auto *CT = BaseType->castAs<ComplexType>();
  8141. uint64_t Index = Entry.getAsArrayIndex();
  8142. if (Index != 1)
  8143. return false;
  8144. BaseType = CT->getElementType();
  8145. } else if (auto *FD = getAsField(Entry)) {
  8146. bool Invalid;
  8147. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8148. return Invalid;
  8149. BaseType = FD->getType();
  8150. } else {
  8151. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  8152. return false;
  8153. }
  8154. }
  8155. return true;
  8156. }
  8157. /// Tests to see if the LValue has a user-specified designator (that isn't
  8158. /// necessarily valid). Note that this always returns 'true' if the LValue has
  8159. /// an unsized array as its first designator entry, because there's currently no
  8160. /// way to tell if the user typed *foo or foo[0].
  8161. static bool refersToCompleteObject(const LValue &LVal) {
  8162. if (LVal.Designator.Invalid)
  8163. return false;
  8164. if (!LVal.Designator.Entries.empty())
  8165. return LVal.Designator.isMostDerivedAnUnsizedArray();
  8166. if (!LVal.InvalidBase)
  8167. return true;
  8168. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  8169. // the LValueBase.
  8170. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  8171. return !E || !isa<MemberExpr>(E);
  8172. }
  8173. /// Attempts to detect a user writing into a piece of memory that's impossible
  8174. /// to figure out the size of by just using types.
  8175. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  8176. const SubobjectDesignator &Designator = LVal.Designator;
  8177. // Notes:
  8178. // - Users can only write off of the end when we have an invalid base. Invalid
  8179. // bases imply we don't know where the memory came from.
  8180. // - We used to be a bit more aggressive here; we'd only be conservative if
  8181. // the array at the end was flexible, or if it had 0 or 1 elements. This
  8182. // broke some common standard library extensions (PR30346), but was
  8183. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  8184. // with some sort of whitelist. OTOH, it seems that GCC is always
  8185. // conservative with the last element in structs (if it's an array), so our
  8186. // current behavior is more compatible than a whitelisting approach would
  8187. // be.
  8188. return LVal.InvalidBase &&
  8189. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  8190. Designator.MostDerivedIsArrayElement &&
  8191. isDesignatorAtObjectEnd(Ctx, LVal);
  8192. }
  8193. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  8194. /// Fails if the conversion would cause loss of precision.
  8195. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  8196. CharUnits &Result) {
  8197. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  8198. if (Int.ugt(CharUnitsMax))
  8199. return false;
  8200. Result = CharUnits::fromQuantity(Int.getZExtValue());
  8201. return true;
  8202. }
  8203. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  8204. /// determine how many bytes exist from the beginning of the object to either
  8205. /// the end of the current subobject, or the end of the object itself, depending
  8206. /// on what the LValue looks like + the value of Type.
  8207. ///
  8208. /// If this returns false, the value of Result is undefined.
  8209. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  8210. unsigned Type, const LValue &LVal,
  8211. CharUnits &EndOffset) {
  8212. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  8213. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  8214. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  8215. return false;
  8216. return HandleSizeof(Info, ExprLoc, Ty, Result);
  8217. };
  8218. // We want to evaluate the size of the entire object. This is a valid fallback
  8219. // for when Type=1 and the designator is invalid, because we're asked for an
  8220. // upper-bound.
  8221. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  8222. // Type=3 wants a lower bound, so we can't fall back to this.
  8223. if (Type == 3 && !DetermineForCompleteObject)
  8224. return false;
  8225. llvm::APInt APEndOffset;
  8226. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8227. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8228. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8229. if (LVal.InvalidBase)
  8230. return false;
  8231. QualType BaseTy = getObjectType(LVal.getLValueBase());
  8232. return CheckedHandleSizeof(BaseTy, EndOffset);
  8233. }
  8234. // We want to evaluate the size of a subobject.
  8235. const SubobjectDesignator &Designator = LVal.Designator;
  8236. // The following is a moderately common idiom in C:
  8237. //
  8238. // struct Foo { int a; char c[1]; };
  8239. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  8240. // strcpy(&F->c[0], Bar);
  8241. //
  8242. // In order to not break too much legacy code, we need to support it.
  8243. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  8244. // If we can resolve this to an alloc_size call, we can hand that back,
  8245. // because we know for certain how many bytes there are to write to.
  8246. llvm::APInt APEndOffset;
  8247. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8248. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8249. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8250. // If we cannot determine the size of the initial allocation, then we can't
  8251. // given an accurate upper-bound. However, we are still able to give
  8252. // conservative lower-bounds for Type=3.
  8253. if (Type == 1)
  8254. return false;
  8255. }
  8256. CharUnits BytesPerElem;
  8257. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  8258. return false;
  8259. // According to the GCC documentation, we want the size of the subobject
  8260. // denoted by the pointer. But that's not quite right -- what we actually
  8261. // want is the size of the immediately-enclosing array, if there is one.
  8262. int64_t ElemsRemaining;
  8263. if (Designator.MostDerivedIsArrayElement &&
  8264. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  8265. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  8266. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  8267. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  8268. } else {
  8269. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  8270. }
  8271. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  8272. return true;
  8273. }
  8274. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  8275. /// returns true and stores the result in @p Size.
  8276. ///
  8277. /// If @p WasError is non-null, this will report whether the failure to evaluate
  8278. /// is to be treated as an Error in IntExprEvaluator.
  8279. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  8280. EvalInfo &Info, uint64_t &Size) {
  8281. // Determine the denoted object.
  8282. LValue LVal;
  8283. {
  8284. // The operand of __builtin_object_size is never evaluated for side-effects.
  8285. // If there are any, but we can determine the pointed-to object anyway, then
  8286. // ignore the side-effects.
  8287. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8288. IgnoreSideEffectsRAII Fold(Info);
  8289. if (E->isGLValue()) {
  8290. // It's possible for us to be given GLValues if we're called via
  8291. // Expr::tryEvaluateObjectSize.
  8292. APValue RVal;
  8293. if (!EvaluateAsRValue(Info, E, RVal))
  8294. return false;
  8295. LVal.setFrom(Info.Ctx, RVal);
  8296. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  8297. /*InvalidBaseOK=*/true))
  8298. return false;
  8299. }
  8300. // If we point to before the start of the object, there are no accessible
  8301. // bytes.
  8302. if (LVal.getLValueOffset().isNegative()) {
  8303. Size = 0;
  8304. return true;
  8305. }
  8306. CharUnits EndOffset;
  8307. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  8308. return false;
  8309. // If we've fallen outside of the end offset, just pretend there's nothing to
  8310. // write to/read from.
  8311. if (EndOffset <= LVal.getLValueOffset())
  8312. Size = 0;
  8313. else
  8314. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  8315. return true;
  8316. }
  8317. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  8318. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  8319. if (E->getResultAPValueKind() != APValue::None)
  8320. return Success(E->getAPValueResult(), E);
  8321. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  8322. }
  8323. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8324. if (unsigned BuiltinOp = E->getBuiltinCallee())
  8325. return VisitBuiltinCallExpr(E, BuiltinOp);
  8326. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8327. }
  8328. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  8329. unsigned BuiltinOp) {
  8330. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  8331. default:
  8332. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8333. case Builtin::BI__builtin_dynamic_object_size:
  8334. case Builtin::BI__builtin_object_size: {
  8335. // The type was checked when we built the expression.
  8336. unsigned Type =
  8337. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8338. assert(Type <= 3 && "unexpected type");
  8339. uint64_t Size;
  8340. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  8341. return Success(Size, E);
  8342. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  8343. return Success((Type & 2) ? 0 : -1, E);
  8344. // Expression had no side effects, but we couldn't statically determine the
  8345. // size of the referenced object.
  8346. switch (Info.EvalMode) {
  8347. case EvalInfo::EM_ConstantExpression:
  8348. case EvalInfo::EM_PotentialConstantExpression:
  8349. case EvalInfo::EM_ConstantFold:
  8350. case EvalInfo::EM_EvaluateForOverflow:
  8351. case EvalInfo::EM_IgnoreSideEffects:
  8352. // Leave it to IR generation.
  8353. return Error(E);
  8354. case EvalInfo::EM_ConstantExpressionUnevaluated:
  8355. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  8356. // Reduce it to a constant now.
  8357. return Success((Type & 2) ? 0 : -1, E);
  8358. }
  8359. llvm_unreachable("unexpected EvalMode");
  8360. }
  8361. case Builtin::BI__builtin_os_log_format_buffer_size: {
  8362. analyze_os_log::OSLogBufferLayout Layout;
  8363. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  8364. return Success(Layout.size().getQuantity(), E);
  8365. }
  8366. case Builtin::BI__builtin_bswap16:
  8367. case Builtin::BI__builtin_bswap32:
  8368. case Builtin::BI__builtin_bswap64: {
  8369. APSInt Val;
  8370. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8371. return false;
  8372. return Success(Val.byteSwap(), E);
  8373. }
  8374. case Builtin::BI__builtin_classify_type:
  8375. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  8376. case Builtin::BI__builtin_clrsb:
  8377. case Builtin::BI__builtin_clrsbl:
  8378. case Builtin::BI__builtin_clrsbll: {
  8379. APSInt Val;
  8380. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8381. return false;
  8382. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  8383. }
  8384. case Builtin::BI__builtin_clz:
  8385. case Builtin::BI__builtin_clzl:
  8386. case Builtin::BI__builtin_clzll:
  8387. case Builtin::BI__builtin_clzs: {
  8388. APSInt Val;
  8389. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8390. return false;
  8391. if (!Val)
  8392. return Error(E);
  8393. return Success(Val.countLeadingZeros(), E);
  8394. }
  8395. case Builtin::BI__builtin_constant_p: {
  8396. const Expr *Arg = E->getArg(0);
  8397. if (EvaluateBuiltinConstantP(Info, Arg))
  8398. return Success(true, E);
  8399. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  8400. // Outside a constant context, eagerly evaluate to false in the presence
  8401. // of side-effects in order to avoid -Wunsequenced false-positives in
  8402. // a branch on __builtin_constant_p(expr).
  8403. return Success(false, E);
  8404. }
  8405. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8406. return false;
  8407. }
  8408. case Builtin::BI__builtin_is_constant_evaluated:
  8409. return Success(Info.InConstantContext, E);
  8410. case Builtin::BI__builtin_ctz:
  8411. case Builtin::BI__builtin_ctzl:
  8412. case Builtin::BI__builtin_ctzll:
  8413. case Builtin::BI__builtin_ctzs: {
  8414. APSInt Val;
  8415. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8416. return false;
  8417. if (!Val)
  8418. return Error(E);
  8419. return Success(Val.countTrailingZeros(), E);
  8420. }
  8421. case Builtin::BI__builtin_eh_return_data_regno: {
  8422. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8423. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  8424. return Success(Operand, E);
  8425. }
  8426. case Builtin::BI__builtin_expect:
  8427. return Visit(E->getArg(0));
  8428. case Builtin::BI__builtin_ffs:
  8429. case Builtin::BI__builtin_ffsl:
  8430. case Builtin::BI__builtin_ffsll: {
  8431. APSInt Val;
  8432. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8433. return false;
  8434. unsigned N = Val.countTrailingZeros();
  8435. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  8436. }
  8437. case Builtin::BI__builtin_fpclassify: {
  8438. APFloat Val(0.0);
  8439. if (!EvaluateFloat(E->getArg(5), Val, Info))
  8440. return false;
  8441. unsigned Arg;
  8442. switch (Val.getCategory()) {
  8443. case APFloat::fcNaN: Arg = 0; break;
  8444. case APFloat::fcInfinity: Arg = 1; break;
  8445. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  8446. case APFloat::fcZero: Arg = 4; break;
  8447. }
  8448. return Visit(E->getArg(Arg));
  8449. }
  8450. case Builtin::BI__builtin_isinf_sign: {
  8451. APFloat Val(0.0);
  8452. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8453. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  8454. }
  8455. case Builtin::BI__builtin_isinf: {
  8456. APFloat Val(0.0);
  8457. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8458. Success(Val.isInfinity() ? 1 : 0, E);
  8459. }
  8460. case Builtin::BI__builtin_isfinite: {
  8461. APFloat Val(0.0);
  8462. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8463. Success(Val.isFinite() ? 1 : 0, E);
  8464. }
  8465. case Builtin::BI__builtin_isnan: {
  8466. APFloat Val(0.0);
  8467. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8468. Success(Val.isNaN() ? 1 : 0, E);
  8469. }
  8470. case Builtin::BI__builtin_isnormal: {
  8471. APFloat Val(0.0);
  8472. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8473. Success(Val.isNormal() ? 1 : 0, E);
  8474. }
  8475. case Builtin::BI__builtin_parity:
  8476. case Builtin::BI__builtin_parityl:
  8477. case Builtin::BI__builtin_parityll: {
  8478. APSInt Val;
  8479. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8480. return false;
  8481. return Success(Val.countPopulation() % 2, E);
  8482. }
  8483. case Builtin::BI__builtin_popcount:
  8484. case Builtin::BI__builtin_popcountl:
  8485. case Builtin::BI__builtin_popcountll: {
  8486. APSInt Val;
  8487. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8488. return false;
  8489. return Success(Val.countPopulation(), E);
  8490. }
  8491. case Builtin::BIstrlen:
  8492. case Builtin::BIwcslen:
  8493. // A call to strlen is not a constant expression.
  8494. if (Info.getLangOpts().CPlusPlus11)
  8495. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8496. << /*isConstexpr*/0 << /*isConstructor*/0
  8497. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8498. else
  8499. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8500. LLVM_FALLTHROUGH;
  8501. case Builtin::BI__builtin_strlen:
  8502. case Builtin::BI__builtin_wcslen: {
  8503. // As an extension, we support __builtin_strlen() as a constant expression,
  8504. // and support folding strlen() to a constant.
  8505. LValue String;
  8506. if (!EvaluatePointer(E->getArg(0), String, Info))
  8507. return false;
  8508. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  8509. // Fast path: if it's a string literal, search the string value.
  8510. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  8511. String.getLValueBase().dyn_cast<const Expr *>())) {
  8512. // The string literal may have embedded null characters. Find the first
  8513. // one and truncate there.
  8514. StringRef Str = S->getBytes();
  8515. int64_t Off = String.Offset.getQuantity();
  8516. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  8517. S->getCharByteWidth() == 1 &&
  8518. // FIXME: Add fast-path for wchar_t too.
  8519. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  8520. Str = Str.substr(Off);
  8521. StringRef::size_type Pos = Str.find(0);
  8522. if (Pos != StringRef::npos)
  8523. Str = Str.substr(0, Pos);
  8524. return Success(Str.size(), E);
  8525. }
  8526. // Fall through to slow path to issue appropriate diagnostic.
  8527. }
  8528. // Slow path: scan the bytes of the string looking for the terminating 0.
  8529. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  8530. APValue Char;
  8531. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  8532. !Char.isInt())
  8533. return false;
  8534. if (!Char.getInt())
  8535. return Success(Strlen, E);
  8536. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  8537. return false;
  8538. }
  8539. }
  8540. case Builtin::BIstrcmp:
  8541. case Builtin::BIwcscmp:
  8542. case Builtin::BIstrncmp:
  8543. case Builtin::BIwcsncmp:
  8544. case Builtin::BImemcmp:
  8545. case Builtin::BIbcmp:
  8546. case Builtin::BIwmemcmp:
  8547. // A call to strlen is not a constant expression.
  8548. if (Info.getLangOpts().CPlusPlus11)
  8549. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8550. << /*isConstexpr*/0 << /*isConstructor*/0
  8551. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8552. else
  8553. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8554. LLVM_FALLTHROUGH;
  8555. case Builtin::BI__builtin_strcmp:
  8556. case Builtin::BI__builtin_wcscmp:
  8557. case Builtin::BI__builtin_strncmp:
  8558. case Builtin::BI__builtin_wcsncmp:
  8559. case Builtin::BI__builtin_memcmp:
  8560. case Builtin::BI__builtin_bcmp:
  8561. case Builtin::BI__builtin_wmemcmp: {
  8562. LValue String1, String2;
  8563. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  8564. !EvaluatePointer(E->getArg(1), String2, Info))
  8565. return false;
  8566. uint64_t MaxLength = uint64_t(-1);
  8567. if (BuiltinOp != Builtin::BIstrcmp &&
  8568. BuiltinOp != Builtin::BIwcscmp &&
  8569. BuiltinOp != Builtin::BI__builtin_strcmp &&
  8570. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  8571. APSInt N;
  8572. if (!EvaluateInteger(E->getArg(2), N, Info))
  8573. return false;
  8574. MaxLength = N.getExtValue();
  8575. }
  8576. // Empty substrings compare equal by definition.
  8577. if (MaxLength == 0u)
  8578. return Success(0, E);
  8579. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8580. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8581. String1.Designator.Invalid || String2.Designator.Invalid)
  8582. return false;
  8583. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  8584. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  8585. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  8586. BuiltinOp == Builtin::BIbcmp ||
  8587. BuiltinOp == Builtin::BI__builtin_memcmp ||
  8588. BuiltinOp == Builtin::BI__builtin_bcmp;
  8589. assert(IsRawByte ||
  8590. (Info.Ctx.hasSameUnqualifiedType(
  8591. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  8592. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  8593. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  8594. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  8595. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  8596. Char1.isInt() && Char2.isInt();
  8597. };
  8598. const auto &AdvanceElems = [&] {
  8599. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  8600. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  8601. };
  8602. if (IsRawByte) {
  8603. uint64_t BytesRemaining = MaxLength;
  8604. // Pointers to const void may point to objects of incomplete type.
  8605. if (CharTy1->isIncompleteType()) {
  8606. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  8607. return false;
  8608. }
  8609. if (CharTy2->isIncompleteType()) {
  8610. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  8611. return false;
  8612. }
  8613. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  8614. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  8615. // Give up on comparing between elements with disparate widths.
  8616. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  8617. return false;
  8618. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  8619. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  8620. "following loop considers at least one element");
  8621. while (true) {
  8622. APValue Char1, Char2;
  8623. if (!ReadCurElems(Char1, Char2))
  8624. return false;
  8625. // We have compatible in-memory widths, but a possible type and
  8626. // (for `bool`) internal representation mismatch.
  8627. // Assuming two's complement representation, including 0 for `false` and
  8628. // 1 for `true`, we can check an appropriate number of elements for
  8629. // equality even if they are not byte-sized.
  8630. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  8631. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  8632. if (Char1InMem.ne(Char2InMem)) {
  8633. // If the elements are byte-sized, then we can produce a three-way
  8634. // comparison result in a straightforward manner.
  8635. if (BytesPerElement == 1u) {
  8636. // memcmp always compares unsigned chars.
  8637. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  8638. }
  8639. // The result is byte-order sensitive, and we have multibyte elements.
  8640. // FIXME: We can compare the remaining bytes in the correct order.
  8641. return false;
  8642. }
  8643. if (!AdvanceElems())
  8644. return false;
  8645. if (BytesRemaining <= BytesPerElement)
  8646. break;
  8647. BytesRemaining -= BytesPerElement;
  8648. }
  8649. // Enough elements are equal to account for the memcmp limit.
  8650. return Success(0, E);
  8651. }
  8652. bool StopAtNull =
  8653. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  8654. BuiltinOp != Builtin::BIwmemcmp &&
  8655. BuiltinOp != Builtin::BI__builtin_memcmp &&
  8656. BuiltinOp != Builtin::BI__builtin_bcmp &&
  8657. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  8658. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  8659. BuiltinOp == Builtin::BIwcsncmp ||
  8660. BuiltinOp == Builtin::BIwmemcmp ||
  8661. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  8662. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  8663. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  8664. for (; MaxLength; --MaxLength) {
  8665. APValue Char1, Char2;
  8666. if (!ReadCurElems(Char1, Char2))
  8667. return false;
  8668. if (Char1.getInt() != Char2.getInt()) {
  8669. if (IsWide) // wmemcmp compares with wchar_t signedness.
  8670. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  8671. // memcmp always compares unsigned chars.
  8672. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  8673. }
  8674. if (StopAtNull && !Char1.getInt())
  8675. return Success(0, E);
  8676. assert(!(StopAtNull && !Char2.getInt()));
  8677. if (!AdvanceElems())
  8678. return false;
  8679. }
  8680. // We hit the strncmp / memcmp limit.
  8681. return Success(0, E);
  8682. }
  8683. case Builtin::BI__atomic_always_lock_free:
  8684. case Builtin::BI__atomic_is_lock_free:
  8685. case Builtin::BI__c11_atomic_is_lock_free: {
  8686. APSInt SizeVal;
  8687. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  8688. return false;
  8689. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  8690. // of two less than the maximum inline atomic width, we know it is
  8691. // lock-free. If the size isn't a power of two, or greater than the
  8692. // maximum alignment where we promote atomics, we know it is not lock-free
  8693. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  8694. // the answer can only be determined at runtime; for example, 16-byte
  8695. // atomics have lock-free implementations on some, but not all,
  8696. // x86-64 processors.
  8697. // Check power-of-two.
  8698. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  8699. if (Size.isPowerOfTwo()) {
  8700. // Check against inlining width.
  8701. unsigned InlineWidthBits =
  8702. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  8703. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  8704. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  8705. Size == CharUnits::One() ||
  8706. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  8707. Expr::NPC_NeverValueDependent))
  8708. // OK, we will inline appropriately-aligned operations of this size,
  8709. // and _Atomic(T) is appropriately-aligned.
  8710. return Success(1, E);
  8711. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  8712. castAs<PointerType>()->getPointeeType();
  8713. if (!PointeeType->isIncompleteType() &&
  8714. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  8715. // OK, we will inline operations on this object.
  8716. return Success(1, E);
  8717. }
  8718. }
  8719. }
  8720. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  8721. Success(0, E) : Error(E);
  8722. }
  8723. case Builtin::BIomp_is_initial_device:
  8724. // We can decide statically which value the runtime would return if called.
  8725. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  8726. case Builtin::BI__builtin_add_overflow:
  8727. case Builtin::BI__builtin_sub_overflow:
  8728. case Builtin::BI__builtin_mul_overflow:
  8729. case Builtin::BI__builtin_sadd_overflow:
  8730. case Builtin::BI__builtin_uadd_overflow:
  8731. case Builtin::BI__builtin_uaddl_overflow:
  8732. case Builtin::BI__builtin_uaddll_overflow:
  8733. case Builtin::BI__builtin_usub_overflow:
  8734. case Builtin::BI__builtin_usubl_overflow:
  8735. case Builtin::BI__builtin_usubll_overflow:
  8736. case Builtin::BI__builtin_umul_overflow:
  8737. case Builtin::BI__builtin_umull_overflow:
  8738. case Builtin::BI__builtin_umulll_overflow:
  8739. case Builtin::BI__builtin_saddl_overflow:
  8740. case Builtin::BI__builtin_saddll_overflow:
  8741. case Builtin::BI__builtin_ssub_overflow:
  8742. case Builtin::BI__builtin_ssubl_overflow:
  8743. case Builtin::BI__builtin_ssubll_overflow:
  8744. case Builtin::BI__builtin_smul_overflow:
  8745. case Builtin::BI__builtin_smull_overflow:
  8746. case Builtin::BI__builtin_smulll_overflow: {
  8747. LValue ResultLValue;
  8748. APSInt LHS, RHS;
  8749. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  8750. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  8751. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  8752. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  8753. return false;
  8754. APSInt Result;
  8755. bool DidOverflow = false;
  8756. // If the types don't have to match, enlarge all 3 to the largest of them.
  8757. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8758. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8759. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8760. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  8761. ResultType->isSignedIntegerOrEnumerationType();
  8762. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  8763. ResultType->isSignedIntegerOrEnumerationType();
  8764. uint64_t LHSSize = LHS.getBitWidth();
  8765. uint64_t RHSSize = RHS.getBitWidth();
  8766. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  8767. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  8768. // Add an additional bit if the signedness isn't uniformly agreed to. We
  8769. // could do this ONLY if there is a signed and an unsigned that both have
  8770. // MaxBits, but the code to check that is pretty nasty. The issue will be
  8771. // caught in the shrink-to-result later anyway.
  8772. if (IsSigned && !AllSigned)
  8773. ++MaxBits;
  8774. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  8775. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  8776. Result = APSInt(MaxBits, !IsSigned);
  8777. }
  8778. // Find largest int.
  8779. switch (BuiltinOp) {
  8780. default:
  8781. llvm_unreachable("Invalid value for BuiltinOp");
  8782. case Builtin::BI__builtin_add_overflow:
  8783. case Builtin::BI__builtin_sadd_overflow:
  8784. case Builtin::BI__builtin_saddl_overflow:
  8785. case Builtin::BI__builtin_saddll_overflow:
  8786. case Builtin::BI__builtin_uadd_overflow:
  8787. case Builtin::BI__builtin_uaddl_overflow:
  8788. case Builtin::BI__builtin_uaddll_overflow:
  8789. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  8790. : LHS.uadd_ov(RHS, DidOverflow);
  8791. break;
  8792. case Builtin::BI__builtin_sub_overflow:
  8793. case Builtin::BI__builtin_ssub_overflow:
  8794. case Builtin::BI__builtin_ssubl_overflow:
  8795. case Builtin::BI__builtin_ssubll_overflow:
  8796. case Builtin::BI__builtin_usub_overflow:
  8797. case Builtin::BI__builtin_usubl_overflow:
  8798. case Builtin::BI__builtin_usubll_overflow:
  8799. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  8800. : LHS.usub_ov(RHS, DidOverflow);
  8801. break;
  8802. case Builtin::BI__builtin_mul_overflow:
  8803. case Builtin::BI__builtin_smul_overflow:
  8804. case Builtin::BI__builtin_smull_overflow:
  8805. case Builtin::BI__builtin_smulll_overflow:
  8806. case Builtin::BI__builtin_umul_overflow:
  8807. case Builtin::BI__builtin_umull_overflow:
  8808. case Builtin::BI__builtin_umulll_overflow:
  8809. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  8810. : LHS.umul_ov(RHS, DidOverflow);
  8811. break;
  8812. }
  8813. // In the case where multiple sizes are allowed, truncate and see if
  8814. // the values are the same.
  8815. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8816. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8817. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8818. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  8819. // since it will give us the behavior of a TruncOrSelf in the case where
  8820. // its parameter <= its size. We previously set Result to be at least the
  8821. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  8822. // will work exactly like TruncOrSelf.
  8823. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  8824. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  8825. if (!APSInt::isSameValue(Temp, Result))
  8826. DidOverflow = true;
  8827. Result = Temp;
  8828. }
  8829. APValue APV{Result};
  8830. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  8831. return false;
  8832. return Success(DidOverflow, E);
  8833. }
  8834. }
  8835. }
  8836. /// Determine whether this is a pointer past the end of the complete
  8837. /// object referred to by the lvalue.
  8838. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  8839. const LValue &LV) {
  8840. // A null pointer can be viewed as being "past the end" but we don't
  8841. // choose to look at it that way here.
  8842. if (!LV.getLValueBase())
  8843. return false;
  8844. // If the designator is valid and refers to a subobject, we're not pointing
  8845. // past the end.
  8846. if (!LV.getLValueDesignator().Invalid &&
  8847. !LV.getLValueDesignator().isOnePastTheEnd())
  8848. return false;
  8849. // A pointer to an incomplete type might be past-the-end if the type's size is
  8850. // zero. We cannot tell because the type is incomplete.
  8851. QualType Ty = getType(LV.getLValueBase());
  8852. if (Ty->isIncompleteType())
  8853. return true;
  8854. // We're a past-the-end pointer if we point to the byte after the object,
  8855. // no matter what our type or path is.
  8856. auto Size = Ctx.getTypeSizeInChars(Ty);
  8857. return LV.getLValueOffset() == Size;
  8858. }
  8859. namespace {
  8860. /// Data recursive integer evaluator of certain binary operators.
  8861. ///
  8862. /// We use a data recursive algorithm for binary operators so that we are able
  8863. /// to handle extreme cases of chained binary operators without causing stack
  8864. /// overflow.
  8865. class DataRecursiveIntBinOpEvaluator {
  8866. struct EvalResult {
  8867. APValue Val;
  8868. bool Failed;
  8869. EvalResult() : Failed(false) { }
  8870. void swap(EvalResult &RHS) {
  8871. Val.swap(RHS.Val);
  8872. Failed = RHS.Failed;
  8873. RHS.Failed = false;
  8874. }
  8875. };
  8876. struct Job {
  8877. const Expr *E;
  8878. EvalResult LHSResult; // meaningful only for binary operator expression.
  8879. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  8880. Job() = default;
  8881. Job(Job &&) = default;
  8882. void startSpeculativeEval(EvalInfo &Info) {
  8883. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  8884. }
  8885. private:
  8886. SpeculativeEvaluationRAII SpecEvalRAII;
  8887. };
  8888. SmallVector<Job, 16> Queue;
  8889. IntExprEvaluator &IntEval;
  8890. EvalInfo &Info;
  8891. APValue &FinalResult;
  8892. public:
  8893. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  8894. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  8895. /// True if \param E is a binary operator that we are going to handle
  8896. /// data recursively.
  8897. /// We handle binary operators that are comma, logical, or that have operands
  8898. /// with integral or enumeration type.
  8899. static bool shouldEnqueue(const BinaryOperator *E) {
  8900. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  8901. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  8902. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8903. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8904. }
  8905. bool Traverse(const BinaryOperator *E) {
  8906. enqueue(E);
  8907. EvalResult PrevResult;
  8908. while (!Queue.empty())
  8909. process(PrevResult);
  8910. if (PrevResult.Failed) return false;
  8911. FinalResult.swap(PrevResult.Val);
  8912. return true;
  8913. }
  8914. private:
  8915. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8916. return IntEval.Success(Value, E, Result);
  8917. }
  8918. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  8919. return IntEval.Success(Value, E, Result);
  8920. }
  8921. bool Error(const Expr *E) {
  8922. return IntEval.Error(E);
  8923. }
  8924. bool Error(const Expr *E, diag::kind D) {
  8925. return IntEval.Error(E, D);
  8926. }
  8927. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  8928. return Info.CCEDiag(E, D);
  8929. }
  8930. // Returns true if visiting the RHS is necessary, false otherwise.
  8931. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8932. bool &SuppressRHSDiags);
  8933. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8934. const BinaryOperator *E, APValue &Result);
  8935. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  8936. Result.Failed = !Evaluate(Result.Val, Info, E);
  8937. if (Result.Failed)
  8938. Result.Val = APValue();
  8939. }
  8940. void process(EvalResult &Result);
  8941. void enqueue(const Expr *E) {
  8942. E = E->IgnoreParens();
  8943. Queue.resize(Queue.size()+1);
  8944. Queue.back().E = E;
  8945. Queue.back().Kind = Job::AnyExprKind;
  8946. }
  8947. };
  8948. }
  8949. bool DataRecursiveIntBinOpEvaluator::
  8950. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8951. bool &SuppressRHSDiags) {
  8952. if (E->getOpcode() == BO_Comma) {
  8953. // Ignore LHS but note if we could not evaluate it.
  8954. if (LHSResult.Failed)
  8955. return Info.noteSideEffect();
  8956. return true;
  8957. }
  8958. if (E->isLogicalOp()) {
  8959. bool LHSAsBool;
  8960. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  8961. // We were able to evaluate the LHS, see if we can get away with not
  8962. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  8963. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  8964. Success(LHSAsBool, E, LHSResult.Val);
  8965. return false; // Ignore RHS
  8966. }
  8967. } else {
  8968. LHSResult.Failed = true;
  8969. // Since we weren't able to evaluate the left hand side, it
  8970. // might have had side effects.
  8971. if (!Info.noteSideEffect())
  8972. return false;
  8973. // We can't evaluate the LHS; however, sometimes the result
  8974. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8975. // Don't ignore RHS and suppress diagnostics from this arm.
  8976. SuppressRHSDiags = true;
  8977. }
  8978. return true;
  8979. }
  8980. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8981. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8982. if (LHSResult.Failed && !Info.noteFailure())
  8983. return false; // Ignore RHS;
  8984. return true;
  8985. }
  8986. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  8987. bool IsSub) {
  8988. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  8989. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  8990. // offsets.
  8991. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  8992. CharUnits &Offset = LVal.getLValueOffset();
  8993. uint64_t Offset64 = Offset.getQuantity();
  8994. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  8995. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  8996. : Offset64 + Index64);
  8997. }
  8998. bool DataRecursiveIntBinOpEvaluator::
  8999. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9000. const BinaryOperator *E, APValue &Result) {
  9001. if (E->getOpcode() == BO_Comma) {
  9002. if (RHSResult.Failed)
  9003. return false;
  9004. Result = RHSResult.Val;
  9005. return true;
  9006. }
  9007. if (E->isLogicalOp()) {
  9008. bool lhsResult, rhsResult;
  9009. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  9010. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  9011. if (LHSIsOK) {
  9012. if (RHSIsOK) {
  9013. if (E->getOpcode() == BO_LOr)
  9014. return Success(lhsResult || rhsResult, E, Result);
  9015. else
  9016. return Success(lhsResult && rhsResult, E, Result);
  9017. }
  9018. } else {
  9019. if (RHSIsOK) {
  9020. // We can't evaluate the LHS; however, sometimes the result
  9021. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9022. if (rhsResult == (E->getOpcode() == BO_LOr))
  9023. return Success(rhsResult, E, Result);
  9024. }
  9025. }
  9026. return false;
  9027. }
  9028. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9029. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9030. if (LHSResult.Failed || RHSResult.Failed)
  9031. return false;
  9032. const APValue &LHSVal = LHSResult.Val;
  9033. const APValue &RHSVal = RHSResult.Val;
  9034. // Handle cases like (unsigned long)&a + 4.
  9035. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  9036. Result = LHSVal;
  9037. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  9038. return true;
  9039. }
  9040. // Handle cases like 4 + (unsigned long)&a
  9041. if (E->getOpcode() == BO_Add &&
  9042. RHSVal.isLValue() && LHSVal.isInt()) {
  9043. Result = RHSVal;
  9044. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  9045. return true;
  9046. }
  9047. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  9048. // Handle (intptr_t)&&A - (intptr_t)&&B.
  9049. if (!LHSVal.getLValueOffset().isZero() ||
  9050. !RHSVal.getLValueOffset().isZero())
  9051. return false;
  9052. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  9053. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  9054. if (!LHSExpr || !RHSExpr)
  9055. return false;
  9056. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9057. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9058. if (!LHSAddrExpr || !RHSAddrExpr)
  9059. return false;
  9060. // Make sure both labels come from the same function.
  9061. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9062. RHSAddrExpr->getLabel()->getDeclContext())
  9063. return false;
  9064. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  9065. return true;
  9066. }
  9067. // All the remaining cases expect both operands to be an integer
  9068. if (!LHSVal.isInt() || !RHSVal.isInt())
  9069. return Error(E);
  9070. // Set up the width and signedness manually, in case it can't be deduced
  9071. // from the operation we're performing.
  9072. // FIXME: Don't do this in the cases where we can deduce it.
  9073. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  9074. E->getType()->isUnsignedIntegerOrEnumerationType());
  9075. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  9076. RHSVal.getInt(), Value))
  9077. return false;
  9078. return Success(Value, E, Result);
  9079. }
  9080. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  9081. Job &job = Queue.back();
  9082. switch (job.Kind) {
  9083. case Job::AnyExprKind: {
  9084. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  9085. if (shouldEnqueue(Bop)) {
  9086. job.Kind = Job::BinOpKind;
  9087. enqueue(Bop->getLHS());
  9088. return;
  9089. }
  9090. }
  9091. EvaluateExpr(job.E, Result);
  9092. Queue.pop_back();
  9093. return;
  9094. }
  9095. case Job::BinOpKind: {
  9096. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9097. bool SuppressRHSDiags = false;
  9098. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  9099. Queue.pop_back();
  9100. return;
  9101. }
  9102. if (SuppressRHSDiags)
  9103. job.startSpeculativeEval(Info);
  9104. job.LHSResult.swap(Result);
  9105. job.Kind = Job::BinOpVisitedLHSKind;
  9106. enqueue(Bop->getRHS());
  9107. return;
  9108. }
  9109. case Job::BinOpVisitedLHSKind: {
  9110. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9111. EvalResult RHS;
  9112. RHS.swap(Result);
  9113. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  9114. Queue.pop_back();
  9115. return;
  9116. }
  9117. }
  9118. llvm_unreachable("Invalid Job::Kind!");
  9119. }
  9120. namespace {
  9121. /// Used when we determine that we should fail, but can keep evaluating prior to
  9122. /// noting that we had a failure.
  9123. class DelayedNoteFailureRAII {
  9124. EvalInfo &Info;
  9125. bool NoteFailure;
  9126. public:
  9127. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  9128. : Info(Info), NoteFailure(NoteFailure) {}
  9129. ~DelayedNoteFailureRAII() {
  9130. if (NoteFailure) {
  9131. bool ContinueAfterFailure = Info.noteFailure();
  9132. (void)ContinueAfterFailure;
  9133. assert(ContinueAfterFailure &&
  9134. "Shouldn't have kept evaluating on failure.");
  9135. }
  9136. }
  9137. };
  9138. }
  9139. template <class SuccessCB, class AfterCB>
  9140. static bool
  9141. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  9142. SuccessCB &&Success, AfterCB &&DoAfter) {
  9143. assert(E->isComparisonOp() && "expected comparison operator");
  9144. assert((E->getOpcode() == BO_Cmp ||
  9145. E->getType()->isIntegralOrEnumerationType()) &&
  9146. "unsupported binary expression evaluation");
  9147. auto Error = [&](const Expr *E) {
  9148. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9149. return false;
  9150. };
  9151. using CCR = ComparisonCategoryResult;
  9152. bool IsRelational = E->isRelationalOp();
  9153. bool IsEquality = E->isEqualityOp();
  9154. if (E->getOpcode() == BO_Cmp) {
  9155. const ComparisonCategoryInfo &CmpInfo =
  9156. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9157. IsRelational = CmpInfo.isOrdered();
  9158. IsEquality = CmpInfo.isEquality();
  9159. }
  9160. QualType LHSTy = E->getLHS()->getType();
  9161. QualType RHSTy = E->getRHS()->getType();
  9162. if (LHSTy->isIntegralOrEnumerationType() &&
  9163. RHSTy->isIntegralOrEnumerationType()) {
  9164. APSInt LHS, RHS;
  9165. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  9166. if (!LHSOK && !Info.noteFailure())
  9167. return false;
  9168. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  9169. return false;
  9170. if (LHS < RHS)
  9171. return Success(CCR::Less, E);
  9172. if (LHS > RHS)
  9173. return Success(CCR::Greater, E);
  9174. return Success(CCR::Equal, E);
  9175. }
  9176. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  9177. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  9178. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  9179. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  9180. if (!LHSOK && !Info.noteFailure())
  9181. return false;
  9182. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  9183. return false;
  9184. if (LHSFX < RHSFX)
  9185. return Success(CCR::Less, E);
  9186. if (LHSFX > RHSFX)
  9187. return Success(CCR::Greater, E);
  9188. return Success(CCR::Equal, E);
  9189. }
  9190. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  9191. ComplexValue LHS, RHS;
  9192. bool LHSOK;
  9193. if (E->isAssignmentOp()) {
  9194. LValue LV;
  9195. EvaluateLValue(E->getLHS(), LV, Info);
  9196. LHSOK = false;
  9197. } else if (LHSTy->isRealFloatingType()) {
  9198. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  9199. if (LHSOK) {
  9200. LHS.makeComplexFloat();
  9201. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  9202. }
  9203. } else {
  9204. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  9205. }
  9206. if (!LHSOK && !Info.noteFailure())
  9207. return false;
  9208. if (E->getRHS()->getType()->isRealFloatingType()) {
  9209. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  9210. return false;
  9211. RHS.makeComplexFloat();
  9212. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  9213. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9214. return false;
  9215. if (LHS.isComplexFloat()) {
  9216. APFloat::cmpResult CR_r =
  9217. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  9218. APFloat::cmpResult CR_i =
  9219. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  9220. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  9221. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9222. } else {
  9223. assert(IsEquality && "invalid complex comparison");
  9224. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  9225. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  9226. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9227. }
  9228. }
  9229. if (LHSTy->isRealFloatingType() &&
  9230. RHSTy->isRealFloatingType()) {
  9231. APFloat RHS(0.0), LHS(0.0);
  9232. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  9233. if (!LHSOK && !Info.noteFailure())
  9234. return false;
  9235. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  9236. return false;
  9237. assert(E->isComparisonOp() && "Invalid binary operator!");
  9238. auto GetCmpRes = [&]() {
  9239. switch (LHS.compare(RHS)) {
  9240. case APFloat::cmpEqual:
  9241. return CCR::Equal;
  9242. case APFloat::cmpLessThan:
  9243. return CCR::Less;
  9244. case APFloat::cmpGreaterThan:
  9245. return CCR::Greater;
  9246. case APFloat::cmpUnordered:
  9247. return CCR::Unordered;
  9248. }
  9249. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  9250. };
  9251. return Success(GetCmpRes(), E);
  9252. }
  9253. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  9254. LValue LHSValue, RHSValue;
  9255. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9256. if (!LHSOK && !Info.noteFailure())
  9257. return false;
  9258. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9259. return false;
  9260. // Reject differing bases from the normal codepath; we special-case
  9261. // comparisons to null.
  9262. if (!HasSameBase(LHSValue, RHSValue)) {
  9263. // Inequalities and subtractions between unrelated pointers have
  9264. // unspecified or undefined behavior.
  9265. if (!IsEquality)
  9266. return Error(E);
  9267. // A constant address may compare equal to the address of a symbol.
  9268. // The one exception is that address of an object cannot compare equal
  9269. // to a null pointer constant.
  9270. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  9271. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  9272. return Error(E);
  9273. // It's implementation-defined whether distinct literals will have
  9274. // distinct addresses. In clang, the result of such a comparison is
  9275. // unspecified, so it is not a constant expression. However, we do know
  9276. // that the address of a literal will be non-null.
  9277. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  9278. LHSValue.Base && RHSValue.Base)
  9279. return Error(E);
  9280. // We can't tell whether weak symbols will end up pointing to the same
  9281. // object.
  9282. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  9283. return Error(E);
  9284. // We can't compare the address of the start of one object with the
  9285. // past-the-end address of another object, per C++ DR1652.
  9286. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  9287. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  9288. (RHSValue.Base && RHSValue.Offset.isZero() &&
  9289. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  9290. return Error(E);
  9291. // We can't tell whether an object is at the same address as another
  9292. // zero sized object.
  9293. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  9294. (LHSValue.Base && isZeroSized(RHSValue)))
  9295. return Error(E);
  9296. return Success(CCR::Nonequal, E);
  9297. }
  9298. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9299. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9300. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9301. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9302. // C++11 [expr.rel]p3:
  9303. // Pointers to void (after pointer conversions) can be compared, with a
  9304. // result defined as follows: If both pointers represent the same
  9305. // address or are both the null pointer value, the result is true if the
  9306. // operator is <= or >= and false otherwise; otherwise the result is
  9307. // unspecified.
  9308. // We interpret this as applying to pointers to *cv* void.
  9309. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  9310. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  9311. // C++11 [expr.rel]p2:
  9312. // - If two pointers point to non-static data members of the same object,
  9313. // or to subobjects or array elements fo such members, recursively, the
  9314. // pointer to the later declared member compares greater provided the
  9315. // two members have the same access control and provided their class is
  9316. // not a union.
  9317. // [...]
  9318. // - Otherwise pointer comparisons are unspecified.
  9319. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  9320. bool WasArrayIndex;
  9321. unsigned Mismatch = FindDesignatorMismatch(
  9322. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  9323. // At the point where the designators diverge, the comparison has a
  9324. // specified value if:
  9325. // - we are comparing array indices
  9326. // - we are comparing fields of a union, or fields with the same access
  9327. // Otherwise, the result is unspecified and thus the comparison is not a
  9328. // constant expression.
  9329. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  9330. Mismatch < RHSDesignator.Entries.size()) {
  9331. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  9332. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  9333. if (!LF && !RF)
  9334. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  9335. else if (!LF)
  9336. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9337. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  9338. << RF->getParent() << RF;
  9339. else if (!RF)
  9340. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9341. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  9342. << LF->getParent() << LF;
  9343. else if (!LF->getParent()->isUnion() &&
  9344. LF->getAccess() != RF->getAccess())
  9345. Info.CCEDiag(E,
  9346. diag::note_constexpr_pointer_comparison_differing_access)
  9347. << LF << LF->getAccess() << RF << RF->getAccess()
  9348. << LF->getParent();
  9349. }
  9350. }
  9351. // The comparison here must be unsigned, and performed with the same
  9352. // width as the pointer.
  9353. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  9354. uint64_t CompareLHS = LHSOffset.getQuantity();
  9355. uint64_t CompareRHS = RHSOffset.getQuantity();
  9356. assert(PtrSize <= 64 && "Unexpected pointer width");
  9357. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  9358. CompareLHS &= Mask;
  9359. CompareRHS &= Mask;
  9360. // If there is a base and this is a relational operator, we can only
  9361. // compare pointers within the object in question; otherwise, the result
  9362. // depends on where the object is located in memory.
  9363. if (!LHSValue.Base.isNull() && IsRelational) {
  9364. QualType BaseTy = getType(LHSValue.Base);
  9365. if (BaseTy->isIncompleteType())
  9366. return Error(E);
  9367. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  9368. uint64_t OffsetLimit = Size.getQuantity();
  9369. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  9370. return Error(E);
  9371. }
  9372. if (CompareLHS < CompareRHS)
  9373. return Success(CCR::Less, E);
  9374. if (CompareLHS > CompareRHS)
  9375. return Success(CCR::Greater, E);
  9376. return Success(CCR::Equal, E);
  9377. }
  9378. if (LHSTy->isMemberPointerType()) {
  9379. assert(IsEquality && "unexpected member pointer operation");
  9380. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  9381. MemberPtr LHSValue, RHSValue;
  9382. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  9383. if (!LHSOK && !Info.noteFailure())
  9384. return false;
  9385. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9386. return false;
  9387. // C++11 [expr.eq]p2:
  9388. // If both operands are null, they compare equal. Otherwise if only one is
  9389. // null, they compare unequal.
  9390. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  9391. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  9392. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9393. }
  9394. // Otherwise if either is a pointer to a virtual member function, the
  9395. // result is unspecified.
  9396. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  9397. if (MD->isVirtual())
  9398. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9399. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  9400. if (MD->isVirtual())
  9401. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9402. // Otherwise they compare equal if and only if they would refer to the
  9403. // same member of the same most derived object or the same subobject if
  9404. // they were dereferenced with a hypothetical object of the associated
  9405. // class type.
  9406. bool Equal = LHSValue == RHSValue;
  9407. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9408. }
  9409. if (LHSTy->isNullPtrType()) {
  9410. assert(E->isComparisonOp() && "unexpected nullptr operation");
  9411. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  9412. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  9413. // are compared, the result is true of the operator is <=, >= or ==, and
  9414. // false otherwise.
  9415. return Success(CCR::Equal, E);
  9416. }
  9417. return DoAfter();
  9418. }
  9419. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  9420. if (!CheckLiteralType(Info, E))
  9421. return false;
  9422. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9423. const BinaryOperator *E) {
  9424. // Evaluation succeeded. Lookup the information for the comparison category
  9425. // type and fetch the VarDecl for the result.
  9426. const ComparisonCategoryInfo &CmpInfo =
  9427. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9428. const VarDecl *VD =
  9429. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  9430. // Check and evaluate the result as a constant expression.
  9431. LValue LV;
  9432. LV.set(VD);
  9433. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9434. return false;
  9435. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9436. };
  9437. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9438. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  9439. });
  9440. }
  9441. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9442. // We don't call noteFailure immediately because the assignment happens after
  9443. // we evaluate LHS and RHS.
  9444. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  9445. return Error(E);
  9446. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  9447. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  9448. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  9449. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  9450. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  9451. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  9452. if (E->isComparisonOp()) {
  9453. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  9454. // comparisons and then translating the result.
  9455. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9456. const BinaryOperator *E) {
  9457. using CCR = ComparisonCategoryResult;
  9458. bool IsEqual = ResKind == CCR::Equal,
  9459. IsLess = ResKind == CCR::Less,
  9460. IsGreater = ResKind == CCR::Greater;
  9461. auto Op = E->getOpcode();
  9462. switch (Op) {
  9463. default:
  9464. llvm_unreachable("unsupported binary operator");
  9465. case BO_EQ:
  9466. case BO_NE:
  9467. return Success(IsEqual == (Op == BO_EQ), E);
  9468. case BO_LT: return Success(IsLess, E);
  9469. case BO_GT: return Success(IsGreater, E);
  9470. case BO_LE: return Success(IsEqual || IsLess, E);
  9471. case BO_GE: return Success(IsEqual || IsGreater, E);
  9472. }
  9473. };
  9474. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9475. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9476. });
  9477. }
  9478. QualType LHSTy = E->getLHS()->getType();
  9479. QualType RHSTy = E->getRHS()->getType();
  9480. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  9481. E->getOpcode() == BO_Sub) {
  9482. LValue LHSValue, RHSValue;
  9483. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9484. if (!LHSOK && !Info.noteFailure())
  9485. return false;
  9486. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9487. return false;
  9488. // Reject differing bases from the normal codepath; we special-case
  9489. // comparisons to null.
  9490. if (!HasSameBase(LHSValue, RHSValue)) {
  9491. // Handle &&A - &&B.
  9492. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  9493. return Error(E);
  9494. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  9495. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  9496. if (!LHSExpr || !RHSExpr)
  9497. return Error(E);
  9498. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9499. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9500. if (!LHSAddrExpr || !RHSAddrExpr)
  9501. return Error(E);
  9502. // Make sure both labels come from the same function.
  9503. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9504. RHSAddrExpr->getLabel()->getDeclContext())
  9505. return Error(E);
  9506. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  9507. }
  9508. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9509. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9510. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9511. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9512. // C++11 [expr.add]p6:
  9513. // Unless both pointers point to elements of the same array object, or
  9514. // one past the last element of the array object, the behavior is
  9515. // undefined.
  9516. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  9517. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  9518. RHSDesignator))
  9519. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  9520. QualType Type = E->getLHS()->getType();
  9521. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  9522. CharUnits ElementSize;
  9523. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  9524. return false;
  9525. // As an extension, a type may have zero size (empty struct or union in
  9526. // C, array of zero length). Pointer subtraction in such cases has
  9527. // undefined behavior, so is not constant.
  9528. if (ElementSize.isZero()) {
  9529. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  9530. << ElementType;
  9531. return false;
  9532. }
  9533. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  9534. // and produce incorrect results when it overflows. Such behavior
  9535. // appears to be non-conforming, but is common, so perhaps we should
  9536. // assume the standard intended for such cases to be undefined behavior
  9537. // and check for them.
  9538. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  9539. // overflow in the final conversion to ptrdiff_t.
  9540. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  9541. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  9542. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  9543. false);
  9544. APSInt TrueResult = (LHS - RHS) / ElemSize;
  9545. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  9546. if (Result.extend(65) != TrueResult &&
  9547. !HandleOverflow(Info, E, TrueResult, E->getType()))
  9548. return false;
  9549. return Success(Result, E);
  9550. }
  9551. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9552. }
  9553. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  9554. /// a result as the expression's type.
  9555. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  9556. const UnaryExprOrTypeTraitExpr *E) {
  9557. switch(E->getKind()) {
  9558. case UETT_PreferredAlignOf:
  9559. case UETT_AlignOf: {
  9560. if (E->isArgumentType())
  9561. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  9562. E);
  9563. else
  9564. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  9565. E);
  9566. }
  9567. case UETT_VecStep: {
  9568. QualType Ty = E->getTypeOfArgument();
  9569. if (Ty->isVectorType()) {
  9570. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  9571. // The vec_step built-in functions that take a 3-component
  9572. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  9573. if (n == 3)
  9574. n = 4;
  9575. return Success(n, E);
  9576. } else
  9577. return Success(1, E);
  9578. }
  9579. case UETT_SizeOf: {
  9580. QualType SrcTy = E->getTypeOfArgument();
  9581. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  9582. // the result is the size of the referenced type."
  9583. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  9584. SrcTy = Ref->getPointeeType();
  9585. CharUnits Sizeof;
  9586. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  9587. return false;
  9588. return Success(Sizeof, E);
  9589. }
  9590. case UETT_OpenMPRequiredSimdAlign:
  9591. assert(E->isArgumentType());
  9592. return Success(
  9593. Info.Ctx.toCharUnitsFromBits(
  9594. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  9595. .getQuantity(),
  9596. E);
  9597. }
  9598. llvm_unreachable("unknown expr/type trait");
  9599. }
  9600. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  9601. CharUnits Result;
  9602. unsigned n = OOE->getNumComponents();
  9603. if (n == 0)
  9604. return Error(OOE);
  9605. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  9606. for (unsigned i = 0; i != n; ++i) {
  9607. OffsetOfNode ON = OOE->getComponent(i);
  9608. switch (ON.getKind()) {
  9609. case OffsetOfNode::Array: {
  9610. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  9611. APSInt IdxResult;
  9612. if (!EvaluateInteger(Idx, IdxResult, Info))
  9613. return false;
  9614. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  9615. if (!AT)
  9616. return Error(OOE);
  9617. CurrentType = AT->getElementType();
  9618. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  9619. Result += IdxResult.getSExtValue() * ElementSize;
  9620. break;
  9621. }
  9622. case OffsetOfNode::Field: {
  9623. FieldDecl *MemberDecl = ON.getField();
  9624. const RecordType *RT = CurrentType->getAs<RecordType>();
  9625. if (!RT)
  9626. return Error(OOE);
  9627. RecordDecl *RD = RT->getDecl();
  9628. if (RD->isInvalidDecl()) return false;
  9629. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  9630. unsigned i = MemberDecl->getFieldIndex();
  9631. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  9632. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  9633. CurrentType = MemberDecl->getType().getNonReferenceType();
  9634. break;
  9635. }
  9636. case OffsetOfNode::Identifier:
  9637. llvm_unreachable("dependent __builtin_offsetof");
  9638. case OffsetOfNode::Base: {
  9639. CXXBaseSpecifier *BaseSpec = ON.getBase();
  9640. if (BaseSpec->isVirtual())
  9641. return Error(OOE);
  9642. // Find the layout of the class whose base we are looking into.
  9643. const RecordType *RT = CurrentType->getAs<RecordType>();
  9644. if (!RT)
  9645. return Error(OOE);
  9646. RecordDecl *RD = RT->getDecl();
  9647. if (RD->isInvalidDecl()) return false;
  9648. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  9649. // Find the base class itself.
  9650. CurrentType = BaseSpec->getType();
  9651. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  9652. if (!BaseRT)
  9653. return Error(OOE);
  9654. // Add the offset to the base.
  9655. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  9656. break;
  9657. }
  9658. }
  9659. }
  9660. return Success(Result, OOE);
  9661. }
  9662. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9663. switch (E->getOpcode()) {
  9664. default:
  9665. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  9666. // See C99 6.6p3.
  9667. return Error(E);
  9668. case UO_Extension:
  9669. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  9670. // If so, we could clear the diagnostic ID.
  9671. return Visit(E->getSubExpr());
  9672. case UO_Plus:
  9673. // The result is just the value.
  9674. return Visit(E->getSubExpr());
  9675. case UO_Minus: {
  9676. if (!Visit(E->getSubExpr()))
  9677. return false;
  9678. if (!Result.isInt()) return Error(E);
  9679. const APSInt &Value = Result.getInt();
  9680. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  9681. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  9682. E->getType()))
  9683. return false;
  9684. return Success(-Value, E);
  9685. }
  9686. case UO_Not: {
  9687. if (!Visit(E->getSubExpr()))
  9688. return false;
  9689. if (!Result.isInt()) return Error(E);
  9690. return Success(~Result.getInt(), E);
  9691. }
  9692. case UO_LNot: {
  9693. bool bres;
  9694. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9695. return false;
  9696. return Success(!bres, E);
  9697. }
  9698. }
  9699. }
  9700. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  9701. /// result type is integer.
  9702. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9703. const Expr *SubExpr = E->getSubExpr();
  9704. QualType DestType = E->getType();
  9705. QualType SrcType = SubExpr->getType();
  9706. switch (E->getCastKind()) {
  9707. case CK_BaseToDerived:
  9708. case CK_DerivedToBase:
  9709. case CK_UncheckedDerivedToBase:
  9710. case CK_Dynamic:
  9711. case CK_ToUnion:
  9712. case CK_ArrayToPointerDecay:
  9713. case CK_FunctionToPointerDecay:
  9714. case CK_NullToPointer:
  9715. case CK_NullToMemberPointer:
  9716. case CK_BaseToDerivedMemberPointer:
  9717. case CK_DerivedToBaseMemberPointer:
  9718. case CK_ReinterpretMemberPointer:
  9719. case CK_ConstructorConversion:
  9720. case CK_IntegralToPointer:
  9721. case CK_ToVoid:
  9722. case CK_VectorSplat:
  9723. case CK_IntegralToFloating:
  9724. case CK_FloatingCast:
  9725. case CK_CPointerToObjCPointerCast:
  9726. case CK_BlockPointerToObjCPointerCast:
  9727. case CK_AnyPointerToBlockPointerCast:
  9728. case CK_ObjCObjectLValueCast:
  9729. case CK_FloatingRealToComplex:
  9730. case CK_FloatingComplexToReal:
  9731. case CK_FloatingComplexCast:
  9732. case CK_FloatingComplexToIntegralComplex:
  9733. case CK_IntegralRealToComplex:
  9734. case CK_IntegralComplexCast:
  9735. case CK_IntegralComplexToFloatingComplex:
  9736. case CK_BuiltinFnToFnPtr:
  9737. case CK_ZeroToOCLOpaqueType:
  9738. case CK_NonAtomicToAtomic:
  9739. case CK_AddressSpaceConversion:
  9740. case CK_IntToOCLSampler:
  9741. case CK_FixedPointCast:
  9742. case CK_IntegralToFixedPoint:
  9743. llvm_unreachable("invalid cast kind for integral value");
  9744. case CK_BitCast:
  9745. case CK_Dependent:
  9746. case CK_LValueBitCast:
  9747. case CK_ARCProduceObject:
  9748. case CK_ARCConsumeObject:
  9749. case CK_ARCReclaimReturnedObject:
  9750. case CK_ARCExtendBlockObject:
  9751. case CK_CopyAndAutoreleaseBlockObject:
  9752. return Error(E);
  9753. case CK_UserDefinedConversion:
  9754. case CK_LValueToRValue:
  9755. case CK_AtomicToNonAtomic:
  9756. case CK_NoOp:
  9757. case CK_LValueToRValueBitCast:
  9758. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9759. case CK_MemberPointerToBoolean:
  9760. case CK_PointerToBoolean:
  9761. case CK_IntegralToBoolean:
  9762. case CK_FloatingToBoolean:
  9763. case CK_BooleanToSignedIntegral:
  9764. case CK_FloatingComplexToBoolean:
  9765. case CK_IntegralComplexToBoolean: {
  9766. bool BoolResult;
  9767. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  9768. return false;
  9769. uint64_t IntResult = BoolResult;
  9770. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  9771. IntResult = (uint64_t)-1;
  9772. return Success(IntResult, E);
  9773. }
  9774. case CK_FixedPointToIntegral: {
  9775. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  9776. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9777. return false;
  9778. bool Overflowed;
  9779. llvm::APSInt Result = Src.convertToInt(
  9780. Info.Ctx.getIntWidth(DestType),
  9781. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  9782. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9783. return false;
  9784. return Success(Result, E);
  9785. }
  9786. case CK_FixedPointToBoolean: {
  9787. // Unsigned padding does not affect this.
  9788. APValue Val;
  9789. if (!Evaluate(Val, Info, SubExpr))
  9790. return false;
  9791. return Success(Val.getFixedPoint().getBoolValue(), E);
  9792. }
  9793. case CK_IntegralCast: {
  9794. if (!Visit(SubExpr))
  9795. return false;
  9796. if (!Result.isInt()) {
  9797. // Allow casts of address-of-label differences if they are no-ops
  9798. // or narrowing. (The narrowing case isn't actually guaranteed to
  9799. // be constant-evaluatable except in some narrow cases which are hard
  9800. // to detect here. We let it through on the assumption the user knows
  9801. // what they are doing.)
  9802. if (Result.isAddrLabelDiff())
  9803. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  9804. // Only allow casts of lvalues if they are lossless.
  9805. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  9806. }
  9807. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  9808. Result.getInt()), E);
  9809. }
  9810. case CK_PointerToIntegral: {
  9811. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  9812. LValue LV;
  9813. if (!EvaluatePointer(SubExpr, LV, Info))
  9814. return false;
  9815. if (LV.getLValueBase()) {
  9816. // Only allow based lvalue casts if they are lossless.
  9817. // FIXME: Allow a larger integer size than the pointer size, and allow
  9818. // narrowing back down to pointer width in subsequent integral casts.
  9819. // FIXME: Check integer type's active bits, not its type size.
  9820. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  9821. return Error(E);
  9822. LV.Designator.setInvalid();
  9823. LV.moveInto(Result);
  9824. return true;
  9825. }
  9826. APSInt AsInt;
  9827. APValue V;
  9828. LV.moveInto(V);
  9829. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  9830. llvm_unreachable("Can't cast this!");
  9831. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  9832. }
  9833. case CK_IntegralComplexToReal: {
  9834. ComplexValue C;
  9835. if (!EvaluateComplex(SubExpr, C, Info))
  9836. return false;
  9837. return Success(C.getComplexIntReal(), E);
  9838. }
  9839. case CK_FloatingToIntegral: {
  9840. APFloat F(0.0);
  9841. if (!EvaluateFloat(SubExpr, F, Info))
  9842. return false;
  9843. APSInt Value;
  9844. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  9845. return false;
  9846. return Success(Value, E);
  9847. }
  9848. }
  9849. llvm_unreachable("unknown cast resulting in integral value");
  9850. }
  9851. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9852. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9853. ComplexValue LV;
  9854. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9855. return false;
  9856. if (!LV.isComplexInt())
  9857. return Error(E);
  9858. return Success(LV.getComplexIntReal(), E);
  9859. }
  9860. return Visit(E->getSubExpr());
  9861. }
  9862. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9863. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  9864. ComplexValue LV;
  9865. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9866. return false;
  9867. if (!LV.isComplexInt())
  9868. return Error(E);
  9869. return Success(LV.getComplexIntImag(), E);
  9870. }
  9871. VisitIgnoredValue(E->getSubExpr());
  9872. return Success(0, E);
  9873. }
  9874. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  9875. return Success(E->getPackLength(), E);
  9876. }
  9877. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  9878. return Success(E->getValue(), E);
  9879. }
  9880. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9881. switch (E->getOpcode()) {
  9882. default:
  9883. // Invalid unary operators
  9884. return Error(E);
  9885. case UO_Plus:
  9886. // The result is just the value.
  9887. return Visit(E->getSubExpr());
  9888. case UO_Minus: {
  9889. if (!Visit(E->getSubExpr())) return false;
  9890. if (!Result.isFixedPoint())
  9891. return Error(E);
  9892. bool Overflowed;
  9893. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  9894. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  9895. return false;
  9896. return Success(Negated, E);
  9897. }
  9898. case UO_LNot: {
  9899. bool bres;
  9900. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9901. return false;
  9902. return Success(!bres, E);
  9903. }
  9904. }
  9905. }
  9906. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9907. const Expr *SubExpr = E->getSubExpr();
  9908. QualType DestType = E->getType();
  9909. assert(DestType->isFixedPointType() &&
  9910. "Expected destination type to be a fixed point type");
  9911. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  9912. switch (E->getCastKind()) {
  9913. case CK_FixedPointCast: {
  9914. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  9915. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9916. return false;
  9917. bool Overflowed;
  9918. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  9919. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9920. return false;
  9921. return Success(Result, E);
  9922. }
  9923. case CK_IntegralToFixedPoint: {
  9924. APSInt Src;
  9925. if (!EvaluateInteger(SubExpr, Src, Info))
  9926. return false;
  9927. bool Overflowed;
  9928. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  9929. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  9930. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  9931. return false;
  9932. return Success(IntResult, E);
  9933. }
  9934. case CK_NoOp:
  9935. case CK_LValueToRValue:
  9936. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9937. default:
  9938. return Error(E);
  9939. }
  9940. }
  9941. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9942. const Expr *LHS = E->getLHS();
  9943. const Expr *RHS = E->getRHS();
  9944. FixedPointSemantics ResultFXSema =
  9945. Info.Ctx.getFixedPointSemantics(E->getType());
  9946. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  9947. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  9948. return false;
  9949. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  9950. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  9951. return false;
  9952. switch (E->getOpcode()) {
  9953. case BO_Add: {
  9954. bool AddOverflow, ConversionOverflow;
  9955. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  9956. .convert(ResultFXSema, &ConversionOverflow);
  9957. if ((AddOverflow || ConversionOverflow) &&
  9958. !HandleOverflow(Info, E, Result, E->getType()))
  9959. return false;
  9960. return Success(Result, E);
  9961. }
  9962. default:
  9963. return false;
  9964. }
  9965. llvm_unreachable("Should've exited before this");
  9966. }
  9967. //===----------------------------------------------------------------------===//
  9968. // Float Evaluation
  9969. //===----------------------------------------------------------------------===//
  9970. namespace {
  9971. class FloatExprEvaluator
  9972. : public ExprEvaluatorBase<FloatExprEvaluator> {
  9973. APFloat &Result;
  9974. public:
  9975. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  9976. : ExprEvaluatorBaseTy(info), Result(result) {}
  9977. bool Success(const APValue &V, const Expr *e) {
  9978. Result = V.getFloat();
  9979. return true;
  9980. }
  9981. bool ZeroInitialization(const Expr *E) {
  9982. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  9983. return true;
  9984. }
  9985. bool VisitCallExpr(const CallExpr *E);
  9986. bool VisitUnaryOperator(const UnaryOperator *E);
  9987. bool VisitBinaryOperator(const BinaryOperator *E);
  9988. bool VisitFloatingLiteral(const FloatingLiteral *E);
  9989. bool VisitCastExpr(const CastExpr *E);
  9990. bool VisitUnaryReal(const UnaryOperator *E);
  9991. bool VisitUnaryImag(const UnaryOperator *E);
  9992. // FIXME: Missing: array subscript of vector, member of vector
  9993. };
  9994. } // end anonymous namespace
  9995. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  9996. assert(E->isRValue() && E->getType()->isRealFloatingType());
  9997. return FloatExprEvaluator(Info, Result).Visit(E);
  9998. }
  9999. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  10000. QualType ResultTy,
  10001. const Expr *Arg,
  10002. bool SNaN,
  10003. llvm::APFloat &Result) {
  10004. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  10005. if (!S) return false;
  10006. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  10007. llvm::APInt fill;
  10008. // Treat empty strings as if they were zero.
  10009. if (S->getString().empty())
  10010. fill = llvm::APInt(32, 0);
  10011. else if (S->getString().getAsInteger(0, fill))
  10012. return false;
  10013. if (Context.getTargetInfo().isNan2008()) {
  10014. if (SNaN)
  10015. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10016. else
  10017. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10018. } else {
  10019. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  10020. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  10021. // a different encoding to what became a standard in 2008, and for pre-
  10022. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  10023. // sNaN. This is now known as "legacy NaN" encoding.
  10024. if (SNaN)
  10025. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10026. else
  10027. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10028. }
  10029. return true;
  10030. }
  10031. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10032. switch (E->getBuiltinCallee()) {
  10033. default:
  10034. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10035. case Builtin::BI__builtin_huge_val:
  10036. case Builtin::BI__builtin_huge_valf:
  10037. case Builtin::BI__builtin_huge_vall:
  10038. case Builtin::BI__builtin_huge_valf128:
  10039. case Builtin::BI__builtin_inf:
  10040. case Builtin::BI__builtin_inff:
  10041. case Builtin::BI__builtin_infl:
  10042. case Builtin::BI__builtin_inff128: {
  10043. const llvm::fltSemantics &Sem =
  10044. Info.Ctx.getFloatTypeSemantics(E->getType());
  10045. Result = llvm::APFloat::getInf(Sem);
  10046. return true;
  10047. }
  10048. case Builtin::BI__builtin_nans:
  10049. case Builtin::BI__builtin_nansf:
  10050. case Builtin::BI__builtin_nansl:
  10051. case Builtin::BI__builtin_nansf128:
  10052. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10053. true, Result))
  10054. return Error(E);
  10055. return true;
  10056. case Builtin::BI__builtin_nan:
  10057. case Builtin::BI__builtin_nanf:
  10058. case Builtin::BI__builtin_nanl:
  10059. case Builtin::BI__builtin_nanf128:
  10060. // If this is __builtin_nan() turn this into a nan, otherwise we
  10061. // can't constant fold it.
  10062. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10063. false, Result))
  10064. return Error(E);
  10065. return true;
  10066. case Builtin::BI__builtin_fabs:
  10067. case Builtin::BI__builtin_fabsf:
  10068. case Builtin::BI__builtin_fabsl:
  10069. case Builtin::BI__builtin_fabsf128:
  10070. if (!EvaluateFloat(E->getArg(0), Result, Info))
  10071. return false;
  10072. if (Result.isNegative())
  10073. Result.changeSign();
  10074. return true;
  10075. // FIXME: Builtin::BI__builtin_powi
  10076. // FIXME: Builtin::BI__builtin_powif
  10077. // FIXME: Builtin::BI__builtin_powil
  10078. case Builtin::BI__builtin_copysign:
  10079. case Builtin::BI__builtin_copysignf:
  10080. case Builtin::BI__builtin_copysignl:
  10081. case Builtin::BI__builtin_copysignf128: {
  10082. APFloat RHS(0.);
  10083. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  10084. !EvaluateFloat(E->getArg(1), RHS, Info))
  10085. return false;
  10086. Result.copySign(RHS);
  10087. return true;
  10088. }
  10089. }
  10090. }
  10091. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10092. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10093. ComplexValue CV;
  10094. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10095. return false;
  10096. Result = CV.FloatReal;
  10097. return true;
  10098. }
  10099. return Visit(E->getSubExpr());
  10100. }
  10101. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10102. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10103. ComplexValue CV;
  10104. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10105. return false;
  10106. Result = CV.FloatImag;
  10107. return true;
  10108. }
  10109. VisitIgnoredValue(E->getSubExpr());
  10110. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  10111. Result = llvm::APFloat::getZero(Sem);
  10112. return true;
  10113. }
  10114. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10115. switch (E->getOpcode()) {
  10116. default: return Error(E);
  10117. case UO_Plus:
  10118. return EvaluateFloat(E->getSubExpr(), Result, Info);
  10119. case UO_Minus:
  10120. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  10121. return false;
  10122. Result.changeSign();
  10123. return true;
  10124. }
  10125. }
  10126. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10127. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10128. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10129. APFloat RHS(0.0);
  10130. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  10131. if (!LHSOK && !Info.noteFailure())
  10132. return false;
  10133. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  10134. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  10135. }
  10136. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  10137. Result = E->getValue();
  10138. return true;
  10139. }
  10140. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10141. const Expr* SubExpr = E->getSubExpr();
  10142. switch (E->getCastKind()) {
  10143. default:
  10144. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10145. case CK_IntegralToFloating: {
  10146. APSInt IntResult;
  10147. return EvaluateInteger(SubExpr, IntResult, Info) &&
  10148. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  10149. E->getType(), Result);
  10150. }
  10151. case CK_FloatingCast: {
  10152. if (!Visit(SubExpr))
  10153. return false;
  10154. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  10155. Result);
  10156. }
  10157. case CK_FloatingComplexToReal: {
  10158. ComplexValue V;
  10159. if (!EvaluateComplex(SubExpr, V, Info))
  10160. return false;
  10161. Result = V.getComplexFloatReal();
  10162. return true;
  10163. }
  10164. }
  10165. }
  10166. //===----------------------------------------------------------------------===//
  10167. // Complex Evaluation (for float and integer)
  10168. //===----------------------------------------------------------------------===//
  10169. namespace {
  10170. class ComplexExprEvaluator
  10171. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  10172. ComplexValue &Result;
  10173. public:
  10174. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  10175. : ExprEvaluatorBaseTy(info), Result(Result) {}
  10176. bool Success(const APValue &V, const Expr *e) {
  10177. Result.setFrom(V);
  10178. return true;
  10179. }
  10180. bool ZeroInitialization(const Expr *E);
  10181. //===--------------------------------------------------------------------===//
  10182. // Visitor Methods
  10183. //===--------------------------------------------------------------------===//
  10184. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  10185. bool VisitCastExpr(const CastExpr *E);
  10186. bool VisitBinaryOperator(const BinaryOperator *E);
  10187. bool VisitUnaryOperator(const UnaryOperator *E);
  10188. bool VisitInitListExpr(const InitListExpr *E);
  10189. };
  10190. } // end anonymous namespace
  10191. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  10192. EvalInfo &Info) {
  10193. assert(E->isRValue() && E->getType()->isAnyComplexType());
  10194. return ComplexExprEvaluator(Info, Result).Visit(E);
  10195. }
  10196. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  10197. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  10198. if (ElemTy->isRealFloatingType()) {
  10199. Result.makeComplexFloat();
  10200. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  10201. Result.FloatReal = Zero;
  10202. Result.FloatImag = Zero;
  10203. } else {
  10204. Result.makeComplexInt();
  10205. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  10206. Result.IntReal = Zero;
  10207. Result.IntImag = Zero;
  10208. }
  10209. return true;
  10210. }
  10211. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  10212. const Expr* SubExpr = E->getSubExpr();
  10213. if (SubExpr->getType()->isRealFloatingType()) {
  10214. Result.makeComplexFloat();
  10215. APFloat &Imag = Result.FloatImag;
  10216. if (!EvaluateFloat(SubExpr, Imag, Info))
  10217. return false;
  10218. Result.FloatReal = APFloat(Imag.getSemantics());
  10219. return true;
  10220. } else {
  10221. assert(SubExpr->getType()->isIntegerType() &&
  10222. "Unexpected imaginary literal.");
  10223. Result.makeComplexInt();
  10224. APSInt &Imag = Result.IntImag;
  10225. if (!EvaluateInteger(SubExpr, Imag, Info))
  10226. return false;
  10227. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  10228. return true;
  10229. }
  10230. }
  10231. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10232. switch (E->getCastKind()) {
  10233. case CK_BitCast:
  10234. case CK_BaseToDerived:
  10235. case CK_DerivedToBase:
  10236. case CK_UncheckedDerivedToBase:
  10237. case CK_Dynamic:
  10238. case CK_ToUnion:
  10239. case CK_ArrayToPointerDecay:
  10240. case CK_FunctionToPointerDecay:
  10241. case CK_NullToPointer:
  10242. case CK_NullToMemberPointer:
  10243. case CK_BaseToDerivedMemberPointer:
  10244. case CK_DerivedToBaseMemberPointer:
  10245. case CK_MemberPointerToBoolean:
  10246. case CK_ReinterpretMemberPointer:
  10247. case CK_ConstructorConversion:
  10248. case CK_IntegralToPointer:
  10249. case CK_PointerToIntegral:
  10250. case CK_PointerToBoolean:
  10251. case CK_ToVoid:
  10252. case CK_VectorSplat:
  10253. case CK_IntegralCast:
  10254. case CK_BooleanToSignedIntegral:
  10255. case CK_IntegralToBoolean:
  10256. case CK_IntegralToFloating:
  10257. case CK_FloatingToIntegral:
  10258. case CK_FloatingToBoolean:
  10259. case CK_FloatingCast:
  10260. case CK_CPointerToObjCPointerCast:
  10261. case CK_BlockPointerToObjCPointerCast:
  10262. case CK_AnyPointerToBlockPointerCast:
  10263. case CK_ObjCObjectLValueCast:
  10264. case CK_FloatingComplexToReal:
  10265. case CK_FloatingComplexToBoolean:
  10266. case CK_IntegralComplexToReal:
  10267. case CK_IntegralComplexToBoolean:
  10268. case CK_ARCProduceObject:
  10269. case CK_ARCConsumeObject:
  10270. case CK_ARCReclaimReturnedObject:
  10271. case CK_ARCExtendBlockObject:
  10272. case CK_CopyAndAutoreleaseBlockObject:
  10273. case CK_BuiltinFnToFnPtr:
  10274. case CK_ZeroToOCLOpaqueType:
  10275. case CK_NonAtomicToAtomic:
  10276. case CK_AddressSpaceConversion:
  10277. case CK_IntToOCLSampler:
  10278. case CK_FixedPointCast:
  10279. case CK_FixedPointToBoolean:
  10280. case CK_FixedPointToIntegral:
  10281. case CK_IntegralToFixedPoint:
  10282. llvm_unreachable("invalid cast kind for complex value");
  10283. case CK_LValueToRValue:
  10284. case CK_AtomicToNonAtomic:
  10285. case CK_NoOp:
  10286. case CK_LValueToRValueBitCast:
  10287. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10288. case CK_Dependent:
  10289. case CK_LValueBitCast:
  10290. case CK_UserDefinedConversion:
  10291. return Error(E);
  10292. case CK_FloatingRealToComplex: {
  10293. APFloat &Real = Result.FloatReal;
  10294. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  10295. return false;
  10296. Result.makeComplexFloat();
  10297. Result.FloatImag = APFloat(Real.getSemantics());
  10298. return true;
  10299. }
  10300. case CK_FloatingComplexCast: {
  10301. if (!Visit(E->getSubExpr()))
  10302. return false;
  10303. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10304. QualType From
  10305. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10306. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  10307. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  10308. }
  10309. case CK_FloatingComplexToIntegralComplex: {
  10310. if (!Visit(E->getSubExpr()))
  10311. return false;
  10312. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10313. QualType From
  10314. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10315. Result.makeComplexInt();
  10316. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  10317. To, Result.IntReal) &&
  10318. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  10319. To, Result.IntImag);
  10320. }
  10321. case CK_IntegralRealToComplex: {
  10322. APSInt &Real = Result.IntReal;
  10323. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  10324. return false;
  10325. Result.makeComplexInt();
  10326. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  10327. return true;
  10328. }
  10329. case CK_IntegralComplexCast: {
  10330. if (!Visit(E->getSubExpr()))
  10331. return false;
  10332. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10333. QualType From
  10334. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10335. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  10336. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  10337. return true;
  10338. }
  10339. case CK_IntegralComplexToFloatingComplex: {
  10340. if (!Visit(E->getSubExpr()))
  10341. return false;
  10342. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  10343. QualType From
  10344. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  10345. Result.makeComplexFloat();
  10346. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  10347. To, Result.FloatReal) &&
  10348. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  10349. To, Result.FloatImag);
  10350. }
  10351. }
  10352. llvm_unreachable("unknown cast resulting in complex value");
  10353. }
  10354. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10355. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10356. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10357. // Track whether the LHS or RHS is real at the type system level. When this is
  10358. // the case we can simplify our evaluation strategy.
  10359. bool LHSReal = false, RHSReal = false;
  10360. bool LHSOK;
  10361. if (E->getLHS()->getType()->isRealFloatingType()) {
  10362. LHSReal = true;
  10363. APFloat &Real = Result.FloatReal;
  10364. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  10365. if (LHSOK) {
  10366. Result.makeComplexFloat();
  10367. Result.FloatImag = APFloat(Real.getSemantics());
  10368. }
  10369. } else {
  10370. LHSOK = Visit(E->getLHS());
  10371. }
  10372. if (!LHSOK && !Info.noteFailure())
  10373. return false;
  10374. ComplexValue RHS;
  10375. if (E->getRHS()->getType()->isRealFloatingType()) {
  10376. RHSReal = true;
  10377. APFloat &Real = RHS.FloatReal;
  10378. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  10379. return false;
  10380. RHS.makeComplexFloat();
  10381. RHS.FloatImag = APFloat(Real.getSemantics());
  10382. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10383. return false;
  10384. assert(!(LHSReal && RHSReal) &&
  10385. "Cannot have both operands of a complex operation be real.");
  10386. switch (E->getOpcode()) {
  10387. default: return Error(E);
  10388. case BO_Add:
  10389. if (Result.isComplexFloat()) {
  10390. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  10391. APFloat::rmNearestTiesToEven);
  10392. if (LHSReal)
  10393. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10394. else if (!RHSReal)
  10395. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  10396. APFloat::rmNearestTiesToEven);
  10397. } else {
  10398. Result.getComplexIntReal() += RHS.getComplexIntReal();
  10399. Result.getComplexIntImag() += RHS.getComplexIntImag();
  10400. }
  10401. break;
  10402. case BO_Sub:
  10403. if (Result.isComplexFloat()) {
  10404. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  10405. APFloat::rmNearestTiesToEven);
  10406. if (LHSReal) {
  10407. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10408. Result.getComplexFloatImag().changeSign();
  10409. } else if (!RHSReal) {
  10410. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  10411. APFloat::rmNearestTiesToEven);
  10412. }
  10413. } else {
  10414. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  10415. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  10416. }
  10417. break;
  10418. case BO_Mul:
  10419. if (Result.isComplexFloat()) {
  10420. // This is an implementation of complex multiplication according to the
  10421. // constraints laid out in C11 Annex G. The implementation uses the
  10422. // following naming scheme:
  10423. // (a + ib) * (c + id)
  10424. ComplexValue LHS = Result;
  10425. APFloat &A = LHS.getComplexFloatReal();
  10426. APFloat &B = LHS.getComplexFloatImag();
  10427. APFloat &C = RHS.getComplexFloatReal();
  10428. APFloat &D = RHS.getComplexFloatImag();
  10429. APFloat &ResR = Result.getComplexFloatReal();
  10430. APFloat &ResI = Result.getComplexFloatImag();
  10431. if (LHSReal) {
  10432. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  10433. ResR = A * C;
  10434. ResI = A * D;
  10435. } else if (RHSReal) {
  10436. ResR = C * A;
  10437. ResI = C * B;
  10438. } else {
  10439. // In the fully general case, we need to handle NaNs and infinities
  10440. // robustly.
  10441. APFloat AC = A * C;
  10442. APFloat BD = B * D;
  10443. APFloat AD = A * D;
  10444. APFloat BC = B * C;
  10445. ResR = AC - BD;
  10446. ResI = AD + BC;
  10447. if (ResR.isNaN() && ResI.isNaN()) {
  10448. bool Recalc = false;
  10449. if (A.isInfinity() || B.isInfinity()) {
  10450. A = APFloat::copySign(
  10451. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10452. B = APFloat::copySign(
  10453. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10454. if (C.isNaN())
  10455. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10456. if (D.isNaN())
  10457. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10458. Recalc = true;
  10459. }
  10460. if (C.isInfinity() || D.isInfinity()) {
  10461. C = APFloat::copySign(
  10462. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10463. D = APFloat::copySign(
  10464. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10465. if (A.isNaN())
  10466. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10467. if (B.isNaN())
  10468. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10469. Recalc = true;
  10470. }
  10471. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  10472. AD.isInfinity() || BC.isInfinity())) {
  10473. if (A.isNaN())
  10474. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10475. if (B.isNaN())
  10476. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10477. if (C.isNaN())
  10478. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10479. if (D.isNaN())
  10480. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10481. Recalc = true;
  10482. }
  10483. if (Recalc) {
  10484. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  10485. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  10486. }
  10487. }
  10488. }
  10489. } else {
  10490. ComplexValue LHS = Result;
  10491. Result.getComplexIntReal() =
  10492. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  10493. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  10494. Result.getComplexIntImag() =
  10495. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  10496. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  10497. }
  10498. break;
  10499. case BO_Div:
  10500. if (Result.isComplexFloat()) {
  10501. // This is an implementation of complex division according to the
  10502. // constraints laid out in C11 Annex G. The implementation uses the
  10503. // following naming scheme:
  10504. // (a + ib) / (c + id)
  10505. ComplexValue LHS = Result;
  10506. APFloat &A = LHS.getComplexFloatReal();
  10507. APFloat &B = LHS.getComplexFloatImag();
  10508. APFloat &C = RHS.getComplexFloatReal();
  10509. APFloat &D = RHS.getComplexFloatImag();
  10510. APFloat &ResR = Result.getComplexFloatReal();
  10511. APFloat &ResI = Result.getComplexFloatImag();
  10512. if (RHSReal) {
  10513. ResR = A / C;
  10514. ResI = B / C;
  10515. } else {
  10516. if (LHSReal) {
  10517. // No real optimizations we can do here, stub out with zero.
  10518. B = APFloat::getZero(A.getSemantics());
  10519. }
  10520. int DenomLogB = 0;
  10521. APFloat MaxCD = maxnum(abs(C), abs(D));
  10522. if (MaxCD.isFinite()) {
  10523. DenomLogB = ilogb(MaxCD);
  10524. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  10525. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  10526. }
  10527. APFloat Denom = C * C + D * D;
  10528. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  10529. APFloat::rmNearestTiesToEven);
  10530. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  10531. APFloat::rmNearestTiesToEven);
  10532. if (ResR.isNaN() && ResI.isNaN()) {
  10533. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  10534. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  10535. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  10536. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  10537. D.isFinite()) {
  10538. A = APFloat::copySign(
  10539. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10540. B = APFloat::copySign(
  10541. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10542. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  10543. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  10544. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  10545. C = APFloat::copySign(
  10546. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10547. D = APFloat::copySign(
  10548. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10549. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  10550. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  10551. }
  10552. }
  10553. }
  10554. } else {
  10555. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  10556. return Error(E, diag::note_expr_divide_by_zero);
  10557. ComplexValue LHS = Result;
  10558. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  10559. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  10560. Result.getComplexIntReal() =
  10561. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  10562. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  10563. Result.getComplexIntImag() =
  10564. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  10565. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  10566. }
  10567. break;
  10568. }
  10569. return true;
  10570. }
  10571. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10572. // Get the operand value into 'Result'.
  10573. if (!Visit(E->getSubExpr()))
  10574. return false;
  10575. switch (E->getOpcode()) {
  10576. default:
  10577. return Error(E);
  10578. case UO_Extension:
  10579. return true;
  10580. case UO_Plus:
  10581. // The result is always just the subexpr.
  10582. return true;
  10583. case UO_Minus:
  10584. if (Result.isComplexFloat()) {
  10585. Result.getComplexFloatReal().changeSign();
  10586. Result.getComplexFloatImag().changeSign();
  10587. }
  10588. else {
  10589. Result.getComplexIntReal() = -Result.getComplexIntReal();
  10590. Result.getComplexIntImag() = -Result.getComplexIntImag();
  10591. }
  10592. return true;
  10593. case UO_Not:
  10594. if (Result.isComplexFloat())
  10595. Result.getComplexFloatImag().changeSign();
  10596. else
  10597. Result.getComplexIntImag() = -Result.getComplexIntImag();
  10598. return true;
  10599. }
  10600. }
  10601. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  10602. if (E->getNumInits() == 2) {
  10603. if (E->getType()->isComplexType()) {
  10604. Result.makeComplexFloat();
  10605. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  10606. return false;
  10607. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  10608. return false;
  10609. } else {
  10610. Result.makeComplexInt();
  10611. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  10612. return false;
  10613. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  10614. return false;
  10615. }
  10616. return true;
  10617. }
  10618. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  10619. }
  10620. //===----------------------------------------------------------------------===//
  10621. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  10622. // implicit conversion.
  10623. //===----------------------------------------------------------------------===//
  10624. namespace {
  10625. class AtomicExprEvaluator :
  10626. public ExprEvaluatorBase<AtomicExprEvaluator> {
  10627. const LValue *This;
  10628. APValue &Result;
  10629. public:
  10630. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  10631. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  10632. bool Success(const APValue &V, const Expr *E) {
  10633. Result = V;
  10634. return true;
  10635. }
  10636. bool ZeroInitialization(const Expr *E) {
  10637. ImplicitValueInitExpr VIE(
  10638. E->getType()->castAs<AtomicType>()->getValueType());
  10639. // For atomic-qualified class (and array) types in C++, initialize the
  10640. // _Atomic-wrapped subobject directly, in-place.
  10641. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  10642. : Evaluate(Result, Info, &VIE);
  10643. }
  10644. bool VisitCastExpr(const CastExpr *E) {
  10645. switch (E->getCastKind()) {
  10646. default:
  10647. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10648. case CK_NonAtomicToAtomic:
  10649. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  10650. : Evaluate(Result, Info, E->getSubExpr());
  10651. }
  10652. }
  10653. };
  10654. } // end anonymous namespace
  10655. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  10656. EvalInfo &Info) {
  10657. assert(E->isRValue() && E->getType()->isAtomicType());
  10658. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  10659. }
  10660. //===----------------------------------------------------------------------===//
  10661. // Void expression evaluation, primarily for a cast to void on the LHS of a
  10662. // comma operator
  10663. //===----------------------------------------------------------------------===//
  10664. namespace {
  10665. class VoidExprEvaluator
  10666. : public ExprEvaluatorBase<VoidExprEvaluator> {
  10667. public:
  10668. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  10669. bool Success(const APValue &V, const Expr *e) { return true; }
  10670. bool ZeroInitialization(const Expr *E) { return true; }
  10671. bool VisitCastExpr(const CastExpr *E) {
  10672. switch (E->getCastKind()) {
  10673. default:
  10674. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10675. case CK_ToVoid:
  10676. VisitIgnoredValue(E->getSubExpr());
  10677. return true;
  10678. }
  10679. }
  10680. bool VisitCallExpr(const CallExpr *E) {
  10681. switch (E->getBuiltinCallee()) {
  10682. default:
  10683. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10684. case Builtin::BI__assume:
  10685. case Builtin::BI__builtin_assume:
  10686. // The argument is not evaluated!
  10687. return true;
  10688. }
  10689. }
  10690. };
  10691. } // end anonymous namespace
  10692. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  10693. assert(E->isRValue() && E->getType()->isVoidType());
  10694. return VoidExprEvaluator(Info).Visit(E);
  10695. }
  10696. //===----------------------------------------------------------------------===//
  10697. // Top level Expr::EvaluateAsRValue method.
  10698. //===----------------------------------------------------------------------===//
  10699. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  10700. // In C, function designators are not lvalues, but we evaluate them as if they
  10701. // are.
  10702. QualType T = E->getType();
  10703. if (E->isGLValue() || T->isFunctionType()) {
  10704. LValue LV;
  10705. if (!EvaluateLValue(E, LV, Info))
  10706. return false;
  10707. LV.moveInto(Result);
  10708. } else if (T->isVectorType()) {
  10709. if (!EvaluateVector(E, Result, Info))
  10710. return false;
  10711. } else if (T->isIntegralOrEnumerationType()) {
  10712. if (!IntExprEvaluator(Info, Result).Visit(E))
  10713. return false;
  10714. } else if (T->hasPointerRepresentation()) {
  10715. LValue LV;
  10716. if (!EvaluatePointer(E, LV, Info))
  10717. return false;
  10718. LV.moveInto(Result);
  10719. } else if (T->isRealFloatingType()) {
  10720. llvm::APFloat F(0.0);
  10721. if (!EvaluateFloat(E, F, Info))
  10722. return false;
  10723. Result = APValue(F);
  10724. } else if (T->isAnyComplexType()) {
  10725. ComplexValue C;
  10726. if (!EvaluateComplex(E, C, Info))
  10727. return false;
  10728. C.moveInto(Result);
  10729. } else if (T->isFixedPointType()) {
  10730. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  10731. } else if (T->isMemberPointerType()) {
  10732. MemberPtr P;
  10733. if (!EvaluateMemberPointer(E, P, Info))
  10734. return false;
  10735. P.moveInto(Result);
  10736. return true;
  10737. } else if (T->isArrayType()) {
  10738. LValue LV;
  10739. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10740. if (!EvaluateArray(E, LV, Value, Info))
  10741. return false;
  10742. Result = Value;
  10743. } else if (T->isRecordType()) {
  10744. LValue LV;
  10745. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10746. if (!EvaluateRecord(E, LV, Value, Info))
  10747. return false;
  10748. Result = Value;
  10749. } else if (T->isVoidType()) {
  10750. if (!Info.getLangOpts().CPlusPlus11)
  10751. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  10752. << E->getType();
  10753. if (!EvaluateVoid(E, Info))
  10754. return false;
  10755. } else if (T->isAtomicType()) {
  10756. QualType Unqual = T.getAtomicUnqualifiedType();
  10757. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  10758. LValue LV;
  10759. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10760. if (!EvaluateAtomic(E, &LV, Value, Info))
  10761. return false;
  10762. } else {
  10763. if (!EvaluateAtomic(E, nullptr, Result, Info))
  10764. return false;
  10765. }
  10766. } else if (Info.getLangOpts().CPlusPlus11) {
  10767. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  10768. return false;
  10769. } else {
  10770. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10771. return false;
  10772. }
  10773. return true;
  10774. }
  10775. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  10776. /// cases, the in-place evaluation is essential, since later initializers for
  10777. /// an object can indirectly refer to subobjects which were initialized earlier.
  10778. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  10779. const Expr *E, bool AllowNonLiteralTypes) {
  10780. assert(!E->isValueDependent());
  10781. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  10782. return false;
  10783. if (E->isRValue()) {
  10784. // Evaluate arrays and record types in-place, so that later initializers can
  10785. // refer to earlier-initialized members of the object.
  10786. QualType T = E->getType();
  10787. if (T->isArrayType())
  10788. return EvaluateArray(E, This, Result, Info);
  10789. else if (T->isRecordType())
  10790. return EvaluateRecord(E, This, Result, Info);
  10791. else if (T->isAtomicType()) {
  10792. QualType Unqual = T.getAtomicUnqualifiedType();
  10793. if (Unqual->isArrayType() || Unqual->isRecordType())
  10794. return EvaluateAtomic(E, &This, Result, Info);
  10795. }
  10796. }
  10797. // For any other type, in-place evaluation is unimportant.
  10798. return Evaluate(Result, Info, E);
  10799. }
  10800. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  10801. /// lvalue-to-rvalue cast if it is an lvalue.
  10802. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  10803. if (E->getType().isNull())
  10804. return false;
  10805. if (!CheckLiteralType(Info, E))
  10806. return false;
  10807. if (!::Evaluate(Result, Info, E))
  10808. return false;
  10809. if (E->isGLValue()) {
  10810. LValue LV;
  10811. LV.setFrom(Info.Ctx, Result);
  10812. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10813. return false;
  10814. }
  10815. // Check this core constant expression is a constant expression.
  10816. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10817. }
  10818. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  10819. const ASTContext &Ctx, bool &IsConst) {
  10820. // Fast-path evaluations of integer literals, since we sometimes see files
  10821. // containing vast quantities of these.
  10822. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  10823. Result.Val = APValue(APSInt(L->getValue(),
  10824. L->getType()->isUnsignedIntegerType()));
  10825. IsConst = true;
  10826. return true;
  10827. }
  10828. // This case should be rare, but we need to check it before we check on
  10829. // the type below.
  10830. if (Exp->getType().isNull()) {
  10831. IsConst = false;
  10832. return true;
  10833. }
  10834. // FIXME: Evaluating values of large array and record types can cause
  10835. // performance problems. Only do so in C++11 for now.
  10836. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  10837. Exp->getType()->isRecordType()) &&
  10838. !Ctx.getLangOpts().CPlusPlus11) {
  10839. IsConst = false;
  10840. return true;
  10841. }
  10842. return false;
  10843. }
  10844. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  10845. Expr::SideEffectsKind SEK) {
  10846. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  10847. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  10848. }
  10849. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  10850. const ASTContext &Ctx, EvalInfo &Info) {
  10851. bool IsConst;
  10852. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  10853. return IsConst;
  10854. return EvaluateAsRValue(Info, E, Result.Val);
  10855. }
  10856. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  10857. const ASTContext &Ctx,
  10858. Expr::SideEffectsKind AllowSideEffects,
  10859. EvalInfo &Info) {
  10860. if (!E->getType()->isIntegralOrEnumerationType())
  10861. return false;
  10862. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  10863. !ExprResult.Val.isInt() ||
  10864. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10865. return false;
  10866. return true;
  10867. }
  10868. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  10869. const ASTContext &Ctx,
  10870. Expr::SideEffectsKind AllowSideEffects,
  10871. EvalInfo &Info) {
  10872. if (!E->getType()->isFixedPointType())
  10873. return false;
  10874. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  10875. return false;
  10876. if (!ExprResult.Val.isFixedPoint() ||
  10877. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10878. return false;
  10879. return true;
  10880. }
  10881. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  10882. /// any crazy technique (that has nothing to do with language standards) that
  10883. /// we want to. If this function returns true, it returns the folded constant
  10884. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  10885. /// will be applied to the result.
  10886. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  10887. bool InConstantContext) const {
  10888. assert(!isValueDependent() &&
  10889. "Expression evaluator can't be called on a dependent expression.");
  10890. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10891. Info.InConstantContext = InConstantContext;
  10892. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  10893. }
  10894. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  10895. bool InConstantContext) const {
  10896. assert(!isValueDependent() &&
  10897. "Expression evaluator can't be called on a dependent expression.");
  10898. EvalResult Scratch;
  10899. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  10900. HandleConversionToBool(Scratch.Val, Result);
  10901. }
  10902. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  10903. SideEffectsKind AllowSideEffects,
  10904. bool InConstantContext) const {
  10905. assert(!isValueDependent() &&
  10906. "Expression evaluator can't be called on a dependent expression.");
  10907. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10908. Info.InConstantContext = InConstantContext;
  10909. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  10910. }
  10911. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  10912. SideEffectsKind AllowSideEffects,
  10913. bool InConstantContext) const {
  10914. assert(!isValueDependent() &&
  10915. "Expression evaluator can't be called on a dependent expression.");
  10916. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10917. Info.InConstantContext = InConstantContext;
  10918. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  10919. }
  10920. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  10921. SideEffectsKind AllowSideEffects,
  10922. bool InConstantContext) const {
  10923. assert(!isValueDependent() &&
  10924. "Expression evaluator can't be called on a dependent expression.");
  10925. if (!getType()->isRealFloatingType())
  10926. return false;
  10927. EvalResult ExprResult;
  10928. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  10929. !ExprResult.Val.isFloat() ||
  10930. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10931. return false;
  10932. Result = ExprResult.Val.getFloat();
  10933. return true;
  10934. }
  10935. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  10936. bool InConstantContext) const {
  10937. assert(!isValueDependent() &&
  10938. "Expression evaluator can't be called on a dependent expression.");
  10939. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  10940. Info.InConstantContext = InConstantContext;
  10941. LValue LV;
  10942. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  10943. !CheckLValueConstantExpression(Info, getExprLoc(),
  10944. Ctx.getLValueReferenceType(getType()), LV,
  10945. Expr::EvaluateForCodeGen))
  10946. return false;
  10947. LV.moveInto(Result.Val);
  10948. return true;
  10949. }
  10950. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  10951. const ASTContext &Ctx) const {
  10952. assert(!isValueDependent() &&
  10953. "Expression evaluator can't be called on a dependent expression.");
  10954. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  10955. EvalInfo Info(Ctx, Result, EM);
  10956. Info.InConstantContext = true;
  10957. if (!::Evaluate(Result.Val, Info, this))
  10958. return false;
  10959. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  10960. Usage);
  10961. }
  10962. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  10963. const VarDecl *VD,
  10964. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  10965. assert(!isValueDependent() &&
  10966. "Expression evaluator can't be called on a dependent expression.");
  10967. // FIXME: Evaluating initializers for large array and record types can cause
  10968. // performance problems. Only do so in C++11 for now.
  10969. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  10970. !Ctx.getLangOpts().CPlusPlus11)
  10971. return false;
  10972. Expr::EvalStatus EStatus;
  10973. EStatus.Diag = &Notes;
  10974. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  10975. ? EvalInfo::EM_ConstantExpression
  10976. : EvalInfo::EM_ConstantFold);
  10977. InitInfo.setEvaluatingDecl(VD, Value);
  10978. InitInfo.InConstantContext = true;
  10979. LValue LVal;
  10980. LVal.set(VD);
  10981. // C++11 [basic.start.init]p2:
  10982. // Variables with static storage duration or thread storage duration shall be
  10983. // zero-initialized before any other initialization takes place.
  10984. // This behavior is not present in C.
  10985. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  10986. !VD->getType()->isReferenceType()) {
  10987. ImplicitValueInitExpr VIE(VD->getType());
  10988. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  10989. /*AllowNonLiteralTypes=*/true))
  10990. return false;
  10991. }
  10992. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  10993. /*AllowNonLiteralTypes=*/true) ||
  10994. EStatus.HasSideEffects)
  10995. return false;
  10996. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  10997. Value);
  10998. }
  10999. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  11000. /// constant folded, but discard the result.
  11001. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  11002. assert(!isValueDependent() &&
  11003. "Expression evaluator can't be called on a dependent expression.");
  11004. EvalResult Result;
  11005. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  11006. !hasUnacceptableSideEffect(Result, SEK);
  11007. }
  11008. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  11009. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11010. assert(!isValueDependent() &&
  11011. "Expression evaluator can't be called on a dependent expression.");
  11012. EvalResult EVResult;
  11013. EVResult.Diag = Diag;
  11014. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11015. Info.InConstantContext = true;
  11016. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  11017. (void)Result;
  11018. assert(Result && "Could not evaluate expression");
  11019. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11020. return EVResult.Val.getInt();
  11021. }
  11022. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  11023. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11024. assert(!isValueDependent() &&
  11025. "Expression evaluator can't be called on a dependent expression.");
  11026. EvalResult EVResult;
  11027. EVResult.Diag = Diag;
  11028. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  11029. Info.InConstantContext = true;
  11030. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  11031. (void)Result;
  11032. assert(Result && "Could not evaluate expression");
  11033. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11034. return EVResult.Val.getInt();
  11035. }
  11036. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  11037. assert(!isValueDependent() &&
  11038. "Expression evaluator can't be called on a dependent expression.");
  11039. bool IsConst;
  11040. EvalResult EVResult;
  11041. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  11042. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  11043. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  11044. }
  11045. }
  11046. bool Expr::EvalResult::isGlobalLValue() const {
  11047. assert(Val.isLValue());
  11048. return IsGlobalLValue(Val.getLValueBase());
  11049. }
  11050. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  11051. /// an integer constant expression.
  11052. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  11053. /// comma, etc
  11054. // CheckICE - This function does the fundamental ICE checking: the returned
  11055. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  11056. // and a (possibly null) SourceLocation indicating the location of the problem.
  11057. //
  11058. // Note that to reduce code duplication, this helper does no evaluation
  11059. // itself; the caller checks whether the expression is evaluatable, and
  11060. // in the rare cases where CheckICE actually cares about the evaluated
  11061. // value, it calls into Evaluate.
  11062. namespace {
  11063. enum ICEKind {
  11064. /// This expression is an ICE.
  11065. IK_ICE,
  11066. /// This expression is not an ICE, but if it isn't evaluated, it's
  11067. /// a legal subexpression for an ICE. This return value is used to handle
  11068. /// the comma operator in C99 mode, and non-constant subexpressions.
  11069. IK_ICEIfUnevaluated,
  11070. /// This expression is not an ICE, and is not a legal subexpression for one.
  11071. IK_NotICE
  11072. };
  11073. struct ICEDiag {
  11074. ICEKind Kind;
  11075. SourceLocation Loc;
  11076. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  11077. };
  11078. }
  11079. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  11080. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  11081. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  11082. Expr::EvalResult EVResult;
  11083. Expr::EvalStatus Status;
  11084. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11085. Info.InConstantContext = true;
  11086. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  11087. !EVResult.Val.isInt())
  11088. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11089. return NoDiag();
  11090. }
  11091. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  11092. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  11093. if (!E->getType()->isIntegralOrEnumerationType())
  11094. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11095. switch (E->getStmtClass()) {
  11096. #define ABSTRACT_STMT(Node)
  11097. #define STMT(Node, Base) case Expr::Node##Class:
  11098. #define EXPR(Node, Base)
  11099. #include "clang/AST/StmtNodes.inc"
  11100. case Expr::PredefinedExprClass:
  11101. case Expr::FloatingLiteralClass:
  11102. case Expr::ImaginaryLiteralClass:
  11103. case Expr::StringLiteralClass:
  11104. case Expr::ArraySubscriptExprClass:
  11105. case Expr::OMPArraySectionExprClass:
  11106. case Expr::MemberExprClass:
  11107. case Expr::CompoundAssignOperatorClass:
  11108. case Expr::CompoundLiteralExprClass:
  11109. case Expr::ExtVectorElementExprClass:
  11110. case Expr::DesignatedInitExprClass:
  11111. case Expr::ArrayInitLoopExprClass:
  11112. case Expr::ArrayInitIndexExprClass:
  11113. case Expr::NoInitExprClass:
  11114. case Expr::DesignatedInitUpdateExprClass:
  11115. case Expr::ImplicitValueInitExprClass:
  11116. case Expr::ParenListExprClass:
  11117. case Expr::VAArgExprClass:
  11118. case Expr::AddrLabelExprClass:
  11119. case Expr::StmtExprClass:
  11120. case Expr::CXXMemberCallExprClass:
  11121. case Expr::CUDAKernelCallExprClass:
  11122. case Expr::CXXDynamicCastExprClass:
  11123. case Expr::CXXTypeidExprClass:
  11124. case Expr::CXXUuidofExprClass:
  11125. case Expr::MSPropertyRefExprClass:
  11126. case Expr::MSPropertySubscriptExprClass:
  11127. case Expr::CXXNullPtrLiteralExprClass:
  11128. case Expr::UserDefinedLiteralClass:
  11129. case Expr::CXXThisExprClass:
  11130. case Expr::CXXThrowExprClass:
  11131. case Expr::CXXNewExprClass:
  11132. case Expr::CXXDeleteExprClass:
  11133. case Expr::CXXPseudoDestructorExprClass:
  11134. case Expr::UnresolvedLookupExprClass:
  11135. case Expr::TypoExprClass:
  11136. case Expr::DependentScopeDeclRefExprClass:
  11137. case Expr::CXXConstructExprClass:
  11138. case Expr::CXXInheritedCtorInitExprClass:
  11139. case Expr::CXXStdInitializerListExprClass:
  11140. case Expr::CXXBindTemporaryExprClass:
  11141. case Expr::ExprWithCleanupsClass:
  11142. case Expr::CXXTemporaryObjectExprClass:
  11143. case Expr::CXXUnresolvedConstructExprClass:
  11144. case Expr::CXXDependentScopeMemberExprClass:
  11145. case Expr::UnresolvedMemberExprClass:
  11146. case Expr::ObjCStringLiteralClass:
  11147. case Expr::ObjCBoxedExprClass:
  11148. case Expr::ObjCArrayLiteralClass:
  11149. case Expr::ObjCDictionaryLiteralClass:
  11150. case Expr::ObjCEncodeExprClass:
  11151. case Expr::ObjCMessageExprClass:
  11152. case Expr::ObjCSelectorExprClass:
  11153. case Expr::ObjCProtocolExprClass:
  11154. case Expr::ObjCIvarRefExprClass:
  11155. case Expr::ObjCPropertyRefExprClass:
  11156. case Expr::ObjCSubscriptRefExprClass:
  11157. case Expr::ObjCIsaExprClass:
  11158. case Expr::ObjCAvailabilityCheckExprClass:
  11159. case Expr::ShuffleVectorExprClass:
  11160. case Expr::ConvertVectorExprClass:
  11161. case Expr::BlockExprClass:
  11162. case Expr::NoStmtClass:
  11163. case Expr::OpaqueValueExprClass:
  11164. case Expr::PackExpansionExprClass:
  11165. case Expr::SubstNonTypeTemplateParmPackExprClass:
  11166. case Expr::FunctionParmPackExprClass:
  11167. case Expr::AsTypeExprClass:
  11168. case Expr::ObjCIndirectCopyRestoreExprClass:
  11169. case Expr::MaterializeTemporaryExprClass:
  11170. case Expr::PseudoObjectExprClass:
  11171. case Expr::AtomicExprClass:
  11172. case Expr::LambdaExprClass:
  11173. case Expr::CXXFoldExprClass:
  11174. case Expr::CoawaitExprClass:
  11175. case Expr::DependentCoawaitExprClass:
  11176. case Expr::CoyieldExprClass:
  11177. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11178. case Expr::InitListExprClass: {
  11179. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  11180. // form "T x = { a };" is equivalent to "T x = a;".
  11181. // Unless we're initializing a reference, T is a scalar as it is known to be
  11182. // of integral or enumeration type.
  11183. if (E->isRValue())
  11184. if (cast<InitListExpr>(E)->getNumInits() == 1)
  11185. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  11186. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11187. }
  11188. case Expr::SizeOfPackExprClass:
  11189. case Expr::GNUNullExprClass:
  11190. case Expr::SourceLocExprClass:
  11191. return NoDiag();
  11192. case Expr::SubstNonTypeTemplateParmExprClass:
  11193. return
  11194. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  11195. case Expr::ConstantExprClass:
  11196. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  11197. case Expr::ParenExprClass:
  11198. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  11199. case Expr::GenericSelectionExprClass:
  11200. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  11201. case Expr::IntegerLiteralClass:
  11202. case Expr::FixedPointLiteralClass:
  11203. case Expr::CharacterLiteralClass:
  11204. case Expr::ObjCBoolLiteralExprClass:
  11205. case Expr::CXXBoolLiteralExprClass:
  11206. case Expr::CXXScalarValueInitExprClass:
  11207. case Expr::TypeTraitExprClass:
  11208. case Expr::ArrayTypeTraitExprClass:
  11209. case Expr::ExpressionTraitExprClass:
  11210. case Expr::CXXNoexceptExprClass:
  11211. return NoDiag();
  11212. case Expr::CallExprClass:
  11213. case Expr::CXXOperatorCallExprClass: {
  11214. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  11215. // constant expressions, but they can never be ICEs because an ICE cannot
  11216. // contain an operand of (pointer to) function type.
  11217. const CallExpr *CE = cast<CallExpr>(E);
  11218. if (CE->getBuiltinCallee())
  11219. return CheckEvalInICE(E, Ctx);
  11220. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11221. }
  11222. case Expr::DeclRefExprClass: {
  11223. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  11224. return NoDiag();
  11225. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  11226. if (Ctx.getLangOpts().CPlusPlus &&
  11227. D && IsConstNonVolatile(D->getType())) {
  11228. // Parameter variables are never constants. Without this check,
  11229. // getAnyInitializer() can find a default argument, which leads
  11230. // to chaos.
  11231. if (isa<ParmVarDecl>(D))
  11232. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11233. // C++ 7.1.5.1p2
  11234. // A variable of non-volatile const-qualified integral or enumeration
  11235. // type initialized by an ICE can be used in ICEs.
  11236. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  11237. if (!Dcl->getType()->isIntegralOrEnumerationType())
  11238. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11239. const VarDecl *VD;
  11240. // Look for a declaration of this variable that has an initializer, and
  11241. // check whether it is an ICE.
  11242. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  11243. return NoDiag();
  11244. else
  11245. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11246. }
  11247. }
  11248. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11249. }
  11250. case Expr::UnaryOperatorClass: {
  11251. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  11252. switch (Exp->getOpcode()) {
  11253. case UO_PostInc:
  11254. case UO_PostDec:
  11255. case UO_PreInc:
  11256. case UO_PreDec:
  11257. case UO_AddrOf:
  11258. case UO_Deref:
  11259. case UO_Coawait:
  11260. // C99 6.6/3 allows increment and decrement within unevaluated
  11261. // subexpressions of constant expressions, but they can never be ICEs
  11262. // because an ICE cannot contain an lvalue operand.
  11263. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11264. case UO_Extension:
  11265. case UO_LNot:
  11266. case UO_Plus:
  11267. case UO_Minus:
  11268. case UO_Not:
  11269. case UO_Real:
  11270. case UO_Imag:
  11271. return CheckICE(Exp->getSubExpr(), Ctx);
  11272. }
  11273. llvm_unreachable("invalid unary operator class");
  11274. }
  11275. case Expr::OffsetOfExprClass: {
  11276. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  11277. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  11278. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  11279. // compliance: we should warn earlier for offsetof expressions with
  11280. // array subscripts that aren't ICEs, and if the array subscripts
  11281. // are ICEs, the value of the offsetof must be an integer constant.
  11282. return CheckEvalInICE(E, Ctx);
  11283. }
  11284. case Expr::UnaryExprOrTypeTraitExprClass: {
  11285. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  11286. if ((Exp->getKind() == UETT_SizeOf) &&
  11287. Exp->getTypeOfArgument()->isVariableArrayType())
  11288. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11289. return NoDiag();
  11290. }
  11291. case Expr::BinaryOperatorClass: {
  11292. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  11293. switch (Exp->getOpcode()) {
  11294. case BO_PtrMemD:
  11295. case BO_PtrMemI:
  11296. case BO_Assign:
  11297. case BO_MulAssign:
  11298. case BO_DivAssign:
  11299. case BO_RemAssign:
  11300. case BO_AddAssign:
  11301. case BO_SubAssign:
  11302. case BO_ShlAssign:
  11303. case BO_ShrAssign:
  11304. case BO_AndAssign:
  11305. case BO_XorAssign:
  11306. case BO_OrAssign:
  11307. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  11308. // constant expressions, but they can never be ICEs because an ICE cannot
  11309. // contain an lvalue operand.
  11310. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11311. case BO_Mul:
  11312. case BO_Div:
  11313. case BO_Rem:
  11314. case BO_Add:
  11315. case BO_Sub:
  11316. case BO_Shl:
  11317. case BO_Shr:
  11318. case BO_LT:
  11319. case BO_GT:
  11320. case BO_LE:
  11321. case BO_GE:
  11322. case BO_EQ:
  11323. case BO_NE:
  11324. case BO_And:
  11325. case BO_Xor:
  11326. case BO_Or:
  11327. case BO_Comma:
  11328. case BO_Cmp: {
  11329. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  11330. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  11331. if (Exp->getOpcode() == BO_Div ||
  11332. Exp->getOpcode() == BO_Rem) {
  11333. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  11334. // we don't evaluate one.
  11335. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  11336. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  11337. if (REval == 0)
  11338. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11339. if (REval.isSigned() && REval.isAllOnesValue()) {
  11340. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  11341. if (LEval.isMinSignedValue())
  11342. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11343. }
  11344. }
  11345. }
  11346. if (Exp->getOpcode() == BO_Comma) {
  11347. if (Ctx.getLangOpts().C99) {
  11348. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  11349. // if it isn't evaluated.
  11350. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  11351. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11352. } else {
  11353. // In both C89 and C++, commas in ICEs are illegal.
  11354. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11355. }
  11356. }
  11357. return Worst(LHSResult, RHSResult);
  11358. }
  11359. case BO_LAnd:
  11360. case BO_LOr: {
  11361. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  11362. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  11363. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  11364. // Rare case where the RHS has a comma "side-effect"; we need
  11365. // to actually check the condition to see whether the side
  11366. // with the comma is evaluated.
  11367. if ((Exp->getOpcode() == BO_LAnd) !=
  11368. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  11369. return RHSResult;
  11370. return NoDiag();
  11371. }
  11372. return Worst(LHSResult, RHSResult);
  11373. }
  11374. }
  11375. llvm_unreachable("invalid binary operator kind");
  11376. }
  11377. case Expr::ImplicitCastExprClass:
  11378. case Expr::CStyleCastExprClass:
  11379. case Expr::CXXFunctionalCastExprClass:
  11380. case Expr::CXXStaticCastExprClass:
  11381. case Expr::CXXReinterpretCastExprClass:
  11382. case Expr::CXXConstCastExprClass:
  11383. case Expr::ObjCBridgedCastExprClass: {
  11384. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  11385. if (isa<ExplicitCastExpr>(E)) {
  11386. if (const FloatingLiteral *FL
  11387. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  11388. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  11389. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  11390. APSInt IgnoredVal(DestWidth, !DestSigned);
  11391. bool Ignored;
  11392. // If the value does not fit in the destination type, the behavior is
  11393. // undefined, so we are not required to treat it as a constant
  11394. // expression.
  11395. if (FL->getValue().convertToInteger(IgnoredVal,
  11396. llvm::APFloat::rmTowardZero,
  11397. &Ignored) & APFloat::opInvalidOp)
  11398. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11399. return NoDiag();
  11400. }
  11401. }
  11402. switch (cast<CastExpr>(E)->getCastKind()) {
  11403. case CK_LValueToRValue:
  11404. case CK_AtomicToNonAtomic:
  11405. case CK_NonAtomicToAtomic:
  11406. case CK_NoOp:
  11407. case CK_IntegralToBoolean:
  11408. case CK_IntegralCast:
  11409. return CheckICE(SubExpr, Ctx);
  11410. default:
  11411. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11412. }
  11413. }
  11414. case Expr::BinaryConditionalOperatorClass: {
  11415. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  11416. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  11417. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  11418. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  11419. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  11420. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  11421. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  11422. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  11423. return FalseResult;
  11424. }
  11425. case Expr::ConditionalOperatorClass: {
  11426. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  11427. // If the condition (ignoring parens) is a __builtin_constant_p call,
  11428. // then only the true side is actually considered in an integer constant
  11429. // expression, and it is fully evaluated. This is an important GNU
  11430. // extension. See GCC PR38377 for discussion.
  11431. if (const CallExpr *CallCE
  11432. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  11433. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  11434. return CheckEvalInICE(E, Ctx);
  11435. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  11436. if (CondResult.Kind == IK_NotICE)
  11437. return CondResult;
  11438. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  11439. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  11440. if (TrueResult.Kind == IK_NotICE)
  11441. return TrueResult;
  11442. if (FalseResult.Kind == IK_NotICE)
  11443. return FalseResult;
  11444. if (CondResult.Kind == IK_ICEIfUnevaluated)
  11445. return CondResult;
  11446. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  11447. return NoDiag();
  11448. // Rare case where the diagnostics depend on which side is evaluated
  11449. // Note that if we get here, CondResult is 0, and at least one of
  11450. // TrueResult and FalseResult is non-zero.
  11451. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  11452. return FalseResult;
  11453. return TrueResult;
  11454. }
  11455. case Expr::CXXDefaultArgExprClass:
  11456. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  11457. case Expr::CXXDefaultInitExprClass:
  11458. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  11459. case Expr::ChooseExprClass: {
  11460. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  11461. }
  11462. case Expr::BuiltinBitCastExprClass: {
  11463. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  11464. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11465. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  11466. }
  11467. }
  11468. llvm_unreachable("Invalid StmtClass!");
  11469. }
  11470. /// Evaluate an expression as a C++11 integral constant expression.
  11471. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  11472. const Expr *E,
  11473. llvm::APSInt *Value,
  11474. SourceLocation *Loc) {
  11475. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  11476. if (Loc) *Loc = E->getExprLoc();
  11477. return false;
  11478. }
  11479. APValue Result;
  11480. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  11481. return false;
  11482. if (!Result.isInt()) {
  11483. if (Loc) *Loc = E->getExprLoc();
  11484. return false;
  11485. }
  11486. if (Value) *Value = Result.getInt();
  11487. return true;
  11488. }
  11489. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  11490. SourceLocation *Loc) const {
  11491. assert(!isValueDependent() &&
  11492. "Expression evaluator can't be called on a dependent expression.");
  11493. if (Ctx.getLangOpts().CPlusPlus11)
  11494. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  11495. ICEDiag D = CheckICE(this, Ctx);
  11496. if (D.Kind != IK_ICE) {
  11497. if (Loc) *Loc = D.Loc;
  11498. return false;
  11499. }
  11500. return true;
  11501. }
  11502. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  11503. SourceLocation *Loc, bool isEvaluated) const {
  11504. assert(!isValueDependent() &&
  11505. "Expression evaluator can't be called on a dependent expression.");
  11506. if (Ctx.getLangOpts().CPlusPlus11)
  11507. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  11508. if (!isIntegerConstantExpr(Ctx, Loc))
  11509. return false;
  11510. // The only possible side-effects here are due to UB discovered in the
  11511. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  11512. // required to treat the expression as an ICE, so we produce the folded
  11513. // value.
  11514. EvalResult ExprResult;
  11515. Expr::EvalStatus Status;
  11516. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  11517. Info.InConstantContext = true;
  11518. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  11519. llvm_unreachable("ICE cannot be evaluated!");
  11520. Value = ExprResult.Val.getInt();
  11521. return true;
  11522. }
  11523. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  11524. assert(!isValueDependent() &&
  11525. "Expression evaluator can't be called on a dependent expression.");
  11526. return CheckICE(this, Ctx).Kind == IK_ICE;
  11527. }
  11528. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  11529. SourceLocation *Loc) const {
  11530. assert(!isValueDependent() &&
  11531. "Expression evaluator can't be called on a dependent expression.");
  11532. // We support this checking in C++98 mode in order to diagnose compatibility
  11533. // issues.
  11534. assert(Ctx.getLangOpts().CPlusPlus);
  11535. // Build evaluation settings.
  11536. Expr::EvalStatus Status;
  11537. SmallVector<PartialDiagnosticAt, 8> Diags;
  11538. Status.Diag = &Diags;
  11539. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11540. APValue Scratch;
  11541. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  11542. if (!Diags.empty()) {
  11543. IsConstExpr = false;
  11544. if (Loc) *Loc = Diags[0].first;
  11545. } else if (!IsConstExpr) {
  11546. // FIXME: This shouldn't happen.
  11547. if (Loc) *Loc = getExprLoc();
  11548. }
  11549. return IsConstExpr;
  11550. }
  11551. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  11552. const FunctionDecl *Callee,
  11553. ArrayRef<const Expr*> Args,
  11554. const Expr *This) const {
  11555. assert(!isValueDependent() &&
  11556. "Expression evaluator can't be called on a dependent expression.");
  11557. Expr::EvalStatus Status;
  11558. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  11559. Info.InConstantContext = true;
  11560. LValue ThisVal;
  11561. const LValue *ThisPtr = nullptr;
  11562. if (This) {
  11563. #ifndef NDEBUG
  11564. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  11565. assert(MD && "Don't provide `this` for non-methods.");
  11566. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  11567. #endif
  11568. if (EvaluateObjectArgument(Info, This, ThisVal))
  11569. ThisPtr = &ThisVal;
  11570. if (Info.EvalStatus.HasSideEffects)
  11571. return false;
  11572. }
  11573. ArgVector ArgValues(Args.size());
  11574. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  11575. I != E; ++I) {
  11576. if ((*I)->isValueDependent() ||
  11577. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  11578. // If evaluation fails, throw away the argument entirely.
  11579. ArgValues[I - Args.begin()] = APValue();
  11580. if (Info.EvalStatus.HasSideEffects)
  11581. return false;
  11582. }
  11583. // Build fake call to Callee.
  11584. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  11585. ArgValues.data());
  11586. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  11587. }
  11588. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  11589. SmallVectorImpl<
  11590. PartialDiagnosticAt> &Diags) {
  11591. // FIXME: It would be useful to check constexpr function templates, but at the
  11592. // moment the constant expression evaluator cannot cope with the non-rigorous
  11593. // ASTs which we build for dependent expressions.
  11594. if (FD->isDependentContext())
  11595. return true;
  11596. Expr::EvalStatus Status;
  11597. Status.Diag = &Diags;
  11598. EvalInfo Info(FD->getASTContext(), Status,
  11599. EvalInfo::EM_PotentialConstantExpression);
  11600. Info.InConstantContext = true;
  11601. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  11602. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  11603. // Fabricate an arbitrary expression on the stack and pretend that it
  11604. // is a temporary being used as the 'this' pointer.
  11605. LValue This;
  11606. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  11607. This.set({&VIE, Info.CurrentCall->Index});
  11608. ArrayRef<const Expr*> Args;
  11609. APValue Scratch;
  11610. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  11611. // Evaluate the call as a constant initializer, to allow the construction
  11612. // of objects of non-literal types.
  11613. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  11614. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  11615. } else {
  11616. SourceLocation Loc = FD->getLocation();
  11617. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  11618. Args, FD->getBody(), Info, Scratch, nullptr);
  11619. }
  11620. return Diags.empty();
  11621. }
  11622. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  11623. const FunctionDecl *FD,
  11624. SmallVectorImpl<
  11625. PartialDiagnosticAt> &Diags) {
  11626. assert(!E->isValueDependent() &&
  11627. "Expression evaluator can't be called on a dependent expression.");
  11628. Expr::EvalStatus Status;
  11629. Status.Diag = &Diags;
  11630. EvalInfo Info(FD->getASTContext(), Status,
  11631. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  11632. Info.InConstantContext = true;
  11633. // Fabricate a call stack frame to give the arguments a plausible cover story.
  11634. ArrayRef<const Expr*> Args;
  11635. ArgVector ArgValues(0);
  11636. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  11637. (void)Success;
  11638. assert(Success &&
  11639. "Failed to set up arguments for potential constant evaluation");
  11640. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  11641. APValue ResultScratch;
  11642. Evaluate(ResultScratch, Info, E);
  11643. return Diags.empty();
  11644. }
  11645. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  11646. unsigned Type) const {
  11647. if (!getType()->isPointerType())
  11648. return false;
  11649. Expr::EvalStatus Status;
  11650. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  11651. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  11652. }