SemaOverload.cpp 625 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580
  1. //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
  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 provides Sema routines for C++ overloading.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/CXXInheritance.h"
  14. #include "clang/AST/DeclCXX.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/DependenceFlags.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/Type.h"
  21. #include "clang/AST/TypeOrdering.h"
  22. #include "clang/Basic/Diagnostic.h"
  23. #include "clang/Basic/DiagnosticOptions.h"
  24. #include "clang/Basic/OperatorKinds.h"
  25. #include "clang/Basic/PartialDiagnostic.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Sema/Initialization.h"
  29. #include "clang/Sema/Lookup.h"
  30. #include "clang/Sema/Overload.h"
  31. #include "clang/Sema/SemaInternal.h"
  32. #include "clang/Sema/Template.h"
  33. #include "clang/Sema/TemplateDeduction.h"
  34. #include "llvm/ADT/DenseSet.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/ADT/SmallPtrSet.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/Support/Casting.h"
  39. #include <algorithm>
  40. #include <cstdlib>
  41. #include <optional>
  42. using namespace clang;
  43. using namespace sema;
  44. using AllowedExplicit = Sema::AllowedExplicit;
  45. static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
  46. return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
  47. return P->hasAttr<PassObjectSizeAttr>();
  48. });
  49. }
  50. /// A convenience routine for creating a decayed reference to a function.
  51. static ExprResult CreateFunctionRefExpr(
  52. Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
  53. bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
  54. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
  55. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  56. return ExprError();
  57. // If FoundDecl is different from Fn (such as if one is a template
  58. // and the other a specialization), make sure DiagnoseUseOfDecl is
  59. // called on both.
  60. // FIXME: This would be more comprehensively addressed by modifying
  61. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  62. // being used.
  63. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  64. return ExprError();
  65. DeclRefExpr *DRE = new (S.Context)
  66. DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
  67. if (HadMultipleCandidates)
  68. DRE->setHadMultipleCandidates(true);
  69. S.MarkDeclRefReferenced(DRE, Base);
  70. if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
  71. if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
  72. S.ResolveExceptionSpec(Loc, FPT);
  73. DRE->setType(Fn->getType());
  74. }
  75. }
  76. return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
  77. CK_FunctionToPointerDecay);
  78. }
  79. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  80. bool InOverloadResolution,
  81. StandardConversionSequence &SCS,
  82. bool CStyle,
  83. bool AllowObjCWritebackConversion);
  84. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  85. QualType &ToType,
  86. bool InOverloadResolution,
  87. StandardConversionSequence &SCS,
  88. bool CStyle);
  89. static OverloadingResult
  90. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  91. UserDefinedConversionSequence& User,
  92. OverloadCandidateSet& Conversions,
  93. AllowedExplicit AllowExplicit,
  94. bool AllowObjCConversionOnExplicit);
  95. static ImplicitConversionSequence::CompareKind
  96. CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
  97. const StandardConversionSequence& SCS1,
  98. const StandardConversionSequence& SCS2);
  99. static ImplicitConversionSequence::CompareKind
  100. CompareQualificationConversions(Sema &S,
  101. const StandardConversionSequence& SCS1,
  102. const StandardConversionSequence& SCS2);
  103. static ImplicitConversionSequence::CompareKind
  104. CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
  105. const StandardConversionSequence& SCS1,
  106. const StandardConversionSequence& SCS2);
  107. /// GetConversionRank - Retrieve the implicit conversion rank
  108. /// corresponding to the given implicit conversion kind.
  109. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  110. static const ImplicitConversionRank
  111. Rank[(int)ICK_Num_Conversion_Kinds] = {
  112. ICR_Exact_Match,
  113. ICR_Exact_Match,
  114. ICR_Exact_Match,
  115. ICR_Exact_Match,
  116. ICR_Exact_Match,
  117. ICR_Exact_Match,
  118. ICR_Promotion,
  119. ICR_Promotion,
  120. ICR_Promotion,
  121. ICR_Conversion,
  122. ICR_Conversion,
  123. ICR_Conversion,
  124. ICR_Conversion,
  125. ICR_Conversion,
  126. ICR_Conversion,
  127. ICR_Conversion,
  128. ICR_Conversion,
  129. ICR_Conversion,
  130. ICR_Conversion,
  131. ICR_Conversion,
  132. ICR_OCL_Scalar_Widening,
  133. ICR_Complex_Real_Conversion,
  134. ICR_Conversion,
  135. ICR_Conversion,
  136. ICR_Writeback_Conversion,
  137. ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
  138. // it was omitted by the patch that added
  139. // ICK_Zero_Event_Conversion
  140. ICR_C_Conversion,
  141. ICR_C_Conversion_Extension
  142. };
  143. return Rank[(int)Kind];
  144. }
  145. /// GetImplicitConversionName - Return the name of this kind of
  146. /// implicit conversion.
  147. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  148. static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
  149. "No conversion",
  150. "Lvalue-to-rvalue",
  151. "Array-to-pointer",
  152. "Function-to-pointer",
  153. "Function pointer conversion",
  154. "Qualification",
  155. "Integral promotion",
  156. "Floating point promotion",
  157. "Complex promotion",
  158. "Integral conversion",
  159. "Floating conversion",
  160. "Complex conversion",
  161. "Floating-integral conversion",
  162. "Pointer conversion",
  163. "Pointer-to-member conversion",
  164. "Boolean conversion",
  165. "Compatible-types conversion",
  166. "Derived-to-base conversion",
  167. "Vector conversion",
  168. "SVE Vector conversion",
  169. "Vector splat",
  170. "Complex-real conversion",
  171. "Block Pointer conversion",
  172. "Transparent Union Conversion",
  173. "Writeback conversion",
  174. "OpenCL Zero Event Conversion",
  175. "C specific type conversion",
  176. "Incompatible pointer conversion"
  177. };
  178. return Name[Kind];
  179. }
  180. /// StandardConversionSequence - Set the standard conversion
  181. /// sequence to the identity conversion.
  182. void StandardConversionSequence::setAsIdentityConversion() {
  183. First = ICK_Identity;
  184. Second = ICK_Identity;
  185. Third = ICK_Identity;
  186. DeprecatedStringLiteralToCharPtr = false;
  187. QualificationIncludesObjCLifetime = false;
  188. ReferenceBinding = false;
  189. DirectBinding = false;
  190. IsLvalueReference = true;
  191. BindsToFunctionLvalue = false;
  192. BindsToRvalue = false;
  193. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  194. ObjCLifetimeConversionBinding = false;
  195. CopyConstructor = nullptr;
  196. }
  197. /// getRank - Retrieve the rank of this standard conversion sequence
  198. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  199. /// implicit conversions.
  200. ImplicitConversionRank StandardConversionSequence::getRank() const {
  201. ImplicitConversionRank Rank = ICR_Exact_Match;
  202. if (GetConversionRank(First) > Rank)
  203. Rank = GetConversionRank(First);
  204. if (GetConversionRank(Second) > Rank)
  205. Rank = GetConversionRank(Second);
  206. if (GetConversionRank(Third) > Rank)
  207. Rank = GetConversionRank(Third);
  208. return Rank;
  209. }
  210. /// isPointerConversionToBool - Determines whether this conversion is
  211. /// a conversion of a pointer or pointer-to-member to bool. This is
  212. /// used as part of the ranking of standard conversion sequences
  213. /// (C++ 13.3.3.2p4).
  214. bool StandardConversionSequence::isPointerConversionToBool() const {
  215. // Note that FromType has not necessarily been transformed by the
  216. // array-to-pointer or function-to-pointer implicit conversions, so
  217. // check for their presence as well as checking whether FromType is
  218. // a pointer.
  219. if (getToType(1)->isBooleanType() &&
  220. (getFromType()->isPointerType() ||
  221. getFromType()->isMemberPointerType() ||
  222. getFromType()->isObjCObjectPointerType() ||
  223. getFromType()->isBlockPointerType() ||
  224. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  225. return true;
  226. return false;
  227. }
  228. /// isPointerConversionToVoidPointer - Determines whether this
  229. /// conversion is a conversion of a pointer to a void pointer. This is
  230. /// used as part of the ranking of standard conversion sequences (C++
  231. /// 13.3.3.2p4).
  232. bool
  233. StandardConversionSequence::
  234. isPointerConversionToVoidPointer(ASTContext& Context) const {
  235. QualType FromType = getFromType();
  236. QualType ToType = getToType(1);
  237. // Note that FromType has not necessarily been transformed by the
  238. // array-to-pointer implicit conversion, so check for its presence
  239. // and redo the conversion to get a pointer.
  240. if (First == ICK_Array_To_Pointer)
  241. FromType = Context.getArrayDecayedType(FromType);
  242. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  243. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  244. return ToPtrType->getPointeeType()->isVoidType();
  245. return false;
  246. }
  247. /// Skip any implicit casts which could be either part of a narrowing conversion
  248. /// or after one in an implicit conversion.
  249. static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
  250. const Expr *Converted) {
  251. // We can have cleanups wrapping the converted expression; these need to be
  252. // preserved so that destructors run if necessary.
  253. if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
  254. Expr *Inner =
  255. const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
  256. return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
  257. EWC->getObjects());
  258. }
  259. while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  260. switch (ICE->getCastKind()) {
  261. case CK_NoOp:
  262. case CK_IntegralCast:
  263. case CK_IntegralToBoolean:
  264. case CK_IntegralToFloating:
  265. case CK_BooleanToSignedIntegral:
  266. case CK_FloatingToIntegral:
  267. case CK_FloatingToBoolean:
  268. case CK_FloatingCast:
  269. Converted = ICE->getSubExpr();
  270. continue;
  271. default:
  272. return Converted;
  273. }
  274. }
  275. return Converted;
  276. }
  277. /// Check if this standard conversion sequence represents a narrowing
  278. /// conversion, according to C++11 [dcl.init.list]p7.
  279. ///
  280. /// \param Ctx The AST context.
  281. /// \param Converted The result of applying this standard conversion sequence.
  282. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  283. /// value of the expression prior to the narrowing conversion.
  284. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  285. /// type of the expression prior to the narrowing conversion.
  286. /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
  287. /// from floating point types to integral types should be ignored.
  288. NarrowingKind StandardConversionSequence::getNarrowingKind(
  289. ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
  290. QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
  291. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  292. // C++11 [dcl.init.list]p7:
  293. // A narrowing conversion is an implicit conversion ...
  294. QualType FromType = getToType(0);
  295. QualType ToType = getToType(1);
  296. // A conversion to an enumeration type is narrowing if the conversion to
  297. // the underlying type is narrowing. This only arises for expressions of
  298. // the form 'Enum{init}'.
  299. if (auto *ET = ToType->getAs<EnumType>())
  300. ToType = ET->getDecl()->getIntegerType();
  301. switch (Second) {
  302. // 'bool' is an integral type; dispatch to the right place to handle it.
  303. case ICK_Boolean_Conversion:
  304. if (FromType->isRealFloatingType())
  305. goto FloatingIntegralConversion;
  306. if (FromType->isIntegralOrUnscopedEnumerationType())
  307. goto IntegralConversion;
  308. // -- from a pointer type or pointer-to-member type to bool, or
  309. return NK_Type_Narrowing;
  310. // -- from a floating-point type to an integer type, or
  311. //
  312. // -- from an integer type or unscoped enumeration type to a floating-point
  313. // type, except where the source is a constant expression and the actual
  314. // value after conversion will fit into the target type and will produce
  315. // the original value when converted back to the original type, or
  316. case ICK_Floating_Integral:
  317. FloatingIntegralConversion:
  318. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  319. return NK_Type_Narrowing;
  320. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  321. ToType->isRealFloatingType()) {
  322. if (IgnoreFloatToIntegralConversion)
  323. return NK_Not_Narrowing;
  324. const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
  325. assert(Initializer && "Unknown conversion expression");
  326. // If it's value-dependent, we can't tell whether it's narrowing.
  327. if (Initializer->isValueDependent())
  328. return NK_Dependent_Narrowing;
  329. if (std::optional<llvm::APSInt> IntConstantValue =
  330. Initializer->getIntegerConstantExpr(Ctx)) {
  331. // Convert the integer to the floating type.
  332. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  333. Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
  334. llvm::APFloat::rmNearestTiesToEven);
  335. // And back.
  336. llvm::APSInt ConvertedValue = *IntConstantValue;
  337. bool ignored;
  338. Result.convertToInteger(ConvertedValue,
  339. llvm::APFloat::rmTowardZero, &ignored);
  340. // If the resulting value is different, this was a narrowing conversion.
  341. if (*IntConstantValue != ConvertedValue) {
  342. ConstantValue = APValue(*IntConstantValue);
  343. ConstantType = Initializer->getType();
  344. return NK_Constant_Narrowing;
  345. }
  346. } else {
  347. // Variables are always narrowings.
  348. return NK_Variable_Narrowing;
  349. }
  350. }
  351. return NK_Not_Narrowing;
  352. // -- from long double to double or float, or from double to float, except
  353. // where the source is a constant expression and the actual value after
  354. // conversion is within the range of values that can be represented (even
  355. // if it cannot be represented exactly), or
  356. case ICK_Floating_Conversion:
  357. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  358. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  359. // FromType is larger than ToType.
  360. const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
  361. // If it's value-dependent, we can't tell whether it's narrowing.
  362. if (Initializer->isValueDependent())
  363. return NK_Dependent_Narrowing;
  364. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  365. // Constant!
  366. assert(ConstantValue.isFloat());
  367. llvm::APFloat FloatVal = ConstantValue.getFloat();
  368. // Convert the source value into the target type.
  369. bool ignored;
  370. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  371. Ctx.getFloatTypeSemantics(ToType),
  372. llvm::APFloat::rmNearestTiesToEven, &ignored);
  373. // If there was no overflow, the source value is within the range of
  374. // values that can be represented.
  375. if (ConvertStatus & llvm::APFloat::opOverflow) {
  376. ConstantType = Initializer->getType();
  377. return NK_Constant_Narrowing;
  378. }
  379. } else {
  380. return NK_Variable_Narrowing;
  381. }
  382. }
  383. return NK_Not_Narrowing;
  384. // -- from an integer type or unscoped enumeration type to an integer type
  385. // that cannot represent all the values of the original type, except where
  386. // the source is a constant expression and the actual value after
  387. // conversion will fit into the target type and will produce the original
  388. // value when converted back to the original type.
  389. case ICK_Integral_Conversion:
  390. IntegralConversion: {
  391. assert(FromType->isIntegralOrUnscopedEnumerationType());
  392. assert(ToType->isIntegralOrUnscopedEnumerationType());
  393. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  394. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  395. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  396. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  397. if (FromWidth > ToWidth ||
  398. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  399. (FromSigned && !ToSigned)) {
  400. // Not all values of FromType can be represented in ToType.
  401. const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
  402. // If it's value-dependent, we can't tell whether it's narrowing.
  403. if (Initializer->isValueDependent())
  404. return NK_Dependent_Narrowing;
  405. std::optional<llvm::APSInt> OptInitializerValue;
  406. if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
  407. // Such conversions on variables are always narrowing.
  408. return NK_Variable_Narrowing;
  409. }
  410. llvm::APSInt &InitializerValue = *OptInitializerValue;
  411. bool Narrowing = false;
  412. if (FromWidth < ToWidth) {
  413. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  414. // narrowing.
  415. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  416. Narrowing = true;
  417. } else {
  418. // Add a bit to the InitializerValue so we don't have to worry about
  419. // signed vs. unsigned comparisons.
  420. InitializerValue = InitializerValue.extend(
  421. InitializerValue.getBitWidth() + 1);
  422. // Convert the initializer to and from the target width and signed-ness.
  423. llvm::APSInt ConvertedValue = InitializerValue;
  424. ConvertedValue = ConvertedValue.trunc(ToWidth);
  425. ConvertedValue.setIsSigned(ToSigned);
  426. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  427. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  428. // If the result is different, this was a narrowing conversion.
  429. if (ConvertedValue != InitializerValue)
  430. Narrowing = true;
  431. }
  432. if (Narrowing) {
  433. ConstantType = Initializer->getType();
  434. ConstantValue = APValue(InitializerValue);
  435. return NK_Constant_Narrowing;
  436. }
  437. }
  438. return NK_Not_Narrowing;
  439. }
  440. default:
  441. // Other kinds of conversions are not narrowings.
  442. return NK_Not_Narrowing;
  443. }
  444. }
  445. /// dump - Print this standard conversion sequence to standard
  446. /// error. Useful for debugging overloading issues.
  447. LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
  448. raw_ostream &OS = llvm::errs();
  449. bool PrintedSomething = false;
  450. if (First != ICK_Identity) {
  451. OS << GetImplicitConversionName(First);
  452. PrintedSomething = true;
  453. }
  454. if (Second != ICK_Identity) {
  455. if (PrintedSomething) {
  456. OS << " -> ";
  457. }
  458. OS << GetImplicitConversionName(Second);
  459. if (CopyConstructor) {
  460. OS << " (by copy constructor)";
  461. } else if (DirectBinding) {
  462. OS << " (direct reference binding)";
  463. } else if (ReferenceBinding) {
  464. OS << " (reference binding)";
  465. }
  466. PrintedSomething = true;
  467. }
  468. if (Third != ICK_Identity) {
  469. if (PrintedSomething) {
  470. OS << " -> ";
  471. }
  472. OS << GetImplicitConversionName(Third);
  473. PrintedSomething = true;
  474. }
  475. if (!PrintedSomething) {
  476. OS << "No conversions required";
  477. }
  478. }
  479. /// dump - Print this user-defined conversion sequence to standard
  480. /// error. Useful for debugging overloading issues.
  481. void UserDefinedConversionSequence::dump() const {
  482. raw_ostream &OS = llvm::errs();
  483. if (Before.First || Before.Second || Before.Third) {
  484. Before.dump();
  485. OS << " -> ";
  486. }
  487. if (ConversionFunction)
  488. OS << '\'' << *ConversionFunction << '\'';
  489. else
  490. OS << "aggregate initialization";
  491. if (After.First || After.Second || After.Third) {
  492. OS << " -> ";
  493. After.dump();
  494. }
  495. }
  496. /// dump - Print this implicit conversion sequence to standard
  497. /// error. Useful for debugging overloading issues.
  498. void ImplicitConversionSequence::dump() const {
  499. raw_ostream &OS = llvm::errs();
  500. if (hasInitializerListContainerType())
  501. OS << "Worst list element conversion: ";
  502. switch (ConversionKind) {
  503. case StandardConversion:
  504. OS << "Standard conversion: ";
  505. Standard.dump();
  506. break;
  507. case UserDefinedConversion:
  508. OS << "User-defined conversion: ";
  509. UserDefined.dump();
  510. break;
  511. case EllipsisConversion:
  512. OS << "Ellipsis conversion";
  513. break;
  514. case AmbiguousConversion:
  515. OS << "Ambiguous conversion";
  516. break;
  517. case BadConversion:
  518. OS << "Bad conversion";
  519. break;
  520. }
  521. OS << "\n";
  522. }
  523. void AmbiguousConversionSequence::construct() {
  524. new (&conversions()) ConversionSet();
  525. }
  526. void AmbiguousConversionSequence::destruct() {
  527. conversions().~ConversionSet();
  528. }
  529. void
  530. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  531. FromTypePtr = O.FromTypePtr;
  532. ToTypePtr = O.ToTypePtr;
  533. new (&conversions()) ConversionSet(O.conversions());
  534. }
  535. namespace {
  536. // Structure used by DeductionFailureInfo to store
  537. // template argument information.
  538. struct DFIArguments {
  539. TemplateArgument FirstArg;
  540. TemplateArgument SecondArg;
  541. };
  542. // Structure used by DeductionFailureInfo to store
  543. // template parameter and template argument information.
  544. struct DFIParamWithArguments : DFIArguments {
  545. TemplateParameter Param;
  546. };
  547. // Structure used by DeductionFailureInfo to store template argument
  548. // information and the index of the problematic call argument.
  549. struct DFIDeducedMismatchArgs : DFIArguments {
  550. TemplateArgumentList *TemplateArgs;
  551. unsigned CallArgIndex;
  552. };
  553. // Structure used by DeductionFailureInfo to store information about
  554. // unsatisfied constraints.
  555. struct CNSInfo {
  556. TemplateArgumentList *TemplateArgs;
  557. ConstraintSatisfaction Satisfaction;
  558. };
  559. }
  560. /// Convert from Sema's representation of template deduction information
  561. /// to the form used in overload-candidate information.
  562. DeductionFailureInfo
  563. clang::MakeDeductionFailureInfo(ASTContext &Context,
  564. Sema::TemplateDeductionResult TDK,
  565. TemplateDeductionInfo &Info) {
  566. DeductionFailureInfo Result;
  567. Result.Result = static_cast<unsigned>(TDK);
  568. Result.HasDiagnostic = false;
  569. switch (TDK) {
  570. case Sema::TDK_Invalid:
  571. case Sema::TDK_InstantiationDepth:
  572. case Sema::TDK_TooManyArguments:
  573. case Sema::TDK_TooFewArguments:
  574. case Sema::TDK_MiscellaneousDeductionFailure:
  575. case Sema::TDK_CUDATargetMismatch:
  576. Result.Data = nullptr;
  577. break;
  578. case Sema::TDK_Incomplete:
  579. case Sema::TDK_InvalidExplicitArguments:
  580. Result.Data = Info.Param.getOpaqueValue();
  581. break;
  582. case Sema::TDK_DeducedMismatch:
  583. case Sema::TDK_DeducedMismatchNested: {
  584. // FIXME: Should allocate from normal heap so that we can free this later.
  585. auto *Saved = new (Context) DFIDeducedMismatchArgs;
  586. Saved->FirstArg = Info.FirstArg;
  587. Saved->SecondArg = Info.SecondArg;
  588. Saved->TemplateArgs = Info.takeSugared();
  589. Saved->CallArgIndex = Info.CallArgIndex;
  590. Result.Data = Saved;
  591. break;
  592. }
  593. case Sema::TDK_NonDeducedMismatch: {
  594. // FIXME: Should allocate from normal heap so that we can free this later.
  595. DFIArguments *Saved = new (Context) DFIArguments;
  596. Saved->FirstArg = Info.FirstArg;
  597. Saved->SecondArg = Info.SecondArg;
  598. Result.Data = Saved;
  599. break;
  600. }
  601. case Sema::TDK_IncompletePack:
  602. // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
  603. case Sema::TDK_Inconsistent:
  604. case Sema::TDK_Underqualified: {
  605. // FIXME: Should allocate from normal heap so that we can free this later.
  606. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  607. Saved->Param = Info.Param;
  608. Saved->FirstArg = Info.FirstArg;
  609. Saved->SecondArg = Info.SecondArg;
  610. Result.Data = Saved;
  611. break;
  612. }
  613. case Sema::TDK_SubstitutionFailure:
  614. Result.Data = Info.takeSugared();
  615. if (Info.hasSFINAEDiagnostic()) {
  616. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  617. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  618. Info.takeSFINAEDiagnostic(*Diag);
  619. Result.HasDiagnostic = true;
  620. }
  621. break;
  622. case Sema::TDK_ConstraintsNotSatisfied: {
  623. CNSInfo *Saved = new (Context) CNSInfo;
  624. Saved->TemplateArgs = Info.takeSugared();
  625. Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
  626. Result.Data = Saved;
  627. break;
  628. }
  629. case Sema::TDK_Success:
  630. case Sema::TDK_NonDependentConversionFailure:
  631. case Sema::TDK_AlreadyDiagnosed:
  632. llvm_unreachable("not a deduction failure");
  633. }
  634. return Result;
  635. }
  636. void DeductionFailureInfo::Destroy() {
  637. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  638. case Sema::TDK_Success:
  639. case Sema::TDK_Invalid:
  640. case Sema::TDK_InstantiationDepth:
  641. case Sema::TDK_Incomplete:
  642. case Sema::TDK_TooManyArguments:
  643. case Sema::TDK_TooFewArguments:
  644. case Sema::TDK_InvalidExplicitArguments:
  645. case Sema::TDK_CUDATargetMismatch:
  646. case Sema::TDK_NonDependentConversionFailure:
  647. break;
  648. case Sema::TDK_IncompletePack:
  649. case Sema::TDK_Inconsistent:
  650. case Sema::TDK_Underqualified:
  651. case Sema::TDK_DeducedMismatch:
  652. case Sema::TDK_DeducedMismatchNested:
  653. case Sema::TDK_NonDeducedMismatch:
  654. // FIXME: Destroy the data?
  655. Data = nullptr;
  656. break;
  657. case Sema::TDK_SubstitutionFailure:
  658. // FIXME: Destroy the template argument list?
  659. Data = nullptr;
  660. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  661. Diag->~PartialDiagnosticAt();
  662. HasDiagnostic = false;
  663. }
  664. break;
  665. case Sema::TDK_ConstraintsNotSatisfied:
  666. // FIXME: Destroy the template argument list?
  667. Data = nullptr;
  668. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  669. Diag->~PartialDiagnosticAt();
  670. HasDiagnostic = false;
  671. }
  672. break;
  673. // Unhandled
  674. case Sema::TDK_MiscellaneousDeductionFailure:
  675. case Sema::TDK_AlreadyDiagnosed:
  676. break;
  677. }
  678. }
  679. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  680. if (HasDiagnostic)
  681. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  682. return nullptr;
  683. }
  684. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  685. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  686. case Sema::TDK_Success:
  687. case Sema::TDK_Invalid:
  688. case Sema::TDK_InstantiationDepth:
  689. case Sema::TDK_TooManyArguments:
  690. case Sema::TDK_TooFewArguments:
  691. case Sema::TDK_SubstitutionFailure:
  692. case Sema::TDK_DeducedMismatch:
  693. case Sema::TDK_DeducedMismatchNested:
  694. case Sema::TDK_NonDeducedMismatch:
  695. case Sema::TDK_CUDATargetMismatch:
  696. case Sema::TDK_NonDependentConversionFailure:
  697. case Sema::TDK_ConstraintsNotSatisfied:
  698. return TemplateParameter();
  699. case Sema::TDK_Incomplete:
  700. case Sema::TDK_InvalidExplicitArguments:
  701. return TemplateParameter::getFromOpaqueValue(Data);
  702. case Sema::TDK_IncompletePack:
  703. case Sema::TDK_Inconsistent:
  704. case Sema::TDK_Underqualified:
  705. return static_cast<DFIParamWithArguments*>(Data)->Param;
  706. // Unhandled
  707. case Sema::TDK_MiscellaneousDeductionFailure:
  708. case Sema::TDK_AlreadyDiagnosed:
  709. break;
  710. }
  711. return TemplateParameter();
  712. }
  713. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  714. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  715. case Sema::TDK_Success:
  716. case Sema::TDK_Invalid:
  717. case Sema::TDK_InstantiationDepth:
  718. case Sema::TDK_TooManyArguments:
  719. case Sema::TDK_TooFewArguments:
  720. case Sema::TDK_Incomplete:
  721. case Sema::TDK_IncompletePack:
  722. case Sema::TDK_InvalidExplicitArguments:
  723. case Sema::TDK_Inconsistent:
  724. case Sema::TDK_Underqualified:
  725. case Sema::TDK_NonDeducedMismatch:
  726. case Sema::TDK_CUDATargetMismatch:
  727. case Sema::TDK_NonDependentConversionFailure:
  728. return nullptr;
  729. case Sema::TDK_DeducedMismatch:
  730. case Sema::TDK_DeducedMismatchNested:
  731. return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
  732. case Sema::TDK_SubstitutionFailure:
  733. return static_cast<TemplateArgumentList*>(Data);
  734. case Sema::TDK_ConstraintsNotSatisfied:
  735. return static_cast<CNSInfo*>(Data)->TemplateArgs;
  736. // Unhandled
  737. case Sema::TDK_MiscellaneousDeductionFailure:
  738. case Sema::TDK_AlreadyDiagnosed:
  739. break;
  740. }
  741. return nullptr;
  742. }
  743. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  744. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  745. case Sema::TDK_Success:
  746. case Sema::TDK_Invalid:
  747. case Sema::TDK_InstantiationDepth:
  748. case Sema::TDK_Incomplete:
  749. case Sema::TDK_TooManyArguments:
  750. case Sema::TDK_TooFewArguments:
  751. case Sema::TDK_InvalidExplicitArguments:
  752. case Sema::TDK_SubstitutionFailure:
  753. case Sema::TDK_CUDATargetMismatch:
  754. case Sema::TDK_NonDependentConversionFailure:
  755. case Sema::TDK_ConstraintsNotSatisfied:
  756. return nullptr;
  757. case Sema::TDK_IncompletePack:
  758. case Sema::TDK_Inconsistent:
  759. case Sema::TDK_Underqualified:
  760. case Sema::TDK_DeducedMismatch:
  761. case Sema::TDK_DeducedMismatchNested:
  762. case Sema::TDK_NonDeducedMismatch:
  763. return &static_cast<DFIArguments*>(Data)->FirstArg;
  764. // Unhandled
  765. case Sema::TDK_MiscellaneousDeductionFailure:
  766. case Sema::TDK_AlreadyDiagnosed:
  767. break;
  768. }
  769. return nullptr;
  770. }
  771. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  772. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  773. case Sema::TDK_Success:
  774. case Sema::TDK_Invalid:
  775. case Sema::TDK_InstantiationDepth:
  776. case Sema::TDK_Incomplete:
  777. case Sema::TDK_IncompletePack:
  778. case Sema::TDK_TooManyArguments:
  779. case Sema::TDK_TooFewArguments:
  780. case Sema::TDK_InvalidExplicitArguments:
  781. case Sema::TDK_SubstitutionFailure:
  782. case Sema::TDK_CUDATargetMismatch:
  783. case Sema::TDK_NonDependentConversionFailure:
  784. case Sema::TDK_ConstraintsNotSatisfied:
  785. return nullptr;
  786. case Sema::TDK_Inconsistent:
  787. case Sema::TDK_Underqualified:
  788. case Sema::TDK_DeducedMismatch:
  789. case Sema::TDK_DeducedMismatchNested:
  790. case Sema::TDK_NonDeducedMismatch:
  791. return &static_cast<DFIArguments*>(Data)->SecondArg;
  792. // Unhandled
  793. case Sema::TDK_MiscellaneousDeductionFailure:
  794. case Sema::TDK_AlreadyDiagnosed:
  795. break;
  796. }
  797. return nullptr;
  798. }
  799. std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
  800. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  801. case Sema::TDK_DeducedMismatch:
  802. case Sema::TDK_DeducedMismatchNested:
  803. return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
  804. default:
  805. return std::nullopt;
  806. }
  807. }
  808. static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
  809. const FunctionDecl *Y) {
  810. if (!X || !Y)
  811. return false;
  812. if (X->getNumParams() != Y->getNumParams())
  813. return false;
  814. for (unsigned I = 0; I < X->getNumParams(); ++I)
  815. if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
  816. Y->getParamDecl(I)->getType()))
  817. return false;
  818. if (auto *FTX = X->getDescribedFunctionTemplate()) {
  819. auto *FTY = Y->getDescribedFunctionTemplate();
  820. if (!FTY)
  821. return false;
  822. if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
  823. FTY->getTemplateParameters()))
  824. return false;
  825. }
  826. return true;
  827. }
  828. static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
  829. Expr *FirstOperand, FunctionDecl *EqFD) {
  830. assert(EqFD->getOverloadedOperator() ==
  831. OverloadedOperatorKind::OO_EqualEqual);
  832. // C++2a [over.match.oper]p4:
  833. // A non-template function or function template F named operator== is a
  834. // rewrite target with first operand o unless a search for the name operator!=
  835. // in the scope S from the instantiation context of the operator expression
  836. // finds a function or function template that would correspond
  837. // ([basic.scope.scope]) to F if its name were operator==, where S is the
  838. // scope of the class type of o if F is a class member, and the namespace
  839. // scope of which F is a member otherwise. A function template specialization
  840. // named operator== is a rewrite target if its function template is a rewrite
  841. // target.
  842. DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
  843. OverloadedOperatorKind::OO_ExclaimEqual);
  844. if (isa<CXXMethodDecl>(EqFD)) {
  845. // If F is a class member, search scope is class type of first operand.
  846. QualType RHS = FirstOperand->getType();
  847. auto *RHSRec = RHS->getAs<RecordType>();
  848. if (!RHSRec)
  849. return true;
  850. LookupResult Members(S, NotEqOp, OpLoc,
  851. Sema::LookupNameKind::LookupMemberName);
  852. S.LookupQualifiedName(Members, RHSRec->getDecl());
  853. Members.suppressDiagnostics();
  854. for (NamedDecl *Op : Members)
  855. if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
  856. return false;
  857. return true;
  858. }
  859. // Otherwise the search scope is the namespace scope of which F is a member.
  860. LookupResult NonMembers(S, NotEqOp, OpLoc,
  861. Sema::LookupNameKind::LookupOperatorName);
  862. S.LookupName(NonMembers,
  863. S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
  864. NonMembers.suppressDiagnostics();
  865. for (NamedDecl *Op : NonMembers) {
  866. auto *FD = Op->getAsFunction();
  867. if(auto* UD = dyn_cast<UsingShadowDecl>(Op))
  868. FD = UD->getUnderlyingDecl()->getAsFunction();
  869. if (FunctionsCorrespond(S.Context, EqFD, FD) &&
  870. declaresSameEntity(cast<Decl>(EqFD->getDeclContext()),
  871. cast<Decl>(Op->getDeclContext())))
  872. return false;
  873. }
  874. return true;
  875. }
  876. bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
  877. OverloadedOperatorKind Op) {
  878. if (!AllowRewrittenCandidates)
  879. return false;
  880. return Op == OO_EqualEqual || Op == OO_Spaceship;
  881. }
  882. bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
  883. Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
  884. auto Op = FD->getOverloadedOperator();
  885. if (!allowsReversed(Op))
  886. return false;
  887. if (Op == OverloadedOperatorKind::OO_EqualEqual) {
  888. assert(OriginalArgs.size() == 2);
  889. if (!shouldAddReversedEqEq(
  890. S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
  891. return false;
  892. }
  893. // Don't bother adding a reversed candidate that can never be a better
  894. // match than the non-reversed version.
  895. return FD->getNumParams() != 2 ||
  896. !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
  897. FD->getParamDecl(1)->getType()) ||
  898. FD->hasAttr<EnableIfAttr>();
  899. }
  900. void OverloadCandidateSet::destroyCandidates() {
  901. for (iterator i = begin(), e = end(); i != e; ++i) {
  902. for (auto &C : i->Conversions)
  903. C.~ImplicitConversionSequence();
  904. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  905. i->DeductionFailure.Destroy();
  906. }
  907. }
  908. void OverloadCandidateSet::clear(CandidateSetKind CSK) {
  909. destroyCandidates();
  910. SlabAllocator.Reset();
  911. NumInlineBytesUsed = 0;
  912. Candidates.clear();
  913. Functions.clear();
  914. Kind = CSK;
  915. }
  916. namespace {
  917. class UnbridgedCastsSet {
  918. struct Entry {
  919. Expr **Addr;
  920. Expr *Saved;
  921. };
  922. SmallVector<Entry, 2> Entries;
  923. public:
  924. void save(Sema &S, Expr *&E) {
  925. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  926. Entry entry = { &E, E };
  927. Entries.push_back(entry);
  928. E = S.stripARCUnbridgedCast(E);
  929. }
  930. void restore() {
  931. for (SmallVectorImpl<Entry>::iterator
  932. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  933. *i->Addr = i->Saved;
  934. }
  935. };
  936. }
  937. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  938. /// preprocessing on the given expression.
  939. ///
  940. /// \param unbridgedCasts a collection to which to add unbridged casts;
  941. /// without this, they will be immediately diagnosed as errors
  942. ///
  943. /// Return true on unrecoverable error.
  944. static bool
  945. checkPlaceholderForOverload(Sema &S, Expr *&E,
  946. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  947. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  948. // We can't handle overloaded expressions here because overload
  949. // resolution might reasonably tweak them.
  950. if (placeholder->getKind() == BuiltinType::Overload) return false;
  951. // If the context potentially accepts unbridged ARC casts, strip
  952. // the unbridged cast and add it to the collection for later restoration.
  953. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  954. unbridgedCasts) {
  955. unbridgedCasts->save(S, E);
  956. return false;
  957. }
  958. // Go ahead and check everything else.
  959. ExprResult result = S.CheckPlaceholderExpr(E);
  960. if (result.isInvalid())
  961. return true;
  962. E = result.get();
  963. return false;
  964. }
  965. // Nothing to do.
  966. return false;
  967. }
  968. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  969. /// placeholders.
  970. static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
  971. UnbridgedCastsSet &unbridged) {
  972. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  973. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  974. return true;
  975. return false;
  976. }
  977. /// Determine whether the given New declaration is an overload of the
  978. /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
  979. /// New and Old cannot be overloaded, e.g., if New has the same signature as
  980. /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
  981. /// functions (or function templates) at all. When it does return Ovl_Match or
  982. /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
  983. /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
  984. /// declaration.
  985. ///
  986. /// Example: Given the following input:
  987. ///
  988. /// void f(int, float); // #1
  989. /// void f(int, int); // #2
  990. /// int f(int, int); // #3
  991. ///
  992. /// When we process #1, there is no previous declaration of "f", so IsOverload
  993. /// will not be used.
  994. ///
  995. /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
  996. /// the parameter types, we see that #1 and #2 are overloaded (since they have
  997. /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
  998. /// unchanged.
  999. ///
  1000. /// When we process #3, Old is an overload set containing #1 and #2. We compare
  1001. /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
  1002. /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
  1003. /// functions are not part of the signature), IsOverload returns Ovl_Match and
  1004. /// MatchedDecl will be set to point to the FunctionDecl for #2.
  1005. ///
  1006. /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
  1007. /// by a using declaration. The rules for whether to hide shadow declarations
  1008. /// ignore some properties which otherwise figure into a function template's
  1009. /// signature.
  1010. Sema::OverloadKind
  1011. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  1012. NamedDecl *&Match, bool NewIsUsingDecl) {
  1013. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  1014. I != E; ++I) {
  1015. NamedDecl *OldD = *I;
  1016. bool OldIsUsingDecl = false;
  1017. if (isa<UsingShadowDecl>(OldD)) {
  1018. OldIsUsingDecl = true;
  1019. // We can always introduce two using declarations into the same
  1020. // context, even if they have identical signatures.
  1021. if (NewIsUsingDecl) continue;
  1022. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  1023. }
  1024. // A using-declaration does not conflict with another declaration
  1025. // if one of them is hidden.
  1026. if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
  1027. continue;
  1028. // If either declaration was introduced by a using declaration,
  1029. // we'll need to use slightly different rules for matching.
  1030. // Essentially, these rules are the normal rules, except that
  1031. // function templates hide function templates with different
  1032. // return types or template parameter lists.
  1033. bool UseMemberUsingDeclRules =
  1034. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  1035. !New->getFriendObjectKind();
  1036. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  1037. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  1038. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  1039. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  1040. continue;
  1041. }
  1042. if (!isa<FunctionTemplateDecl>(OldD) &&
  1043. !shouldLinkPossiblyHiddenDecl(*I, New))
  1044. continue;
  1045. // C++20 [temp.friend] p9: A non-template friend declaration with a
  1046. // requires-clause shall be a definition. A friend function template
  1047. // with a constraint that depends on a template parameter from an
  1048. // enclosing template shall be a definition. Such a constrained friend
  1049. // function or function template declaration does not declare the same
  1050. // function or function template as a declaration in any other scope.
  1051. if (Context.FriendsDifferByConstraints(OldF, New))
  1052. continue;
  1053. Match = *I;
  1054. return Ovl_Match;
  1055. }
  1056. // Builtins that have custom typechecking or have a reference should
  1057. // not be overloadable or redeclarable.
  1058. if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
  1059. Match = *I;
  1060. return Ovl_NonFunction;
  1061. }
  1062. } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
  1063. // We can overload with these, which can show up when doing
  1064. // redeclaration checks for UsingDecls.
  1065. assert(Old.getLookupKind() == LookupUsingDeclName);
  1066. } else if (isa<TagDecl>(OldD)) {
  1067. // We can always overload with tags by hiding them.
  1068. } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
  1069. // Optimistically assume that an unresolved using decl will
  1070. // overload; if it doesn't, we'll have to diagnose during
  1071. // template instantiation.
  1072. //
  1073. // Exception: if the scope is dependent and this is not a class
  1074. // member, the using declaration can only introduce an enumerator.
  1075. if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
  1076. Match = *I;
  1077. return Ovl_NonFunction;
  1078. }
  1079. } else {
  1080. // (C++ 13p1):
  1081. // Only function declarations can be overloaded; object and type
  1082. // declarations cannot be overloaded.
  1083. Match = *I;
  1084. return Ovl_NonFunction;
  1085. }
  1086. }
  1087. // C++ [temp.friend]p1:
  1088. // For a friend function declaration that is not a template declaration:
  1089. // -- if the name of the friend is a qualified or unqualified template-id,
  1090. // [...], otherwise
  1091. // -- if the name of the friend is a qualified-id and a matching
  1092. // non-template function is found in the specified class or namespace,
  1093. // the friend declaration refers to that function, otherwise,
  1094. // -- if the name of the friend is a qualified-id and a matching function
  1095. // template is found in the specified class or namespace, the friend
  1096. // declaration refers to the deduced specialization of that function
  1097. // template, otherwise
  1098. // -- the name shall be an unqualified-id [...]
  1099. // If we get here for a qualified friend declaration, we've just reached the
  1100. // third bullet. If the type of the friend is dependent, skip this lookup
  1101. // until instantiation.
  1102. if (New->getFriendObjectKind() && New->getQualifier() &&
  1103. !New->getDescribedFunctionTemplate() &&
  1104. !New->getDependentSpecializationInfo() &&
  1105. !New->getType()->isDependentType()) {
  1106. LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
  1107. TemplateSpecResult.addAllDecls(Old);
  1108. if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
  1109. /*QualifiedFriend*/true)) {
  1110. New->setInvalidDecl();
  1111. return Ovl_Overload;
  1112. }
  1113. Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
  1114. return Ovl_Match;
  1115. }
  1116. return Ovl_Overload;
  1117. }
  1118. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  1119. bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
  1120. bool ConsiderRequiresClauses) {
  1121. // C++ [basic.start.main]p2: This function shall not be overloaded.
  1122. if (New->isMain())
  1123. return false;
  1124. // MSVCRT user defined entry points cannot be overloaded.
  1125. if (New->isMSVCRTEntryPoint())
  1126. return false;
  1127. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  1128. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  1129. // C++ [temp.fct]p2:
  1130. // A function template can be overloaded with other function templates
  1131. // and with normal (non-template) functions.
  1132. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  1133. return true;
  1134. // Is the function New an overload of the function Old?
  1135. QualType OldQType = Context.getCanonicalType(Old->getType());
  1136. QualType NewQType = Context.getCanonicalType(New->getType());
  1137. // Compare the signatures (C++ 1.3.10) of the two functions to
  1138. // determine whether they are overloads. If we find any mismatch
  1139. // in the signature, they are overloads.
  1140. // If either of these functions is a K&R-style function (no
  1141. // prototype), then we consider them to have matching signatures.
  1142. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  1143. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  1144. return false;
  1145. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  1146. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  1147. // The signature of a function includes the types of its
  1148. // parameters (C++ 1.3.10), which includes the presence or absence
  1149. // of the ellipsis; see C++ DR 357).
  1150. if (OldQType != NewQType &&
  1151. (OldType->getNumParams() != NewType->getNumParams() ||
  1152. OldType->isVariadic() != NewType->isVariadic() ||
  1153. !FunctionParamTypesAreEqual(OldType, NewType)))
  1154. return true;
  1155. if (NewTemplate) {
  1156. // C++ [temp.over.link]p4:
  1157. // The signature of a function template consists of its function
  1158. // signature, its return type and its template parameter list. The names
  1159. // of the template parameters are significant only for establishing the
  1160. // relationship between the template parameters and the rest of the
  1161. // signature.
  1162. //
  1163. // We check the return type and template parameter lists for function
  1164. // templates first; the remaining checks follow.
  1165. bool SameTemplateParameterList = TemplateParameterListsAreEqual(
  1166. NewTemplate->getTemplateParameters(),
  1167. OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
  1168. bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
  1169. New->getDeclaredReturnType());
  1170. // FIXME(GH58571): Match template parameter list even for non-constrained
  1171. // template heads. This currently ensures that the code prior to C++20 is
  1172. // not newly broken.
  1173. bool ConstraintsInTemplateHead =
  1174. NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
  1175. OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
  1176. // C++ [namespace.udecl]p11:
  1177. // The set of declarations named by a using-declarator that inhabits a
  1178. // class C does not include member functions and member function
  1179. // templates of a base class that "correspond" to (and thus would
  1180. // conflict with) a declaration of a function or function template in
  1181. // C.
  1182. // Comparing return types is not required for the "correspond" check to
  1183. // decide whether a member introduced by a shadow declaration is hidden.
  1184. if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
  1185. !SameTemplateParameterList)
  1186. return true;
  1187. if (!UseMemberUsingDeclRules &&
  1188. (!SameTemplateParameterList || !SameReturnType))
  1189. return true;
  1190. }
  1191. if (ConsiderRequiresClauses) {
  1192. Expr *NewRC = New->getTrailingRequiresClause(),
  1193. *OldRC = Old->getTrailingRequiresClause();
  1194. if ((NewRC != nullptr) != (OldRC != nullptr))
  1195. return true;
  1196. if (NewRC && !AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
  1197. return true;
  1198. }
  1199. // If the function is a class member, its signature includes the
  1200. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  1201. //
  1202. // As part of this, also check whether one of the member functions
  1203. // is static, in which case they are not overloads (C++
  1204. // 13.1p2). While not part of the definition of the signature,
  1205. // this check is important to determine whether these functions
  1206. // can be overloaded.
  1207. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1208. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  1209. if (OldMethod && NewMethod &&
  1210. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  1211. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  1212. if (!UseMemberUsingDeclRules &&
  1213. (OldMethod->getRefQualifier() == RQ_None ||
  1214. NewMethod->getRefQualifier() == RQ_None)) {
  1215. // C++20 [over.load]p2:
  1216. // - Member function declarations with the same name, the same
  1217. // parameter-type-list, and the same trailing requires-clause (if
  1218. // any), as well as member function template declarations with the
  1219. // same name, the same parameter-type-list, the same trailing
  1220. // requires-clause (if any), and the same template-head, cannot be
  1221. // overloaded if any of them, but not all, have a ref-qualifier.
  1222. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  1223. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  1224. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  1225. }
  1226. return true;
  1227. }
  1228. // We may not have applied the implicit const for a constexpr member
  1229. // function yet (because we haven't yet resolved whether this is a static
  1230. // or non-static member function). Add it now, on the assumption that this
  1231. // is a redeclaration of OldMethod.
  1232. auto OldQuals = OldMethod->getMethodQualifiers();
  1233. auto NewQuals = NewMethod->getMethodQualifiers();
  1234. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  1235. !isa<CXXConstructorDecl>(NewMethod))
  1236. NewQuals.addConst();
  1237. // We do not allow overloading based off of '__restrict'.
  1238. OldQuals.removeRestrict();
  1239. NewQuals.removeRestrict();
  1240. if (OldQuals != NewQuals)
  1241. return true;
  1242. }
  1243. // Though pass_object_size is placed on parameters and takes an argument, we
  1244. // consider it to be a function-level modifier for the sake of function
  1245. // identity. Either the function has one or more parameters with
  1246. // pass_object_size or it doesn't.
  1247. if (functionHasPassObjectSizeParams(New) !=
  1248. functionHasPassObjectSizeParams(Old))
  1249. return true;
  1250. // enable_if attributes are an order-sensitive part of the signature.
  1251. for (specific_attr_iterator<EnableIfAttr>
  1252. NewI = New->specific_attr_begin<EnableIfAttr>(),
  1253. NewE = New->specific_attr_end<EnableIfAttr>(),
  1254. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  1255. OldE = Old->specific_attr_end<EnableIfAttr>();
  1256. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  1257. if (NewI == NewE || OldI == OldE)
  1258. return true;
  1259. llvm::FoldingSetNodeID NewID, OldID;
  1260. NewI->getCond()->Profile(NewID, Context, true);
  1261. OldI->getCond()->Profile(OldID, Context, true);
  1262. if (NewID != OldID)
  1263. return true;
  1264. }
  1265. if (getLangOpts().CUDA && ConsiderCudaAttrs) {
  1266. // Don't allow overloading of destructors. (In theory we could, but it
  1267. // would be a giant change to clang.)
  1268. if (!isa<CXXDestructorDecl>(New)) {
  1269. CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
  1270. OldTarget = IdentifyCUDATarget(Old);
  1271. if (NewTarget != CFT_InvalidTarget) {
  1272. assert((OldTarget != CFT_InvalidTarget) &&
  1273. "Unexpected invalid target.");
  1274. // Allow overloading of functions with same signature and different CUDA
  1275. // target attributes.
  1276. if (NewTarget != OldTarget)
  1277. return true;
  1278. }
  1279. }
  1280. }
  1281. // The signatures match; this is not an overload.
  1282. return false;
  1283. }
  1284. /// Tries a user-defined conversion from From to ToType.
  1285. ///
  1286. /// Produces an implicit conversion sequence for when a standard conversion
  1287. /// is not an option. See TryImplicitConversion for more information.
  1288. static ImplicitConversionSequence
  1289. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1290. bool SuppressUserConversions,
  1291. AllowedExplicit AllowExplicit,
  1292. bool InOverloadResolution,
  1293. bool CStyle,
  1294. bool AllowObjCWritebackConversion,
  1295. bool AllowObjCConversionOnExplicit) {
  1296. ImplicitConversionSequence ICS;
  1297. if (SuppressUserConversions) {
  1298. // We're not in the case above, so there is no conversion that
  1299. // we can perform.
  1300. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1301. return ICS;
  1302. }
  1303. // Attempt user-defined conversion.
  1304. OverloadCandidateSet Conversions(From->getExprLoc(),
  1305. OverloadCandidateSet::CSK_Normal);
  1306. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1307. Conversions, AllowExplicit,
  1308. AllowObjCConversionOnExplicit)) {
  1309. case OR_Success:
  1310. case OR_Deleted:
  1311. ICS.setUserDefined();
  1312. // C++ [over.ics.user]p4:
  1313. // A conversion of an expression of class type to the same class
  1314. // type is given Exact Match rank, and a conversion of an
  1315. // expression of class type to a base class of that type is
  1316. // given Conversion rank, in spite of the fact that a copy
  1317. // constructor (i.e., a user-defined conversion function) is
  1318. // called for those cases.
  1319. if (CXXConstructorDecl *Constructor
  1320. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1321. QualType FromCanon
  1322. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1323. QualType ToCanon
  1324. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1325. if (Constructor->isCopyConstructor() &&
  1326. (FromCanon == ToCanon ||
  1327. S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
  1328. // Turn this into a "standard" conversion sequence, so that it
  1329. // gets ranked with standard conversion sequences.
  1330. DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
  1331. ICS.setStandard();
  1332. ICS.Standard.setAsIdentityConversion();
  1333. ICS.Standard.setFromType(From->getType());
  1334. ICS.Standard.setAllToTypes(ToType);
  1335. ICS.Standard.CopyConstructor = Constructor;
  1336. ICS.Standard.FoundCopyConstructor = Found;
  1337. if (ToCanon != FromCanon)
  1338. ICS.Standard.Second = ICK_Derived_To_Base;
  1339. }
  1340. }
  1341. break;
  1342. case OR_Ambiguous:
  1343. ICS.setAmbiguous();
  1344. ICS.Ambiguous.setFromType(From->getType());
  1345. ICS.Ambiguous.setToType(ToType);
  1346. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1347. Cand != Conversions.end(); ++Cand)
  1348. if (Cand->Best)
  1349. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  1350. break;
  1351. // Fall through.
  1352. case OR_No_Viable_Function:
  1353. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1354. break;
  1355. }
  1356. return ICS;
  1357. }
  1358. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1359. /// from the given expression (Expr) to the given type (ToType). This
  1360. /// function returns an implicit conversion sequence that can be used
  1361. /// to perform the initialization. Given
  1362. ///
  1363. /// void f(float f);
  1364. /// void g(int i) { f(i); }
  1365. ///
  1366. /// this routine would produce an implicit conversion sequence to
  1367. /// describe the initialization of f from i, which will be a standard
  1368. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1369. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1370. //
  1371. /// Note that this routine only determines how the conversion can be
  1372. /// performed; it does not actually perform the conversion. As such,
  1373. /// it will not produce any diagnostics if no conversion is available,
  1374. /// but will instead return an implicit conversion sequence of kind
  1375. /// "BadConversion".
  1376. ///
  1377. /// If @p SuppressUserConversions, then user-defined conversions are
  1378. /// not permitted.
  1379. /// If @p AllowExplicit, then explicit user-defined conversions are
  1380. /// permitted.
  1381. ///
  1382. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1383. /// writeback conversion, which allows __autoreleasing id* parameters to
  1384. /// be initialized with __strong id* or __weak id* arguments.
  1385. static ImplicitConversionSequence
  1386. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1387. bool SuppressUserConversions,
  1388. AllowedExplicit AllowExplicit,
  1389. bool InOverloadResolution,
  1390. bool CStyle,
  1391. bool AllowObjCWritebackConversion,
  1392. bool AllowObjCConversionOnExplicit) {
  1393. ImplicitConversionSequence ICS;
  1394. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1395. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1396. ICS.setStandard();
  1397. return ICS;
  1398. }
  1399. if (!S.getLangOpts().CPlusPlus) {
  1400. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1401. return ICS;
  1402. }
  1403. // C++ [over.ics.user]p4:
  1404. // A conversion of an expression of class type to the same class
  1405. // type is given Exact Match rank, and a conversion of an
  1406. // expression of class type to a base class of that type is
  1407. // given Conversion rank, in spite of the fact that a copy/move
  1408. // constructor (i.e., a user-defined conversion function) is
  1409. // called for those cases.
  1410. QualType FromType = From->getType();
  1411. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1412. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1413. S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
  1414. ICS.setStandard();
  1415. ICS.Standard.setAsIdentityConversion();
  1416. ICS.Standard.setFromType(FromType);
  1417. ICS.Standard.setAllToTypes(ToType);
  1418. // We don't actually check at this point whether there is a valid
  1419. // copy/move constructor, since overloading just assumes that it
  1420. // exists. When we actually perform initialization, we'll find the
  1421. // appropriate constructor to copy the returned object, if needed.
  1422. ICS.Standard.CopyConstructor = nullptr;
  1423. // Determine whether this is considered a derived-to-base conversion.
  1424. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1425. ICS.Standard.Second = ICK_Derived_To_Base;
  1426. return ICS;
  1427. }
  1428. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1429. AllowExplicit, InOverloadResolution, CStyle,
  1430. AllowObjCWritebackConversion,
  1431. AllowObjCConversionOnExplicit);
  1432. }
  1433. ImplicitConversionSequence
  1434. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1435. bool SuppressUserConversions,
  1436. AllowedExplicit AllowExplicit,
  1437. bool InOverloadResolution,
  1438. bool CStyle,
  1439. bool AllowObjCWritebackConversion) {
  1440. return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
  1441. AllowExplicit, InOverloadResolution, CStyle,
  1442. AllowObjCWritebackConversion,
  1443. /*AllowObjCConversionOnExplicit=*/false);
  1444. }
  1445. /// PerformImplicitConversion - Perform an implicit conversion of the
  1446. /// expression From to the type ToType. Returns the
  1447. /// converted expression. Flavor is the kind of conversion we're
  1448. /// performing, used in the error message. If @p AllowExplicit,
  1449. /// explicit user-defined conversions are permitted.
  1450. ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1451. AssignmentAction Action,
  1452. bool AllowExplicit) {
  1453. if (checkPlaceholderForOverload(*this, From))
  1454. return ExprError();
  1455. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1456. bool AllowObjCWritebackConversion
  1457. = getLangOpts().ObjCAutoRefCount &&
  1458. (Action == AA_Passing || Action == AA_Sending);
  1459. if (getLangOpts().ObjC)
  1460. CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
  1461. From->getType(), From);
  1462. ImplicitConversionSequence ICS = ::TryImplicitConversion(
  1463. *this, From, ToType,
  1464. /*SuppressUserConversions=*/false,
  1465. AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
  1466. /*InOverloadResolution=*/false,
  1467. /*CStyle=*/false, AllowObjCWritebackConversion,
  1468. /*AllowObjCConversionOnExplicit=*/false);
  1469. return PerformImplicitConversion(From, ToType, ICS, Action);
  1470. }
  1471. /// Determine whether the conversion from FromType to ToType is a valid
  1472. /// conversion that strips "noexcept" or "noreturn" off the nested function
  1473. /// type.
  1474. bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
  1475. QualType &ResultTy) {
  1476. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1477. return false;
  1478. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1479. // or F(t noexcept) -> F(t)
  1480. // where F adds one of the following at most once:
  1481. // - a pointer
  1482. // - a member pointer
  1483. // - a block pointer
  1484. // Changes here need matching changes in FindCompositePointerType.
  1485. CanQualType CanTo = Context.getCanonicalType(ToType);
  1486. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1487. Type::TypeClass TyClass = CanTo->getTypeClass();
  1488. if (TyClass != CanFrom->getTypeClass()) return false;
  1489. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1490. if (TyClass == Type::Pointer) {
  1491. CanTo = CanTo.castAs<PointerType>()->getPointeeType();
  1492. CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
  1493. } else if (TyClass == Type::BlockPointer) {
  1494. CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
  1495. CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
  1496. } else if (TyClass == Type::MemberPointer) {
  1497. auto ToMPT = CanTo.castAs<MemberPointerType>();
  1498. auto FromMPT = CanFrom.castAs<MemberPointerType>();
  1499. // A function pointer conversion cannot change the class of the function.
  1500. if (ToMPT->getClass() != FromMPT->getClass())
  1501. return false;
  1502. CanTo = ToMPT->getPointeeType();
  1503. CanFrom = FromMPT->getPointeeType();
  1504. } else {
  1505. return false;
  1506. }
  1507. TyClass = CanTo->getTypeClass();
  1508. if (TyClass != CanFrom->getTypeClass()) return false;
  1509. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1510. return false;
  1511. }
  1512. const auto *FromFn = cast<FunctionType>(CanFrom);
  1513. FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
  1514. const auto *ToFn = cast<FunctionType>(CanTo);
  1515. FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
  1516. bool Changed = false;
  1517. // Drop 'noreturn' if not present in target type.
  1518. if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
  1519. FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
  1520. Changed = true;
  1521. }
  1522. // Drop 'noexcept' if not present in target type.
  1523. if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
  1524. const auto *ToFPT = cast<FunctionProtoType>(ToFn);
  1525. if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
  1526. FromFn = cast<FunctionType>(
  1527. Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
  1528. EST_None)
  1529. .getTypePtr());
  1530. Changed = true;
  1531. }
  1532. // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
  1533. // only if the ExtParameterInfo lists of the two function prototypes can be
  1534. // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
  1535. SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
  1536. bool CanUseToFPT, CanUseFromFPT;
  1537. if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
  1538. CanUseFromFPT, NewParamInfos) &&
  1539. CanUseToFPT && !CanUseFromFPT) {
  1540. FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
  1541. ExtInfo.ExtParameterInfos =
  1542. NewParamInfos.empty() ? nullptr : NewParamInfos.data();
  1543. QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
  1544. FromFPT->getParamTypes(), ExtInfo);
  1545. FromFn = QT->getAs<FunctionType>();
  1546. Changed = true;
  1547. }
  1548. }
  1549. if (!Changed)
  1550. return false;
  1551. assert(QualType(FromFn, 0).isCanonical());
  1552. if (QualType(FromFn, 0) != CanTo) return false;
  1553. ResultTy = ToType;
  1554. return true;
  1555. }
  1556. /// Determine whether the conversion from FromType to ToType is a valid
  1557. /// vector conversion.
  1558. ///
  1559. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1560. /// conversion.
  1561. static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
  1562. ImplicitConversionKind &ICK, Expr *From,
  1563. bool InOverloadResolution, bool CStyle) {
  1564. // We need at least one of these types to be a vector type to have a vector
  1565. // conversion.
  1566. if (!ToType->isVectorType() && !FromType->isVectorType())
  1567. return false;
  1568. // Identical types require no conversions.
  1569. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1570. return false;
  1571. // There are no conversions between extended vector types, only identity.
  1572. if (ToType->isExtVectorType()) {
  1573. // There are no conversions between extended vector types other than the
  1574. // identity conversion.
  1575. if (FromType->isExtVectorType())
  1576. return false;
  1577. // Vector splat from any arithmetic type to a vector.
  1578. if (FromType->isArithmeticType()) {
  1579. ICK = ICK_Vector_Splat;
  1580. return true;
  1581. }
  1582. }
  1583. if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
  1584. if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
  1585. S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
  1586. ICK = ICK_SVE_Vector_Conversion;
  1587. return true;
  1588. }
  1589. // We can perform the conversion between vector types in the following cases:
  1590. // 1)vector types are equivalent AltiVec and GCC vector types
  1591. // 2)lax vector conversions are permitted and the vector types are of the
  1592. // same size
  1593. // 3)the destination type does not have the ARM MVE strict-polymorphism
  1594. // attribute, which inhibits lax vector conversion for overload resolution
  1595. // only
  1596. if (ToType->isVectorType() && FromType->isVectorType()) {
  1597. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1598. (S.isLaxVectorConversion(FromType, ToType) &&
  1599. !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
  1600. if (S.isLaxVectorConversion(FromType, ToType) &&
  1601. S.anyAltivecTypes(FromType, ToType) &&
  1602. !S.areSameVectorElemTypes(FromType, ToType) &&
  1603. !InOverloadResolution && !CStyle) {
  1604. S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
  1605. << FromType << ToType;
  1606. }
  1607. ICK = ICK_Vector_Conversion;
  1608. return true;
  1609. }
  1610. }
  1611. return false;
  1612. }
  1613. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1614. bool InOverloadResolution,
  1615. StandardConversionSequence &SCS,
  1616. bool CStyle);
  1617. /// IsStandardConversion - Determines whether there is a standard
  1618. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1619. /// expression From to the type ToType. Standard conversion sequences
  1620. /// only consider non-class types; for conversions that involve class
  1621. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1622. /// contain the standard conversion sequence required to perform this
  1623. /// conversion and this routine will return true. Otherwise, this
  1624. /// routine will return false and the value of SCS is unspecified.
  1625. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1626. bool InOverloadResolution,
  1627. StandardConversionSequence &SCS,
  1628. bool CStyle,
  1629. bool AllowObjCWritebackConversion) {
  1630. QualType FromType = From->getType();
  1631. // Standard conversions (C++ [conv])
  1632. SCS.setAsIdentityConversion();
  1633. SCS.IncompatibleObjC = false;
  1634. SCS.setFromType(FromType);
  1635. SCS.CopyConstructor = nullptr;
  1636. // There are no standard conversions for class types in C++, so
  1637. // abort early. When overloading in C, however, we do permit them.
  1638. if (S.getLangOpts().CPlusPlus &&
  1639. (FromType->isRecordType() || ToType->isRecordType()))
  1640. return false;
  1641. // The first conversion can be an lvalue-to-rvalue conversion,
  1642. // array-to-pointer conversion, or function-to-pointer conversion
  1643. // (C++ 4p1).
  1644. if (FromType == S.Context.OverloadTy) {
  1645. DeclAccessPair AccessPair;
  1646. if (FunctionDecl *Fn
  1647. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1648. AccessPair)) {
  1649. // We were able to resolve the address of the overloaded function,
  1650. // so we can convert to the type of that function.
  1651. FromType = Fn->getType();
  1652. SCS.setFromType(FromType);
  1653. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1654. // if the type matches (identity) or we are converting to bool
  1655. if (!S.Context.hasSameUnqualifiedType(
  1656. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1657. QualType resultTy;
  1658. // if the function type matches except for [[noreturn]], it's ok
  1659. if (!S.IsFunctionConversion(FromType,
  1660. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1661. // otherwise, only a boolean conversion is standard
  1662. if (!ToType->isBooleanType())
  1663. return false;
  1664. }
  1665. // Check if the "from" expression is taking the address of an overloaded
  1666. // function and recompute the FromType accordingly. Take advantage of the
  1667. // fact that non-static member functions *must* have such an address-of
  1668. // expression.
  1669. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1670. if (Method && !Method->isStatic()) {
  1671. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1672. "Non-unary operator on non-static member address");
  1673. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1674. == UO_AddrOf &&
  1675. "Non-address-of operator on non-static member address");
  1676. const Type *ClassType
  1677. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1678. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1679. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1680. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1681. UO_AddrOf &&
  1682. "Non-address-of operator for overloaded function expression");
  1683. FromType = S.Context.getPointerType(FromType);
  1684. }
  1685. } else {
  1686. return false;
  1687. }
  1688. }
  1689. // Lvalue-to-rvalue conversion (C++11 4.1):
  1690. // A glvalue (3.10) of a non-function, non-array type T can
  1691. // be converted to a prvalue.
  1692. bool argIsLValue = From->isGLValue();
  1693. if (argIsLValue &&
  1694. !FromType->isFunctionType() && !FromType->isArrayType() &&
  1695. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1696. SCS.First = ICK_Lvalue_To_Rvalue;
  1697. // C11 6.3.2.1p2:
  1698. // ... if the lvalue has atomic type, the value has the non-atomic version
  1699. // of the type of the lvalue ...
  1700. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1701. FromType = Atomic->getValueType();
  1702. // If T is a non-class type, the type of the rvalue is the
  1703. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1704. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1705. // just strip the qualifiers because they don't matter.
  1706. FromType = FromType.getUnqualifiedType();
  1707. } else if (FromType->isArrayType()) {
  1708. // Array-to-pointer conversion (C++ 4.2)
  1709. SCS.First = ICK_Array_To_Pointer;
  1710. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1711. // bound of T" can be converted to an rvalue of type "pointer to
  1712. // T" (C++ 4.2p1).
  1713. FromType = S.Context.getArrayDecayedType(FromType);
  1714. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1715. // This conversion is deprecated in C++03 (D.4)
  1716. SCS.DeprecatedStringLiteralToCharPtr = true;
  1717. // For the purpose of ranking in overload resolution
  1718. // (13.3.3.1.1), this conversion is considered an
  1719. // array-to-pointer conversion followed by a qualification
  1720. // conversion (4.4). (C++ 4.2p2)
  1721. SCS.Second = ICK_Identity;
  1722. SCS.Third = ICK_Qualification;
  1723. SCS.QualificationIncludesObjCLifetime = false;
  1724. SCS.setAllToTypes(FromType);
  1725. return true;
  1726. }
  1727. } else if (FromType->isFunctionType() && argIsLValue) {
  1728. // Function-to-pointer conversion (C++ 4.3).
  1729. SCS.First = ICK_Function_To_Pointer;
  1730. if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
  1731. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  1732. if (!S.checkAddressOfFunctionIsAvailable(FD))
  1733. return false;
  1734. // An lvalue of function type T can be converted to an rvalue of
  1735. // type "pointer to T." The result is a pointer to the
  1736. // function. (C++ 4.3p1).
  1737. FromType = S.Context.getPointerType(FromType);
  1738. } else {
  1739. // We don't require any conversions for the first step.
  1740. SCS.First = ICK_Identity;
  1741. }
  1742. SCS.setToType(0, FromType);
  1743. // The second conversion can be an integral promotion, floating
  1744. // point promotion, integral conversion, floating point conversion,
  1745. // floating-integral conversion, pointer conversion,
  1746. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1747. // For overloading in C, this can also be a "compatible-type"
  1748. // conversion.
  1749. bool IncompatibleObjC = false;
  1750. ImplicitConversionKind SecondICK = ICK_Identity;
  1751. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1752. // The unqualified versions of the types are the same: there's no
  1753. // conversion to do.
  1754. SCS.Second = ICK_Identity;
  1755. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1756. // Integral promotion (C++ 4.5).
  1757. SCS.Second = ICK_Integral_Promotion;
  1758. FromType = ToType.getUnqualifiedType();
  1759. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1760. // Floating point promotion (C++ 4.6).
  1761. SCS.Second = ICK_Floating_Promotion;
  1762. FromType = ToType.getUnqualifiedType();
  1763. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1764. // Complex promotion (Clang extension)
  1765. SCS.Second = ICK_Complex_Promotion;
  1766. FromType = ToType.getUnqualifiedType();
  1767. } else if (ToType->isBooleanType() &&
  1768. (FromType->isArithmeticType() ||
  1769. FromType->isAnyPointerType() ||
  1770. FromType->isBlockPointerType() ||
  1771. FromType->isMemberPointerType())) {
  1772. // Boolean conversions (C++ 4.12).
  1773. SCS.Second = ICK_Boolean_Conversion;
  1774. FromType = S.Context.BoolTy;
  1775. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1776. ToType->isIntegralType(S.Context)) {
  1777. // Integral conversions (C++ 4.7).
  1778. SCS.Second = ICK_Integral_Conversion;
  1779. FromType = ToType.getUnqualifiedType();
  1780. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1781. // Complex conversions (C99 6.3.1.6)
  1782. SCS.Second = ICK_Complex_Conversion;
  1783. FromType = ToType.getUnqualifiedType();
  1784. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1785. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1786. // Complex-real conversions (C99 6.3.1.7)
  1787. SCS.Second = ICK_Complex_Real;
  1788. FromType = ToType.getUnqualifiedType();
  1789. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1790. // FIXME: disable conversions between long double, __ibm128 and __float128
  1791. // if their representation is different until there is back end support
  1792. // We of course allow this conversion if long double is really double.
  1793. // Conversions between bfloat and other floats are not permitted.
  1794. if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
  1795. return false;
  1796. // Conversions between IEEE-quad and IBM-extended semantics are not
  1797. // permitted.
  1798. const llvm::fltSemantics &FromSem =
  1799. S.Context.getFloatTypeSemantics(FromType);
  1800. const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
  1801. if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
  1802. &ToSem == &llvm::APFloat::IEEEquad()) ||
  1803. (&FromSem == &llvm::APFloat::IEEEquad() &&
  1804. &ToSem == &llvm::APFloat::PPCDoubleDouble()))
  1805. return false;
  1806. // Floating point conversions (C++ 4.8).
  1807. SCS.Second = ICK_Floating_Conversion;
  1808. FromType = ToType.getUnqualifiedType();
  1809. } else if ((FromType->isRealFloatingType() &&
  1810. ToType->isIntegralType(S.Context)) ||
  1811. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1812. ToType->isRealFloatingType())) {
  1813. // Conversions between bfloat and int are not permitted.
  1814. if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
  1815. return false;
  1816. // Floating-integral conversions (C++ 4.9).
  1817. SCS.Second = ICK_Floating_Integral;
  1818. FromType = ToType.getUnqualifiedType();
  1819. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1820. SCS.Second = ICK_Block_Pointer_Conversion;
  1821. } else if (AllowObjCWritebackConversion &&
  1822. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1823. SCS.Second = ICK_Writeback_Conversion;
  1824. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1825. FromType, IncompatibleObjC)) {
  1826. // Pointer conversions (C++ 4.10).
  1827. SCS.Second = ICK_Pointer_Conversion;
  1828. SCS.IncompatibleObjC = IncompatibleObjC;
  1829. FromType = FromType.getUnqualifiedType();
  1830. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1831. InOverloadResolution, FromType)) {
  1832. // Pointer to member conversions (4.11).
  1833. SCS.Second = ICK_Pointer_Member;
  1834. } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
  1835. InOverloadResolution, CStyle)) {
  1836. SCS.Second = SecondICK;
  1837. FromType = ToType.getUnqualifiedType();
  1838. } else if (!S.getLangOpts().CPlusPlus &&
  1839. S.Context.typesAreCompatible(ToType, FromType)) {
  1840. // Compatible conversions (Clang extension for C function overloading)
  1841. SCS.Second = ICK_Compatible_Conversion;
  1842. FromType = ToType.getUnqualifiedType();
  1843. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1844. InOverloadResolution,
  1845. SCS, CStyle)) {
  1846. SCS.Second = ICK_TransparentUnionConversion;
  1847. FromType = ToType;
  1848. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1849. CStyle)) {
  1850. // tryAtomicConversion has updated the standard conversion sequence
  1851. // appropriately.
  1852. return true;
  1853. } else if (ToType->isEventT() &&
  1854. From->isIntegerConstantExpr(S.getASTContext()) &&
  1855. From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
  1856. SCS.Second = ICK_Zero_Event_Conversion;
  1857. FromType = ToType;
  1858. } else if (ToType->isQueueT() &&
  1859. From->isIntegerConstantExpr(S.getASTContext()) &&
  1860. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1861. SCS.Second = ICK_Zero_Queue_Conversion;
  1862. FromType = ToType;
  1863. } else if (ToType->isSamplerT() &&
  1864. From->isIntegerConstantExpr(S.getASTContext())) {
  1865. SCS.Second = ICK_Compatible_Conversion;
  1866. FromType = ToType;
  1867. } else {
  1868. // No second conversion required.
  1869. SCS.Second = ICK_Identity;
  1870. }
  1871. SCS.setToType(1, FromType);
  1872. // The third conversion can be a function pointer conversion or a
  1873. // qualification conversion (C++ [conv.fctptr], [conv.qual]).
  1874. bool ObjCLifetimeConversion;
  1875. if (S.IsFunctionConversion(FromType, ToType, FromType)) {
  1876. // Function pointer conversions (removing 'noexcept') including removal of
  1877. // 'noreturn' (Clang extension).
  1878. SCS.Third = ICK_Function_Conversion;
  1879. } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1880. ObjCLifetimeConversion)) {
  1881. SCS.Third = ICK_Qualification;
  1882. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1883. FromType = ToType;
  1884. } else {
  1885. // No conversion required
  1886. SCS.Third = ICK_Identity;
  1887. }
  1888. // C++ [over.best.ics]p6:
  1889. // [...] Any difference in top-level cv-qualification is
  1890. // subsumed by the initialization itself and does not constitute
  1891. // a conversion. [...]
  1892. QualType CanonFrom = S.Context.getCanonicalType(FromType);
  1893. QualType CanonTo = S.Context.getCanonicalType(ToType);
  1894. if (CanonFrom.getLocalUnqualifiedType()
  1895. == CanonTo.getLocalUnqualifiedType() &&
  1896. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1897. FromType = ToType;
  1898. CanonFrom = CanonTo;
  1899. }
  1900. SCS.setToType(2, FromType);
  1901. if (CanonFrom == CanonTo)
  1902. return true;
  1903. // If we have not converted the argument type to the parameter type,
  1904. // this is a bad conversion sequence, unless we're resolving an overload in C.
  1905. if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
  1906. return false;
  1907. ExprResult ER = ExprResult{From};
  1908. Sema::AssignConvertType Conv =
  1909. S.CheckSingleAssignmentConstraints(ToType, ER,
  1910. /*Diagnose=*/false,
  1911. /*DiagnoseCFAudited=*/false,
  1912. /*ConvertRHS=*/false);
  1913. ImplicitConversionKind SecondConv;
  1914. switch (Conv) {
  1915. case Sema::Compatible:
  1916. SecondConv = ICK_C_Only_Conversion;
  1917. break;
  1918. // For our purposes, discarding qualifiers is just as bad as using an
  1919. // incompatible pointer. Note that an IncompatiblePointer conversion can drop
  1920. // qualifiers, as well.
  1921. case Sema::CompatiblePointerDiscardsQualifiers:
  1922. case Sema::IncompatiblePointer:
  1923. case Sema::IncompatiblePointerSign:
  1924. SecondConv = ICK_Incompatible_Pointer_Conversion;
  1925. break;
  1926. default:
  1927. return false;
  1928. }
  1929. // First can only be an lvalue conversion, so we pretend that this was the
  1930. // second conversion. First should already be valid from earlier in the
  1931. // function.
  1932. SCS.Second = SecondConv;
  1933. SCS.setToType(1, ToType);
  1934. // Third is Identity, because Second should rank us worse than any other
  1935. // conversion. This could also be ICK_Qualification, but it's simpler to just
  1936. // lump everything in with the second conversion, and we don't gain anything
  1937. // from making this ICK_Qualification.
  1938. SCS.Third = ICK_Identity;
  1939. SCS.setToType(2, ToType);
  1940. return true;
  1941. }
  1942. static bool
  1943. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1944. QualType &ToType,
  1945. bool InOverloadResolution,
  1946. StandardConversionSequence &SCS,
  1947. bool CStyle) {
  1948. const RecordType *UT = ToType->getAsUnionType();
  1949. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1950. return false;
  1951. // The field to initialize within the transparent union.
  1952. RecordDecl *UD = UT->getDecl();
  1953. // It's compatible if the expression matches any of the fields.
  1954. for (const auto *it : UD->fields()) {
  1955. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1956. CStyle, /*AllowObjCWritebackConversion=*/false)) {
  1957. ToType = it->getType();
  1958. return true;
  1959. }
  1960. }
  1961. return false;
  1962. }
  1963. /// IsIntegralPromotion - Determines whether the conversion from the
  1964. /// expression From (whose potentially-adjusted type is FromType) to
  1965. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1966. /// sets PromotedType to the promoted type.
  1967. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1968. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1969. // All integers are built-in.
  1970. if (!To) {
  1971. return false;
  1972. }
  1973. // An rvalue of type char, signed char, unsigned char, short int, or
  1974. // unsigned short int can be converted to an rvalue of type int if
  1975. // int can represent all the values of the source type; otherwise,
  1976. // the source rvalue can be converted to an rvalue of type unsigned
  1977. // int (C++ 4.5p1).
  1978. if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
  1979. !FromType->isEnumeralType()) {
  1980. if ( // We can promote any signed, promotable integer type to an int
  1981. (FromType->isSignedIntegerType() ||
  1982. // We can promote any unsigned integer type whose size is
  1983. // less than int to an int.
  1984. Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
  1985. return To->getKind() == BuiltinType::Int;
  1986. }
  1987. return To->getKind() == BuiltinType::UInt;
  1988. }
  1989. // C++11 [conv.prom]p3:
  1990. // A prvalue of an unscoped enumeration type whose underlying type is not
  1991. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1992. // following types that can represent all the values of the enumeration
  1993. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1994. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1995. // long long int. If none of the types in that list can represent all the
  1996. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1997. // type can be converted to an rvalue a prvalue of the extended integer type
  1998. // with lowest integer conversion rank (4.13) greater than the rank of long
  1999. // long in which all the values of the enumeration can be represented. If
  2000. // there are two such extended types, the signed one is chosen.
  2001. // C++11 [conv.prom]p4:
  2002. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  2003. // can be converted to a prvalue of its underlying type. Moreover, if
  2004. // integral promotion can be applied to its underlying type, a prvalue of an
  2005. // unscoped enumeration type whose underlying type is fixed can also be
  2006. // converted to a prvalue of the promoted underlying type.
  2007. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  2008. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  2009. // provided for a scoped enumeration.
  2010. if (FromEnumType->getDecl()->isScoped())
  2011. return false;
  2012. // We can perform an integral promotion to the underlying type of the enum,
  2013. // even if that's not the promoted type. Note that the check for promoting
  2014. // the underlying type is based on the type alone, and does not consider
  2015. // the bitfield-ness of the actual source expression.
  2016. if (FromEnumType->getDecl()->isFixed()) {
  2017. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  2018. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  2019. IsIntegralPromotion(nullptr, Underlying, ToType);
  2020. }
  2021. // We have already pre-calculated the promotion type, so this is trivial.
  2022. if (ToType->isIntegerType() &&
  2023. isCompleteType(From->getBeginLoc(), FromType))
  2024. return Context.hasSameUnqualifiedType(
  2025. ToType, FromEnumType->getDecl()->getPromotionType());
  2026. // C++ [conv.prom]p5:
  2027. // If the bit-field has an enumerated type, it is treated as any other
  2028. // value of that type for promotion purposes.
  2029. //
  2030. // ... so do not fall through into the bit-field checks below in C++.
  2031. if (getLangOpts().CPlusPlus)
  2032. return false;
  2033. }
  2034. // C++0x [conv.prom]p2:
  2035. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  2036. // to an rvalue a prvalue of the first of the following types that can
  2037. // represent all the values of its underlying type: int, unsigned int,
  2038. // long int, unsigned long int, long long int, or unsigned long long int.
  2039. // If none of the types in that list can represent all the values of its
  2040. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  2041. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  2042. // type.
  2043. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  2044. ToType->isIntegerType()) {
  2045. // Determine whether the type we're converting from is signed or
  2046. // unsigned.
  2047. bool FromIsSigned = FromType->isSignedIntegerType();
  2048. uint64_t FromSize = Context.getTypeSize(FromType);
  2049. // The types we'll try to promote to, in the appropriate
  2050. // order. Try each of these types.
  2051. QualType PromoteTypes[6] = {
  2052. Context.IntTy, Context.UnsignedIntTy,
  2053. Context.LongTy, Context.UnsignedLongTy ,
  2054. Context.LongLongTy, Context.UnsignedLongLongTy
  2055. };
  2056. for (int Idx = 0; Idx < 6; ++Idx) {
  2057. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  2058. if (FromSize < ToSize ||
  2059. (FromSize == ToSize &&
  2060. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  2061. // We found the type that we can promote to. If this is the
  2062. // type we wanted, we have a promotion. Otherwise, no
  2063. // promotion.
  2064. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  2065. }
  2066. }
  2067. }
  2068. // An rvalue for an integral bit-field (9.6) can be converted to an
  2069. // rvalue of type int if int can represent all the values of the
  2070. // bit-field; otherwise, it can be converted to unsigned int if
  2071. // unsigned int can represent all the values of the bit-field. If
  2072. // the bit-field is larger yet, no integral promotion applies to
  2073. // it. If the bit-field has an enumerated type, it is treated as any
  2074. // other value of that type for promotion purposes (C++ 4.5p3).
  2075. // FIXME: We should delay checking of bit-fields until we actually perform the
  2076. // conversion.
  2077. //
  2078. // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
  2079. // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
  2080. // bit-fields and those whose underlying type is larger than int) for GCC
  2081. // compatibility.
  2082. if (From) {
  2083. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  2084. std::optional<llvm::APSInt> BitWidth;
  2085. if (FromType->isIntegralType(Context) &&
  2086. (BitWidth =
  2087. MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
  2088. llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
  2089. ToSize = Context.getTypeSize(ToType);
  2090. // Are we promoting to an int from a bitfield that fits in an int?
  2091. if (*BitWidth < ToSize ||
  2092. (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
  2093. return To->getKind() == BuiltinType::Int;
  2094. }
  2095. // Are we promoting to an unsigned int from an unsigned bitfield
  2096. // that fits into an unsigned int?
  2097. if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
  2098. return To->getKind() == BuiltinType::UInt;
  2099. }
  2100. return false;
  2101. }
  2102. }
  2103. }
  2104. // An rvalue of type bool can be converted to an rvalue of type int,
  2105. // with false becoming zero and true becoming one (C++ 4.5p4).
  2106. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  2107. return true;
  2108. }
  2109. return false;
  2110. }
  2111. /// IsFloatingPointPromotion - Determines whether the conversion from
  2112. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  2113. /// returns true and sets PromotedType to the promoted type.
  2114. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  2115. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  2116. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  2117. /// An rvalue of type float can be converted to an rvalue of type
  2118. /// double. (C++ 4.6p1).
  2119. if (FromBuiltin->getKind() == BuiltinType::Float &&
  2120. ToBuiltin->getKind() == BuiltinType::Double)
  2121. return true;
  2122. // C99 6.3.1.5p1:
  2123. // When a float is promoted to double or long double, or a
  2124. // double is promoted to long double [...].
  2125. if (!getLangOpts().CPlusPlus &&
  2126. (FromBuiltin->getKind() == BuiltinType::Float ||
  2127. FromBuiltin->getKind() == BuiltinType::Double) &&
  2128. (ToBuiltin->getKind() == BuiltinType::LongDouble ||
  2129. ToBuiltin->getKind() == BuiltinType::Float128 ||
  2130. ToBuiltin->getKind() == BuiltinType::Ibm128))
  2131. return true;
  2132. // Half can be promoted to float.
  2133. if (!getLangOpts().NativeHalfType &&
  2134. FromBuiltin->getKind() == BuiltinType::Half &&
  2135. ToBuiltin->getKind() == BuiltinType::Float)
  2136. return true;
  2137. }
  2138. return false;
  2139. }
  2140. /// Determine if a conversion is a complex promotion.
  2141. ///
  2142. /// A complex promotion is defined as a complex -> complex conversion
  2143. /// where the conversion between the underlying real types is a
  2144. /// floating-point or integral promotion.
  2145. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  2146. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  2147. if (!FromComplex)
  2148. return false;
  2149. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  2150. if (!ToComplex)
  2151. return false;
  2152. return IsFloatingPointPromotion(FromComplex->getElementType(),
  2153. ToComplex->getElementType()) ||
  2154. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  2155. ToComplex->getElementType());
  2156. }
  2157. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  2158. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  2159. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  2160. /// if non-empty, will be a pointer to ToType that may or may not have
  2161. /// the right set of qualifiers on its pointee.
  2162. ///
  2163. static QualType
  2164. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  2165. QualType ToPointee, QualType ToType,
  2166. ASTContext &Context,
  2167. bool StripObjCLifetime = false) {
  2168. assert((FromPtr->getTypeClass() == Type::Pointer ||
  2169. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  2170. "Invalid similarly-qualified pointer type");
  2171. /// Conversions to 'id' subsume cv-qualifier conversions.
  2172. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  2173. return ToType.getUnqualifiedType();
  2174. QualType CanonFromPointee
  2175. = Context.getCanonicalType(FromPtr->getPointeeType());
  2176. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  2177. Qualifiers Quals = CanonFromPointee.getQualifiers();
  2178. if (StripObjCLifetime)
  2179. Quals.removeObjCLifetime();
  2180. // Exact qualifier match -> return the pointer type we're converting to.
  2181. if (CanonToPointee.getLocalQualifiers() == Quals) {
  2182. // ToType is exactly what we need. Return it.
  2183. if (!ToType.isNull())
  2184. return ToType.getUnqualifiedType();
  2185. // Build a pointer to ToPointee. It has the right qualifiers
  2186. // already.
  2187. if (isa<ObjCObjectPointerType>(ToType))
  2188. return Context.getObjCObjectPointerType(ToPointee);
  2189. return Context.getPointerType(ToPointee);
  2190. }
  2191. // Just build a canonical type that has the right qualifiers.
  2192. QualType QualifiedCanonToPointee
  2193. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  2194. if (isa<ObjCObjectPointerType>(ToType))
  2195. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  2196. return Context.getPointerType(QualifiedCanonToPointee);
  2197. }
  2198. static bool isNullPointerConstantForConversion(Expr *Expr,
  2199. bool InOverloadResolution,
  2200. ASTContext &Context) {
  2201. // Handle value-dependent integral null pointer constants correctly.
  2202. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  2203. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  2204. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  2205. return !InOverloadResolution;
  2206. return Expr->isNullPointerConstant(Context,
  2207. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2208. : Expr::NPC_ValueDependentIsNull);
  2209. }
  2210. /// IsPointerConversion - Determines whether the conversion of the
  2211. /// expression From, which has the (possibly adjusted) type FromType,
  2212. /// can be converted to the type ToType via a pointer conversion (C++
  2213. /// 4.10). If so, returns true and places the converted type (that
  2214. /// might differ from ToType in its cv-qualifiers at some level) into
  2215. /// ConvertedType.
  2216. ///
  2217. /// This routine also supports conversions to and from block pointers
  2218. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  2219. /// pointers to interfaces. FIXME: Once we've determined the
  2220. /// appropriate overloading rules for Objective-C, we may want to
  2221. /// split the Objective-C checks into a different routine; however,
  2222. /// GCC seems to consider all of these conversions to be pointer
  2223. /// conversions, so for now they live here. IncompatibleObjC will be
  2224. /// set if the conversion is an allowed Objective-C conversion that
  2225. /// should result in a warning.
  2226. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  2227. bool InOverloadResolution,
  2228. QualType& ConvertedType,
  2229. bool &IncompatibleObjC) {
  2230. IncompatibleObjC = false;
  2231. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  2232. IncompatibleObjC))
  2233. return true;
  2234. // Conversion from a null pointer constant to any Objective-C pointer type.
  2235. if (ToType->isObjCObjectPointerType() &&
  2236. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2237. ConvertedType = ToType;
  2238. return true;
  2239. }
  2240. // Blocks: Block pointers can be converted to void*.
  2241. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  2242. ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  2243. ConvertedType = ToType;
  2244. return true;
  2245. }
  2246. // Blocks: A null pointer constant can be converted to a block
  2247. // pointer type.
  2248. if (ToType->isBlockPointerType() &&
  2249. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2250. ConvertedType = ToType;
  2251. return true;
  2252. }
  2253. // If the left-hand-side is nullptr_t, the right side can be a null
  2254. // pointer constant.
  2255. if (ToType->isNullPtrType() &&
  2256. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2257. ConvertedType = ToType;
  2258. return true;
  2259. }
  2260. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  2261. if (!ToTypePtr)
  2262. return false;
  2263. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  2264. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2265. ConvertedType = ToType;
  2266. return true;
  2267. }
  2268. // Beyond this point, both types need to be pointers
  2269. // , including objective-c pointers.
  2270. QualType ToPointeeType = ToTypePtr->getPointeeType();
  2271. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  2272. !getLangOpts().ObjCAutoRefCount) {
  2273. ConvertedType = BuildSimilarlyQualifiedPointerType(
  2274. FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
  2275. Context);
  2276. return true;
  2277. }
  2278. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  2279. if (!FromTypePtr)
  2280. return false;
  2281. QualType FromPointeeType = FromTypePtr->getPointeeType();
  2282. // If the unqualified pointee types are the same, this can't be a
  2283. // pointer conversion, so don't do all of the work below.
  2284. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  2285. return false;
  2286. // An rvalue of type "pointer to cv T," where T is an object type,
  2287. // can be converted to an rvalue of type "pointer to cv void" (C++
  2288. // 4.10p2).
  2289. if (FromPointeeType->isIncompleteOrObjectType() &&
  2290. ToPointeeType->isVoidType()) {
  2291. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2292. ToPointeeType,
  2293. ToType, Context,
  2294. /*StripObjCLifetime=*/true);
  2295. return true;
  2296. }
  2297. // MSVC allows implicit function to void* type conversion.
  2298. if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
  2299. ToPointeeType->isVoidType()) {
  2300. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2301. ToPointeeType,
  2302. ToType, Context);
  2303. return true;
  2304. }
  2305. // When we're overloading in C, we allow a special kind of pointer
  2306. // conversion for compatible-but-not-identical pointee types.
  2307. if (!getLangOpts().CPlusPlus &&
  2308. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  2309. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2310. ToPointeeType,
  2311. ToType, Context);
  2312. return true;
  2313. }
  2314. // C++ [conv.ptr]p3:
  2315. //
  2316. // An rvalue of type "pointer to cv D," where D is a class type,
  2317. // can be converted to an rvalue of type "pointer to cv B," where
  2318. // B is a base class (clause 10) of D. If B is an inaccessible
  2319. // (clause 11) or ambiguous (10.2) base class of D, a program that
  2320. // necessitates this conversion is ill-formed. The result of the
  2321. // conversion is a pointer to the base class sub-object of the
  2322. // derived class object. The null pointer value is converted to
  2323. // the null pointer value of the destination type.
  2324. //
  2325. // Note that we do not check for ambiguity or inaccessibility
  2326. // here. That is handled by CheckPointerConversion.
  2327. if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
  2328. ToPointeeType->isRecordType() &&
  2329. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  2330. IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
  2331. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2332. ToPointeeType,
  2333. ToType, Context);
  2334. return true;
  2335. }
  2336. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  2337. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  2338. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2339. ToPointeeType,
  2340. ToType, Context);
  2341. return true;
  2342. }
  2343. return false;
  2344. }
  2345. /// Adopt the given qualifiers for the given type.
  2346. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  2347. Qualifiers TQs = T.getQualifiers();
  2348. // Check whether qualifiers already match.
  2349. if (TQs == Qs)
  2350. return T;
  2351. if (Qs.compatiblyIncludes(TQs))
  2352. return Context.getQualifiedType(T, Qs);
  2353. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  2354. }
  2355. /// isObjCPointerConversion - Determines whether this is an
  2356. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  2357. /// with the same arguments and return values.
  2358. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  2359. QualType& ConvertedType,
  2360. bool &IncompatibleObjC) {
  2361. if (!getLangOpts().ObjC)
  2362. return false;
  2363. // The set of qualifiers on the type we're converting from.
  2364. Qualifiers FromQualifiers = FromType.getQualifiers();
  2365. // First, we handle all conversions on ObjC object pointer types.
  2366. const ObjCObjectPointerType* ToObjCPtr =
  2367. ToType->getAs<ObjCObjectPointerType>();
  2368. const ObjCObjectPointerType *FromObjCPtr =
  2369. FromType->getAs<ObjCObjectPointerType>();
  2370. if (ToObjCPtr && FromObjCPtr) {
  2371. // If the pointee types are the same (ignoring qualifications),
  2372. // then this is not a pointer conversion.
  2373. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  2374. FromObjCPtr->getPointeeType()))
  2375. return false;
  2376. // Conversion between Objective-C pointers.
  2377. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  2378. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  2379. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  2380. if (getLangOpts().CPlusPlus && LHS && RHS &&
  2381. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  2382. FromObjCPtr->getPointeeType()))
  2383. return false;
  2384. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2385. ToObjCPtr->getPointeeType(),
  2386. ToType, Context);
  2387. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2388. return true;
  2389. }
  2390. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2391. // Okay: this is some kind of implicit downcast of Objective-C
  2392. // interfaces, which is permitted. However, we're going to
  2393. // complain about it.
  2394. IncompatibleObjC = true;
  2395. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2396. ToObjCPtr->getPointeeType(),
  2397. ToType, Context);
  2398. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2399. return true;
  2400. }
  2401. }
  2402. // Beyond this point, both types need to be C pointers or block pointers.
  2403. QualType ToPointeeType;
  2404. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2405. ToPointeeType = ToCPtr->getPointeeType();
  2406. else if (const BlockPointerType *ToBlockPtr =
  2407. ToType->getAs<BlockPointerType>()) {
  2408. // Objective C++: We're able to convert from a pointer to any object
  2409. // to a block pointer type.
  2410. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2411. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2412. return true;
  2413. }
  2414. ToPointeeType = ToBlockPtr->getPointeeType();
  2415. }
  2416. else if (FromType->getAs<BlockPointerType>() &&
  2417. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2418. // Objective C++: We're able to convert from a block pointer type to a
  2419. // pointer to any object.
  2420. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2421. return true;
  2422. }
  2423. else
  2424. return false;
  2425. QualType FromPointeeType;
  2426. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2427. FromPointeeType = FromCPtr->getPointeeType();
  2428. else if (const BlockPointerType *FromBlockPtr =
  2429. FromType->getAs<BlockPointerType>())
  2430. FromPointeeType = FromBlockPtr->getPointeeType();
  2431. else
  2432. return false;
  2433. // If we have pointers to pointers, recursively check whether this
  2434. // is an Objective-C conversion.
  2435. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2436. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2437. IncompatibleObjC)) {
  2438. // We always complain about this conversion.
  2439. IncompatibleObjC = true;
  2440. ConvertedType = Context.getPointerType(ConvertedType);
  2441. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2442. return true;
  2443. }
  2444. // Allow conversion of pointee being objective-c pointer to another one;
  2445. // as in I* to id.
  2446. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2447. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2448. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2449. IncompatibleObjC)) {
  2450. ConvertedType = Context.getPointerType(ConvertedType);
  2451. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2452. return true;
  2453. }
  2454. // If we have pointers to functions or blocks, check whether the only
  2455. // differences in the argument and result types are in Objective-C
  2456. // pointer conversions. If so, we permit the conversion (but
  2457. // complain about it).
  2458. const FunctionProtoType *FromFunctionType
  2459. = FromPointeeType->getAs<FunctionProtoType>();
  2460. const FunctionProtoType *ToFunctionType
  2461. = ToPointeeType->getAs<FunctionProtoType>();
  2462. if (FromFunctionType && ToFunctionType) {
  2463. // If the function types are exactly the same, this isn't an
  2464. // Objective-C pointer conversion.
  2465. if (Context.getCanonicalType(FromPointeeType)
  2466. == Context.getCanonicalType(ToPointeeType))
  2467. return false;
  2468. // Perform the quick checks that will tell us whether these
  2469. // function types are obviously different.
  2470. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2471. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2472. FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
  2473. return false;
  2474. bool HasObjCConversion = false;
  2475. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2476. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2477. // Okay, the types match exactly. Nothing to do.
  2478. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2479. ToFunctionType->getReturnType(),
  2480. ConvertedType, IncompatibleObjC)) {
  2481. // Okay, we have an Objective-C pointer conversion.
  2482. HasObjCConversion = true;
  2483. } else {
  2484. // Function types are too different. Abort.
  2485. return false;
  2486. }
  2487. // Check argument types.
  2488. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2489. ArgIdx != NumArgs; ++ArgIdx) {
  2490. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2491. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2492. if (Context.getCanonicalType(FromArgType)
  2493. == Context.getCanonicalType(ToArgType)) {
  2494. // Okay, the types match exactly. Nothing to do.
  2495. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2496. ConvertedType, IncompatibleObjC)) {
  2497. // Okay, we have an Objective-C pointer conversion.
  2498. HasObjCConversion = true;
  2499. } else {
  2500. // Argument types are too different. Abort.
  2501. return false;
  2502. }
  2503. }
  2504. if (HasObjCConversion) {
  2505. // We had an Objective-C conversion. Allow this pointer
  2506. // conversion, but complain about it.
  2507. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2508. IncompatibleObjC = true;
  2509. return true;
  2510. }
  2511. }
  2512. return false;
  2513. }
  2514. /// Determine whether this is an Objective-C writeback conversion,
  2515. /// used for parameter passing when performing automatic reference counting.
  2516. ///
  2517. /// \param FromType The type we're converting form.
  2518. ///
  2519. /// \param ToType The type we're converting to.
  2520. ///
  2521. /// \param ConvertedType The type that will be produced after applying
  2522. /// this conversion.
  2523. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2524. QualType &ConvertedType) {
  2525. if (!getLangOpts().ObjCAutoRefCount ||
  2526. Context.hasSameUnqualifiedType(FromType, ToType))
  2527. return false;
  2528. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2529. QualType ToPointee;
  2530. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2531. ToPointee = ToPointer->getPointeeType();
  2532. else
  2533. return false;
  2534. Qualifiers ToQuals = ToPointee.getQualifiers();
  2535. if (!ToPointee->isObjCLifetimeType() ||
  2536. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2537. !ToQuals.withoutObjCLifetime().empty())
  2538. return false;
  2539. // Argument must be a pointer to __strong to __weak.
  2540. QualType FromPointee;
  2541. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2542. FromPointee = FromPointer->getPointeeType();
  2543. else
  2544. return false;
  2545. Qualifiers FromQuals = FromPointee.getQualifiers();
  2546. if (!FromPointee->isObjCLifetimeType() ||
  2547. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2548. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2549. return false;
  2550. // Make sure that we have compatible qualifiers.
  2551. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2552. if (!ToQuals.compatiblyIncludes(FromQuals))
  2553. return false;
  2554. // Remove qualifiers from the pointee type we're converting from; they
  2555. // aren't used in the compatibility check belong, and we'll be adding back
  2556. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2557. FromPointee = FromPointee.getUnqualifiedType();
  2558. // The unqualified form of the pointee types must be compatible.
  2559. ToPointee = ToPointee.getUnqualifiedType();
  2560. bool IncompatibleObjC;
  2561. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2562. FromPointee = ToPointee;
  2563. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2564. IncompatibleObjC))
  2565. return false;
  2566. /// Construct the type we're converting to, which is a pointer to
  2567. /// __autoreleasing pointee.
  2568. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2569. ConvertedType = Context.getPointerType(FromPointee);
  2570. return true;
  2571. }
  2572. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2573. QualType& ConvertedType) {
  2574. QualType ToPointeeType;
  2575. if (const BlockPointerType *ToBlockPtr =
  2576. ToType->getAs<BlockPointerType>())
  2577. ToPointeeType = ToBlockPtr->getPointeeType();
  2578. else
  2579. return false;
  2580. QualType FromPointeeType;
  2581. if (const BlockPointerType *FromBlockPtr =
  2582. FromType->getAs<BlockPointerType>())
  2583. FromPointeeType = FromBlockPtr->getPointeeType();
  2584. else
  2585. return false;
  2586. // We have pointer to blocks, check whether the only
  2587. // differences in the argument and result types are in Objective-C
  2588. // pointer conversions. If so, we permit the conversion.
  2589. const FunctionProtoType *FromFunctionType
  2590. = FromPointeeType->getAs<FunctionProtoType>();
  2591. const FunctionProtoType *ToFunctionType
  2592. = ToPointeeType->getAs<FunctionProtoType>();
  2593. if (!FromFunctionType || !ToFunctionType)
  2594. return false;
  2595. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2596. return true;
  2597. // Perform the quick checks that will tell us whether these
  2598. // function types are obviously different.
  2599. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2600. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2601. return false;
  2602. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2603. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2604. if (FromEInfo != ToEInfo)
  2605. return false;
  2606. bool IncompatibleObjC = false;
  2607. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2608. ToFunctionType->getReturnType())) {
  2609. // Okay, the types match exactly. Nothing to do.
  2610. } else {
  2611. QualType RHS = FromFunctionType->getReturnType();
  2612. QualType LHS = ToFunctionType->getReturnType();
  2613. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2614. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2615. LHS = LHS.getUnqualifiedType();
  2616. if (Context.hasSameType(RHS,LHS)) {
  2617. // OK exact match.
  2618. } else if (isObjCPointerConversion(RHS, LHS,
  2619. ConvertedType, IncompatibleObjC)) {
  2620. if (IncompatibleObjC)
  2621. return false;
  2622. // Okay, we have an Objective-C pointer conversion.
  2623. }
  2624. else
  2625. return false;
  2626. }
  2627. // Check argument types.
  2628. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2629. ArgIdx != NumArgs; ++ArgIdx) {
  2630. IncompatibleObjC = false;
  2631. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2632. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2633. if (Context.hasSameType(FromArgType, ToArgType)) {
  2634. // Okay, the types match exactly. Nothing to do.
  2635. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2636. ConvertedType, IncompatibleObjC)) {
  2637. if (IncompatibleObjC)
  2638. return false;
  2639. // Okay, we have an Objective-C pointer conversion.
  2640. } else
  2641. // Argument types are too different. Abort.
  2642. return false;
  2643. }
  2644. SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
  2645. bool CanUseToFPT, CanUseFromFPT;
  2646. if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
  2647. CanUseToFPT, CanUseFromFPT,
  2648. NewParamInfos))
  2649. return false;
  2650. ConvertedType = ToType;
  2651. return true;
  2652. }
  2653. enum {
  2654. ft_default,
  2655. ft_different_class,
  2656. ft_parameter_arity,
  2657. ft_parameter_mismatch,
  2658. ft_return_type,
  2659. ft_qualifer_mismatch,
  2660. ft_noexcept
  2661. };
  2662. /// Attempts to get the FunctionProtoType from a Type. Handles
  2663. /// MemberFunctionPointers properly.
  2664. static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
  2665. if (auto *FPT = FromType->getAs<FunctionProtoType>())
  2666. return FPT;
  2667. if (auto *MPT = FromType->getAs<MemberPointerType>())
  2668. return MPT->getPointeeType()->getAs<FunctionProtoType>();
  2669. return nullptr;
  2670. }
  2671. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2672. /// function types. Catches different number of parameter, mismatch in
  2673. /// parameter types, and different return types.
  2674. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2675. QualType FromType, QualType ToType) {
  2676. // If either type is not valid, include no extra info.
  2677. if (FromType.isNull() || ToType.isNull()) {
  2678. PDiag << ft_default;
  2679. return;
  2680. }
  2681. // Get the function type from the pointers.
  2682. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2683. const auto *FromMember = FromType->castAs<MemberPointerType>(),
  2684. *ToMember = ToType->castAs<MemberPointerType>();
  2685. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2686. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2687. << QualType(FromMember->getClass(), 0);
  2688. return;
  2689. }
  2690. FromType = FromMember->getPointeeType();
  2691. ToType = ToMember->getPointeeType();
  2692. }
  2693. if (FromType->isPointerType())
  2694. FromType = FromType->getPointeeType();
  2695. if (ToType->isPointerType())
  2696. ToType = ToType->getPointeeType();
  2697. // Remove references.
  2698. FromType = FromType.getNonReferenceType();
  2699. ToType = ToType.getNonReferenceType();
  2700. // Don't print extra info for non-specialized template functions.
  2701. if (FromType->isInstantiationDependentType() &&
  2702. !FromType->getAs<TemplateSpecializationType>()) {
  2703. PDiag << ft_default;
  2704. return;
  2705. }
  2706. // No extra info for same types.
  2707. if (Context.hasSameType(FromType, ToType)) {
  2708. PDiag << ft_default;
  2709. return;
  2710. }
  2711. const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
  2712. *ToFunction = tryGetFunctionProtoType(ToType);
  2713. // Both types need to be function types.
  2714. if (!FromFunction || !ToFunction) {
  2715. PDiag << ft_default;
  2716. return;
  2717. }
  2718. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2719. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2720. << FromFunction->getNumParams();
  2721. return;
  2722. }
  2723. // Handle different parameter types.
  2724. unsigned ArgPos;
  2725. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2726. PDiag << ft_parameter_mismatch << ArgPos + 1
  2727. << ToFunction->getParamType(ArgPos)
  2728. << FromFunction->getParamType(ArgPos);
  2729. return;
  2730. }
  2731. // Handle different return type.
  2732. if (!Context.hasSameType(FromFunction->getReturnType(),
  2733. ToFunction->getReturnType())) {
  2734. PDiag << ft_return_type << ToFunction->getReturnType()
  2735. << FromFunction->getReturnType();
  2736. return;
  2737. }
  2738. if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
  2739. PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
  2740. << FromFunction->getMethodQuals();
  2741. return;
  2742. }
  2743. // Handle exception specification differences on canonical type (in C++17
  2744. // onwards).
  2745. if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
  2746. ->isNothrow() !=
  2747. cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
  2748. ->isNothrow()) {
  2749. PDiag << ft_noexcept;
  2750. return;
  2751. }
  2752. // Unable to find a difference, so add no extra info.
  2753. PDiag << ft_default;
  2754. }
  2755. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2756. /// for equality of their parameter types. Caller has already checked that
  2757. /// they have same number of parameters. If the parameters are different,
  2758. /// ArgPos will have the parameter index of the first different parameter.
  2759. /// If `Reversed` is true, the parameters of `NewType` will be compared in
  2760. /// reverse order. That's useful if one of the functions is being used as a C++20
  2761. /// synthesized operator overload with a reversed parameter order.
  2762. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2763. const FunctionProtoType *NewType,
  2764. unsigned *ArgPos, bool Reversed) {
  2765. assert(OldType->getNumParams() == NewType->getNumParams() &&
  2766. "Can't compare parameters of functions with different number of "
  2767. "parameters!");
  2768. for (size_t I = 0; I < OldType->getNumParams(); I++) {
  2769. // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
  2770. size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
  2771. // Ignore address spaces in pointee type. This is to disallow overloading
  2772. // on __ptr32/__ptr64 address spaces.
  2773. QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
  2774. QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
  2775. if (!Context.hasSameType(Old, New)) {
  2776. if (ArgPos)
  2777. *ArgPos = I;
  2778. return false;
  2779. }
  2780. }
  2781. return true;
  2782. }
  2783. /// CheckPointerConversion - Check the pointer conversion from the
  2784. /// expression From to the type ToType. This routine checks for
  2785. /// ambiguous or inaccessible derived-to-base pointer
  2786. /// conversions for which IsPointerConversion has already returned
  2787. /// true. It returns true and produces a diagnostic if there was an
  2788. /// error, or returns false otherwise.
  2789. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2790. CastKind &Kind,
  2791. CXXCastPath& BasePath,
  2792. bool IgnoreBaseAccess,
  2793. bool Diagnose) {
  2794. QualType FromType = From->getType();
  2795. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2796. Kind = CK_BitCast;
  2797. if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2798. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2799. Expr::NPCK_ZeroExpression) {
  2800. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2801. DiagRuntimeBehavior(From->getExprLoc(), From,
  2802. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2803. << ToType << From->getSourceRange());
  2804. else if (!isUnevaluatedContext())
  2805. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2806. << ToType << From->getSourceRange();
  2807. }
  2808. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2809. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2810. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2811. ToPointeeType = ToPtrType->getPointeeType();
  2812. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2813. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2814. // We must have a derived-to-base conversion. Check an
  2815. // ambiguous or inaccessible conversion.
  2816. unsigned InaccessibleID = 0;
  2817. unsigned AmbiguousID = 0;
  2818. if (Diagnose) {
  2819. InaccessibleID = diag::err_upcast_to_inaccessible_base;
  2820. AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
  2821. }
  2822. if (CheckDerivedToBaseConversion(
  2823. FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
  2824. From->getExprLoc(), From->getSourceRange(), DeclarationName(),
  2825. &BasePath, IgnoreBaseAccess))
  2826. return true;
  2827. // The conversion was successful.
  2828. Kind = CK_DerivedToBase;
  2829. }
  2830. if (Diagnose && !IsCStyleOrFunctionalCast &&
  2831. FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
  2832. assert(getLangOpts().MSVCCompat &&
  2833. "this should only be possible with MSVCCompat!");
  2834. Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
  2835. << From->getSourceRange();
  2836. }
  2837. }
  2838. } else if (const ObjCObjectPointerType *ToPtrType =
  2839. ToType->getAs<ObjCObjectPointerType>()) {
  2840. if (const ObjCObjectPointerType *FromPtrType =
  2841. FromType->getAs<ObjCObjectPointerType>()) {
  2842. // Objective-C++ conversions are always okay.
  2843. // FIXME: We should have a different class of conversions for the
  2844. // Objective-C++ implicit conversions.
  2845. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2846. return false;
  2847. } else if (FromType->isBlockPointerType()) {
  2848. Kind = CK_BlockPointerToObjCPointerCast;
  2849. } else {
  2850. Kind = CK_CPointerToObjCPointerCast;
  2851. }
  2852. } else if (ToType->isBlockPointerType()) {
  2853. if (!FromType->isBlockPointerType())
  2854. Kind = CK_AnyPointerToBlockPointerCast;
  2855. }
  2856. // We shouldn't fall into this case unless it's valid for other
  2857. // reasons.
  2858. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2859. Kind = CK_NullToPointer;
  2860. return false;
  2861. }
  2862. /// IsMemberPointerConversion - Determines whether the conversion of the
  2863. /// expression From, which has the (possibly adjusted) type FromType, can be
  2864. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2865. /// If so, returns true and places the converted type (that might differ from
  2866. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2867. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2868. QualType ToType,
  2869. bool InOverloadResolution,
  2870. QualType &ConvertedType) {
  2871. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2872. if (!ToTypePtr)
  2873. return false;
  2874. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2875. if (From->isNullPointerConstant(Context,
  2876. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2877. : Expr::NPC_ValueDependentIsNull)) {
  2878. ConvertedType = ToType;
  2879. return true;
  2880. }
  2881. // Otherwise, both types have to be member pointers.
  2882. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2883. if (!FromTypePtr)
  2884. return false;
  2885. // A pointer to member of B can be converted to a pointer to member of D,
  2886. // where D is derived from B (C++ 4.11p2).
  2887. QualType FromClass(FromTypePtr->getClass(), 0);
  2888. QualType ToClass(ToTypePtr->getClass(), 0);
  2889. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2890. IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
  2891. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2892. ToClass.getTypePtr());
  2893. return true;
  2894. }
  2895. return false;
  2896. }
  2897. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2898. /// expression From to the type ToType. This routine checks for ambiguous or
  2899. /// virtual or inaccessible base-to-derived member pointer conversions
  2900. /// for which IsMemberPointerConversion has already returned true. It returns
  2901. /// true and produces a diagnostic if there was an error, or returns false
  2902. /// otherwise.
  2903. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2904. CastKind &Kind,
  2905. CXXCastPath &BasePath,
  2906. bool IgnoreBaseAccess) {
  2907. QualType FromType = From->getType();
  2908. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2909. if (!FromPtrType) {
  2910. // This must be a null pointer to member pointer conversion
  2911. assert(From->isNullPointerConstant(Context,
  2912. Expr::NPC_ValueDependentIsNull) &&
  2913. "Expr must be null pointer constant!");
  2914. Kind = CK_NullToMemberPointer;
  2915. return false;
  2916. }
  2917. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2918. assert(ToPtrType && "No member pointer cast has a target type "
  2919. "that is not a member pointer.");
  2920. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2921. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2922. // FIXME: What about dependent types?
  2923. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2924. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2925. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2926. /*DetectVirtual=*/true);
  2927. bool DerivationOkay =
  2928. IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
  2929. assert(DerivationOkay &&
  2930. "Should not have been called if derivation isn't OK.");
  2931. (void)DerivationOkay;
  2932. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2933. getUnqualifiedType())) {
  2934. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2935. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2936. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2937. return true;
  2938. }
  2939. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2940. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2941. << FromClass << ToClass << QualType(VBase, 0)
  2942. << From->getSourceRange();
  2943. return true;
  2944. }
  2945. if (!IgnoreBaseAccess)
  2946. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2947. Paths.front(),
  2948. diag::err_downcast_from_inaccessible_base);
  2949. // Must be a base to derived member conversion.
  2950. BuildBasePathArray(Paths, BasePath);
  2951. Kind = CK_BaseToDerivedMemberPointer;
  2952. return false;
  2953. }
  2954. /// Determine whether the lifetime conversion between the two given
  2955. /// qualifiers sets is nontrivial.
  2956. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2957. Qualifiers ToQuals) {
  2958. // Converting anything to const __unsafe_unretained is trivial.
  2959. if (ToQuals.hasConst() &&
  2960. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2961. return false;
  2962. return true;
  2963. }
  2964. /// Perform a single iteration of the loop for checking if a qualification
  2965. /// conversion is valid.
  2966. ///
  2967. /// Specifically, check whether any change between the qualifiers of \p
  2968. /// FromType and \p ToType is permissible, given knowledge about whether every
  2969. /// outer layer is const-qualified.
  2970. static bool isQualificationConversionStep(QualType FromType, QualType ToType,
  2971. bool CStyle, bool IsTopLevel,
  2972. bool &PreviousToQualsIncludeConst,
  2973. bool &ObjCLifetimeConversion) {
  2974. Qualifiers FromQuals = FromType.getQualifiers();
  2975. Qualifiers ToQuals = ToType.getQualifiers();
  2976. // Ignore __unaligned qualifier.
  2977. FromQuals.removeUnaligned();
  2978. // Objective-C ARC:
  2979. // Check Objective-C lifetime conversions.
  2980. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
  2981. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2982. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2983. ObjCLifetimeConversion = true;
  2984. FromQuals.removeObjCLifetime();
  2985. ToQuals.removeObjCLifetime();
  2986. } else {
  2987. // Qualification conversions cannot cast between different
  2988. // Objective-C lifetime qualifiers.
  2989. return false;
  2990. }
  2991. }
  2992. // Allow addition/removal of GC attributes but not changing GC attributes.
  2993. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2994. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2995. FromQuals.removeObjCGCAttr();
  2996. ToQuals.removeObjCGCAttr();
  2997. }
  2998. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2999. // 2,j, and similarly for volatile.
  3000. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  3001. return false;
  3002. // If address spaces mismatch:
  3003. // - in top level it is only valid to convert to addr space that is a
  3004. // superset in all cases apart from C-style casts where we allow
  3005. // conversions between overlapping address spaces.
  3006. // - in non-top levels it is not a valid conversion.
  3007. if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
  3008. (!IsTopLevel ||
  3009. !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
  3010. (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
  3011. return false;
  3012. // -- if the cv 1,j and cv 2,j are different, then const is in
  3013. // every cv for 0 < k < j.
  3014. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
  3015. !PreviousToQualsIncludeConst)
  3016. return false;
  3017. // The following wording is from C++20, where the result of the conversion
  3018. // is T3, not T2.
  3019. // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
  3020. // "array of unknown bound of"
  3021. if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
  3022. return false;
  3023. // -- if the resulting P3,i is different from P1,i [...], then const is
  3024. // added to every cv 3_k for 0 < k < i.
  3025. if (!CStyle && FromType->isConstantArrayType() &&
  3026. ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
  3027. return false;
  3028. // Keep track of whether all prior cv-qualifiers in the "to" type
  3029. // include const.
  3030. PreviousToQualsIncludeConst =
  3031. PreviousToQualsIncludeConst && ToQuals.hasConst();
  3032. return true;
  3033. }
  3034. /// IsQualificationConversion - Determines whether the conversion from
  3035. /// an rvalue of type FromType to ToType is a qualification conversion
  3036. /// (C++ 4.4).
  3037. ///
  3038. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  3039. /// when the qualification conversion involves a change in the Objective-C
  3040. /// object lifetime.
  3041. bool
  3042. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  3043. bool CStyle, bool &ObjCLifetimeConversion) {
  3044. FromType = Context.getCanonicalType(FromType);
  3045. ToType = Context.getCanonicalType(ToType);
  3046. ObjCLifetimeConversion = false;
  3047. // If FromType and ToType are the same type, this is not a
  3048. // qualification conversion.
  3049. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  3050. return false;
  3051. // (C++ 4.4p4):
  3052. // A conversion can add cv-qualifiers at levels other than the first
  3053. // in multi-level pointers, subject to the following rules: [...]
  3054. bool PreviousToQualsIncludeConst = true;
  3055. bool UnwrappedAnyPointer = false;
  3056. while (Context.UnwrapSimilarTypes(FromType, ToType)) {
  3057. if (!isQualificationConversionStep(
  3058. FromType, ToType, CStyle, !UnwrappedAnyPointer,
  3059. PreviousToQualsIncludeConst, ObjCLifetimeConversion))
  3060. return false;
  3061. UnwrappedAnyPointer = true;
  3062. }
  3063. // We are left with FromType and ToType being the pointee types
  3064. // after unwrapping the original FromType and ToType the same number
  3065. // of times. If we unwrapped any pointers, and if FromType and
  3066. // ToType have the same unqualified type (since we checked
  3067. // qualifiers above), then this is a qualification conversion.
  3068. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  3069. }
  3070. /// - Determine whether this is a conversion from a scalar type to an
  3071. /// atomic type.
  3072. ///
  3073. /// If successful, updates \c SCS's second and third steps in the conversion
  3074. /// sequence to finish the conversion.
  3075. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  3076. bool InOverloadResolution,
  3077. StandardConversionSequence &SCS,
  3078. bool CStyle) {
  3079. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  3080. if (!ToAtomic)
  3081. return false;
  3082. StandardConversionSequence InnerSCS;
  3083. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  3084. InOverloadResolution, InnerSCS,
  3085. CStyle, /*AllowObjCWritebackConversion=*/false))
  3086. return false;
  3087. SCS.Second = InnerSCS.Second;
  3088. SCS.setToType(1, InnerSCS.getToType(1));
  3089. SCS.Third = InnerSCS.Third;
  3090. SCS.QualificationIncludesObjCLifetime
  3091. = InnerSCS.QualificationIncludesObjCLifetime;
  3092. SCS.setToType(2, InnerSCS.getToType(2));
  3093. return true;
  3094. }
  3095. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  3096. CXXConstructorDecl *Constructor,
  3097. QualType Type) {
  3098. const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
  3099. if (CtorType->getNumParams() > 0) {
  3100. QualType FirstArg = CtorType->getParamType(0);
  3101. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  3102. return true;
  3103. }
  3104. return false;
  3105. }
  3106. static OverloadingResult
  3107. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  3108. CXXRecordDecl *To,
  3109. UserDefinedConversionSequence &User,
  3110. OverloadCandidateSet &CandidateSet,
  3111. bool AllowExplicit) {
  3112. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3113. for (auto *D : S.LookupConstructors(To)) {
  3114. auto Info = getConstructorInfo(D);
  3115. if (!Info)
  3116. continue;
  3117. bool Usable = !Info.Constructor->isInvalidDecl() &&
  3118. S.isInitListConstructor(Info.Constructor);
  3119. if (Usable) {
  3120. bool SuppressUserConversions = false;
  3121. if (Info.ConstructorTmpl)
  3122. S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
  3123. /*ExplicitArgs*/ nullptr, From,
  3124. CandidateSet, SuppressUserConversions,
  3125. /*PartialOverloading*/ false,
  3126. AllowExplicit);
  3127. else
  3128. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
  3129. CandidateSet, SuppressUserConversions,
  3130. /*PartialOverloading*/ false, AllowExplicit);
  3131. }
  3132. }
  3133. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3134. OverloadCandidateSet::iterator Best;
  3135. switch (auto Result =
  3136. CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
  3137. case OR_Deleted:
  3138. case OR_Success: {
  3139. // Record the standard conversion we used and the conversion function.
  3140. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  3141. QualType ThisType = Constructor->getThisType();
  3142. // Initializer lists don't have conversions as such.
  3143. User.Before.setAsIdentityConversion();
  3144. User.HadMultipleCandidates = HadMultipleCandidates;
  3145. User.ConversionFunction = Constructor;
  3146. User.FoundConversionFunction = Best->FoundDecl;
  3147. User.After.setAsIdentityConversion();
  3148. User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
  3149. User.After.setAllToTypes(ToType);
  3150. return Result;
  3151. }
  3152. case OR_No_Viable_Function:
  3153. return OR_No_Viable_Function;
  3154. case OR_Ambiguous:
  3155. return OR_Ambiguous;
  3156. }
  3157. llvm_unreachable("Invalid OverloadResult!");
  3158. }
  3159. /// Determines whether there is a user-defined conversion sequence
  3160. /// (C++ [over.ics.user]) that converts expression From to the type
  3161. /// ToType. If such a conversion exists, User will contain the
  3162. /// user-defined conversion sequence that performs such a conversion
  3163. /// and this routine will return true. Otherwise, this routine returns
  3164. /// false and User is unspecified.
  3165. ///
  3166. /// \param AllowExplicit true if the conversion should consider C++0x
  3167. /// "explicit" conversion functions as well as non-explicit conversion
  3168. /// functions (C++0x [class.conv.fct]p2).
  3169. ///
  3170. /// \param AllowObjCConversionOnExplicit true if the conversion should
  3171. /// allow an extra Objective-C pointer conversion on uses of explicit
  3172. /// constructors. Requires \c AllowExplicit to also be set.
  3173. static OverloadingResult
  3174. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  3175. UserDefinedConversionSequence &User,
  3176. OverloadCandidateSet &CandidateSet,
  3177. AllowedExplicit AllowExplicit,
  3178. bool AllowObjCConversionOnExplicit) {
  3179. assert(AllowExplicit != AllowedExplicit::None ||
  3180. !AllowObjCConversionOnExplicit);
  3181. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3182. // Whether we will only visit constructors.
  3183. bool ConstructorsOnly = false;
  3184. // If the type we are conversion to is a class type, enumerate its
  3185. // constructors.
  3186. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  3187. // C++ [over.match.ctor]p1:
  3188. // When objects of class type are direct-initialized (8.5), or
  3189. // copy-initialized from an expression of the same or a
  3190. // derived class type (8.5), overload resolution selects the
  3191. // constructor. [...] For copy-initialization, the candidate
  3192. // functions are all the converting constructors (12.3.1) of
  3193. // that class. The argument list is the expression-list within
  3194. // the parentheses of the initializer.
  3195. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  3196. (From->getType()->getAs<RecordType>() &&
  3197. S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
  3198. ConstructorsOnly = true;
  3199. if (!S.isCompleteType(From->getExprLoc(), ToType)) {
  3200. // We're not going to find any constructors.
  3201. } else if (CXXRecordDecl *ToRecordDecl
  3202. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  3203. Expr **Args = &From;
  3204. unsigned NumArgs = 1;
  3205. bool ListInitializing = false;
  3206. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  3207. // But first, see if there is an init-list-constructor that will work.
  3208. OverloadingResult Result = IsInitializerListConstructorConversion(
  3209. S, From, ToType, ToRecordDecl, User, CandidateSet,
  3210. AllowExplicit == AllowedExplicit::All);
  3211. if (Result != OR_No_Viable_Function)
  3212. return Result;
  3213. // Never mind.
  3214. CandidateSet.clear(
  3215. OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3216. // If we're list-initializing, we pass the individual elements as
  3217. // arguments, not the entire list.
  3218. Args = InitList->getInits();
  3219. NumArgs = InitList->getNumInits();
  3220. ListInitializing = true;
  3221. }
  3222. for (auto *D : S.LookupConstructors(ToRecordDecl)) {
  3223. auto Info = getConstructorInfo(D);
  3224. if (!Info)
  3225. continue;
  3226. bool Usable = !Info.Constructor->isInvalidDecl();
  3227. if (!ListInitializing)
  3228. Usable = Usable && Info.Constructor->isConvertingConstructor(
  3229. /*AllowExplicit*/ true);
  3230. if (Usable) {
  3231. bool SuppressUserConversions = !ConstructorsOnly;
  3232. // C++20 [over.best.ics.general]/4.5:
  3233. // if the target is the first parameter of a constructor [of class
  3234. // X] and the constructor [...] is a candidate by [...] the second
  3235. // phase of [over.match.list] when the initializer list has exactly
  3236. // one element that is itself an initializer list, [...] and the
  3237. // conversion is to X or reference to cv X, user-defined conversion
  3238. // sequences are not cnosidered.
  3239. if (SuppressUserConversions && ListInitializing) {
  3240. SuppressUserConversions =
  3241. NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
  3242. isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
  3243. ToType);
  3244. }
  3245. if (Info.ConstructorTmpl)
  3246. S.AddTemplateOverloadCandidate(
  3247. Info.ConstructorTmpl, Info.FoundDecl,
  3248. /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
  3249. CandidateSet, SuppressUserConversions,
  3250. /*PartialOverloading*/ false,
  3251. AllowExplicit == AllowedExplicit::All);
  3252. else
  3253. // Allow one user-defined conversion when user specifies a
  3254. // From->ToType conversion via an static cast (c-style, etc).
  3255. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
  3256. llvm::ArrayRef(Args, NumArgs), CandidateSet,
  3257. SuppressUserConversions,
  3258. /*PartialOverloading*/ false,
  3259. AllowExplicit == AllowedExplicit::All);
  3260. }
  3261. }
  3262. }
  3263. }
  3264. // Enumerate conversion functions, if we're allowed to.
  3265. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  3266. } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
  3267. // No conversion functions from incomplete types.
  3268. } else if (const RecordType *FromRecordType =
  3269. From->getType()->getAs<RecordType>()) {
  3270. if (CXXRecordDecl *FromRecordDecl
  3271. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  3272. // Add all of the conversion functions as candidates.
  3273. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  3274. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3275. DeclAccessPair FoundDecl = I.getPair();
  3276. NamedDecl *D = FoundDecl.getDecl();
  3277. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  3278. if (isa<UsingShadowDecl>(D))
  3279. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3280. CXXConversionDecl *Conv;
  3281. FunctionTemplateDecl *ConvTemplate;
  3282. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  3283. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3284. else
  3285. Conv = cast<CXXConversionDecl>(D);
  3286. if (ConvTemplate)
  3287. S.AddTemplateConversionCandidate(
  3288. ConvTemplate, FoundDecl, ActingContext, From, ToType,
  3289. CandidateSet, AllowObjCConversionOnExplicit,
  3290. AllowExplicit != AllowedExplicit::None);
  3291. else
  3292. S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
  3293. CandidateSet, AllowObjCConversionOnExplicit,
  3294. AllowExplicit != AllowedExplicit::None);
  3295. }
  3296. }
  3297. }
  3298. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3299. OverloadCandidateSet::iterator Best;
  3300. switch (auto Result =
  3301. CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
  3302. case OR_Success:
  3303. case OR_Deleted:
  3304. // Record the standard conversion we used and the conversion function.
  3305. if (CXXConstructorDecl *Constructor
  3306. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  3307. // C++ [over.ics.user]p1:
  3308. // If the user-defined conversion is specified by a
  3309. // constructor (12.3.1), the initial standard conversion
  3310. // sequence converts the source type to the type required by
  3311. // the argument of the constructor.
  3312. //
  3313. QualType ThisType = Constructor->getThisType();
  3314. if (isa<InitListExpr>(From)) {
  3315. // Initializer lists don't have conversions as such.
  3316. User.Before.setAsIdentityConversion();
  3317. } else {
  3318. if (Best->Conversions[0].isEllipsis())
  3319. User.EllipsisConversion = true;
  3320. else {
  3321. User.Before = Best->Conversions[0].Standard;
  3322. User.EllipsisConversion = false;
  3323. }
  3324. }
  3325. User.HadMultipleCandidates = HadMultipleCandidates;
  3326. User.ConversionFunction = Constructor;
  3327. User.FoundConversionFunction = Best->FoundDecl;
  3328. User.After.setAsIdentityConversion();
  3329. User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
  3330. User.After.setAllToTypes(ToType);
  3331. return Result;
  3332. }
  3333. if (CXXConversionDecl *Conversion
  3334. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  3335. // C++ [over.ics.user]p1:
  3336. //
  3337. // [...] If the user-defined conversion is specified by a
  3338. // conversion function (12.3.2), the initial standard
  3339. // conversion sequence converts the source type to the
  3340. // implicit object parameter of the conversion function.
  3341. User.Before = Best->Conversions[0].Standard;
  3342. User.HadMultipleCandidates = HadMultipleCandidates;
  3343. User.ConversionFunction = Conversion;
  3344. User.FoundConversionFunction = Best->FoundDecl;
  3345. User.EllipsisConversion = false;
  3346. // C++ [over.ics.user]p2:
  3347. // The second standard conversion sequence converts the
  3348. // result of the user-defined conversion to the target type
  3349. // for the sequence. Since an implicit conversion sequence
  3350. // is an initialization, the special rules for
  3351. // initialization by user-defined conversion apply when
  3352. // selecting the best user-defined conversion for a
  3353. // user-defined conversion sequence (see 13.3.3 and
  3354. // 13.3.3.1).
  3355. User.After = Best->FinalConversion;
  3356. return Result;
  3357. }
  3358. llvm_unreachable("Not a constructor or conversion function?");
  3359. case OR_No_Viable_Function:
  3360. return OR_No_Viable_Function;
  3361. case OR_Ambiguous:
  3362. return OR_Ambiguous;
  3363. }
  3364. llvm_unreachable("Invalid OverloadResult!");
  3365. }
  3366. bool
  3367. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  3368. ImplicitConversionSequence ICS;
  3369. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  3370. OverloadCandidateSet::CSK_Normal);
  3371. OverloadingResult OvResult =
  3372. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  3373. CandidateSet, AllowedExplicit::None, false);
  3374. if (!(OvResult == OR_Ambiguous ||
  3375. (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
  3376. return false;
  3377. auto Cands = CandidateSet.CompleteCandidates(
  3378. *this,
  3379. OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
  3380. From);
  3381. if (OvResult == OR_Ambiguous)
  3382. Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
  3383. << From->getType() << ToType << From->getSourceRange();
  3384. else { // OR_No_Viable_Function && !CandidateSet.empty()
  3385. if (!RequireCompleteType(From->getBeginLoc(), ToType,
  3386. diag::err_typecheck_nonviable_condition_incomplete,
  3387. From->getType(), From->getSourceRange()))
  3388. Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
  3389. << false << From->getType() << From->getSourceRange() << ToType;
  3390. }
  3391. CandidateSet.NoteCandidates(
  3392. *this, From, Cands);
  3393. return true;
  3394. }
  3395. // Helper for compareConversionFunctions that gets the FunctionType that the
  3396. // conversion-operator return value 'points' to, or nullptr.
  3397. static const FunctionType *
  3398. getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
  3399. const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
  3400. const PointerType *RetPtrTy =
  3401. ConvFuncTy->getReturnType()->getAs<PointerType>();
  3402. if (!RetPtrTy)
  3403. return nullptr;
  3404. return RetPtrTy->getPointeeType()->getAs<FunctionType>();
  3405. }
  3406. /// Compare the user-defined conversion functions or constructors
  3407. /// of two user-defined conversion sequences to determine whether any ordering
  3408. /// is possible.
  3409. static ImplicitConversionSequence::CompareKind
  3410. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  3411. FunctionDecl *Function2) {
  3412. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  3413. CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
  3414. if (!Conv1 || !Conv2)
  3415. return ImplicitConversionSequence::Indistinguishable;
  3416. if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
  3417. return ImplicitConversionSequence::Indistinguishable;
  3418. // Objective-C++:
  3419. // If both conversion functions are implicitly-declared conversions from
  3420. // a lambda closure type to a function pointer and a block pointer,
  3421. // respectively, always prefer the conversion to a function pointer,
  3422. // because the function pointer is more lightweight and is more likely
  3423. // to keep code working.
  3424. if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
  3425. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  3426. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  3427. if (Block1 != Block2)
  3428. return Block1 ? ImplicitConversionSequence::Worse
  3429. : ImplicitConversionSequence::Better;
  3430. }
  3431. // In order to support multiple calling conventions for the lambda conversion
  3432. // operator (such as when the free and member function calling convention is
  3433. // different), prefer the 'free' mechanism, followed by the calling-convention
  3434. // of operator(). The latter is in place to support the MSVC-like solution of
  3435. // defining ALL of the possible conversions in regards to calling-convention.
  3436. const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
  3437. const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
  3438. if (Conv1FuncRet && Conv2FuncRet &&
  3439. Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
  3440. CallingConv Conv1CC = Conv1FuncRet->getCallConv();
  3441. CallingConv Conv2CC = Conv2FuncRet->getCallConv();
  3442. CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
  3443. const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
  3444. CallingConv CallOpCC =
  3445. CallOp->getType()->castAs<FunctionType>()->getCallConv();
  3446. CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
  3447. CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
  3448. CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
  3449. CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
  3450. CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
  3451. for (CallingConv CC : PrefOrder) {
  3452. if (Conv1CC == CC)
  3453. return ImplicitConversionSequence::Better;
  3454. if (Conv2CC == CC)
  3455. return ImplicitConversionSequence::Worse;
  3456. }
  3457. }
  3458. return ImplicitConversionSequence::Indistinguishable;
  3459. }
  3460. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  3461. const ImplicitConversionSequence &ICS) {
  3462. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  3463. (ICS.isUserDefined() &&
  3464. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  3465. }
  3466. /// CompareImplicitConversionSequences - Compare two implicit
  3467. /// conversion sequences to determine whether one is better than the
  3468. /// other or if they are indistinguishable (C++ 13.3.3.2).
  3469. static ImplicitConversionSequence::CompareKind
  3470. CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
  3471. const ImplicitConversionSequence& ICS1,
  3472. const ImplicitConversionSequence& ICS2)
  3473. {
  3474. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  3475. // conversion sequences (as defined in 13.3.3.1)
  3476. // -- a standard conversion sequence (13.3.3.1.1) is a better
  3477. // conversion sequence than a user-defined conversion sequence or
  3478. // an ellipsis conversion sequence, and
  3479. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3480. // conversion sequence than an ellipsis conversion sequence
  3481. // (13.3.3.1.3).
  3482. //
  3483. // C++0x [over.best.ics]p10:
  3484. // For the purpose of ranking implicit conversion sequences as
  3485. // described in 13.3.3.2, the ambiguous conversion sequence is
  3486. // treated as a user-defined sequence that is indistinguishable
  3487. // from any other user-defined conversion sequence.
  3488. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3489. // been removed from C++11. We still accept this conversion, if it happens at
  3490. // the best viable function. Otherwise, this conversion is considered worse
  3491. // than ellipsis conversion. Consider this as an extension; this is not in the
  3492. // standard. For example:
  3493. //
  3494. // int &f(...); // #1
  3495. // void f(char*); // #2
  3496. // void g() { int &r = f("foo"); }
  3497. //
  3498. // In C++03, we pick #2 as the best viable function.
  3499. // In C++11, we pick #1 as the best viable function, because ellipsis
  3500. // conversion is better than string-literal to char* conversion (since there
  3501. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3502. // convert arguments, #2 would be the best viable function in C++11.
  3503. // If the best viable function has this conversion, a warning will be issued
  3504. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3505. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3506. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3507. hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
  3508. // Ill-formedness must not differ
  3509. ICS1.isBad() == ICS2.isBad())
  3510. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3511. ? ImplicitConversionSequence::Worse
  3512. : ImplicitConversionSequence::Better;
  3513. if (ICS1.getKindRank() < ICS2.getKindRank())
  3514. return ImplicitConversionSequence::Better;
  3515. if (ICS2.getKindRank() < ICS1.getKindRank())
  3516. return ImplicitConversionSequence::Worse;
  3517. // The following checks require both conversion sequences to be of
  3518. // the same kind.
  3519. if (ICS1.getKind() != ICS2.getKind())
  3520. return ImplicitConversionSequence::Indistinguishable;
  3521. ImplicitConversionSequence::CompareKind Result =
  3522. ImplicitConversionSequence::Indistinguishable;
  3523. // Two implicit conversion sequences of the same form are
  3524. // indistinguishable conversion sequences unless one of the
  3525. // following rules apply: (C++ 13.3.3.2p3):
  3526. // List-initialization sequence L1 is a better conversion sequence than
  3527. // list-initialization sequence L2 if:
  3528. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3529. // if not that,
  3530. // — L1 and L2 convert to arrays of the same element type, and either the
  3531. // number of elements n_1 initialized by L1 is less than the number of
  3532. // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
  3533. // an array of unknown bound and L1 does not,
  3534. // even if one of the other rules in this paragraph would otherwise apply.
  3535. if (!ICS1.isBad()) {
  3536. bool StdInit1 = false, StdInit2 = false;
  3537. if (ICS1.hasInitializerListContainerType())
  3538. StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
  3539. nullptr);
  3540. if (ICS2.hasInitializerListContainerType())
  3541. StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
  3542. nullptr);
  3543. if (StdInit1 != StdInit2)
  3544. return StdInit1 ? ImplicitConversionSequence::Better
  3545. : ImplicitConversionSequence::Worse;
  3546. if (ICS1.hasInitializerListContainerType() &&
  3547. ICS2.hasInitializerListContainerType())
  3548. if (auto *CAT1 = S.Context.getAsConstantArrayType(
  3549. ICS1.getInitializerListContainerType()))
  3550. if (auto *CAT2 = S.Context.getAsConstantArrayType(
  3551. ICS2.getInitializerListContainerType())) {
  3552. if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
  3553. CAT2->getElementType())) {
  3554. // Both to arrays of the same element type
  3555. if (CAT1->getSize() != CAT2->getSize())
  3556. // Different sized, the smaller wins
  3557. return CAT1->getSize().ult(CAT2->getSize())
  3558. ? ImplicitConversionSequence::Better
  3559. : ImplicitConversionSequence::Worse;
  3560. if (ICS1.isInitializerListOfIncompleteArray() !=
  3561. ICS2.isInitializerListOfIncompleteArray())
  3562. // One is incomplete, it loses
  3563. return ICS2.isInitializerListOfIncompleteArray()
  3564. ? ImplicitConversionSequence::Better
  3565. : ImplicitConversionSequence::Worse;
  3566. }
  3567. }
  3568. }
  3569. if (ICS1.isStandard())
  3570. // Standard conversion sequence S1 is a better conversion sequence than
  3571. // standard conversion sequence S2 if [...]
  3572. Result = CompareStandardConversionSequences(S, Loc,
  3573. ICS1.Standard, ICS2.Standard);
  3574. else if (ICS1.isUserDefined()) {
  3575. // User-defined conversion sequence U1 is a better conversion
  3576. // sequence than another user-defined conversion sequence U2 if
  3577. // they contain the same user-defined conversion function or
  3578. // constructor and if the second standard conversion sequence of
  3579. // U1 is better than the second standard conversion sequence of
  3580. // U2 (C++ 13.3.3.2p3).
  3581. if (ICS1.UserDefined.ConversionFunction ==
  3582. ICS2.UserDefined.ConversionFunction)
  3583. Result = CompareStandardConversionSequences(S, Loc,
  3584. ICS1.UserDefined.After,
  3585. ICS2.UserDefined.After);
  3586. else
  3587. Result = compareConversionFunctions(S,
  3588. ICS1.UserDefined.ConversionFunction,
  3589. ICS2.UserDefined.ConversionFunction);
  3590. }
  3591. return Result;
  3592. }
  3593. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3594. // determine if one is a proper subset of the other.
  3595. static ImplicitConversionSequence::CompareKind
  3596. compareStandardConversionSubsets(ASTContext &Context,
  3597. const StandardConversionSequence& SCS1,
  3598. const StandardConversionSequence& SCS2) {
  3599. ImplicitConversionSequence::CompareKind Result
  3600. = ImplicitConversionSequence::Indistinguishable;
  3601. // the identity conversion sequence is considered to be a subsequence of
  3602. // any non-identity conversion sequence
  3603. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3604. return ImplicitConversionSequence::Better;
  3605. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3606. return ImplicitConversionSequence::Worse;
  3607. if (SCS1.Second != SCS2.Second) {
  3608. if (SCS1.Second == ICK_Identity)
  3609. Result = ImplicitConversionSequence::Better;
  3610. else if (SCS2.Second == ICK_Identity)
  3611. Result = ImplicitConversionSequence::Worse;
  3612. else
  3613. return ImplicitConversionSequence::Indistinguishable;
  3614. } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
  3615. return ImplicitConversionSequence::Indistinguishable;
  3616. if (SCS1.Third == SCS2.Third) {
  3617. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3618. : ImplicitConversionSequence::Indistinguishable;
  3619. }
  3620. if (SCS1.Third == ICK_Identity)
  3621. return Result == ImplicitConversionSequence::Worse
  3622. ? ImplicitConversionSequence::Indistinguishable
  3623. : ImplicitConversionSequence::Better;
  3624. if (SCS2.Third == ICK_Identity)
  3625. return Result == ImplicitConversionSequence::Better
  3626. ? ImplicitConversionSequence::Indistinguishable
  3627. : ImplicitConversionSequence::Worse;
  3628. return ImplicitConversionSequence::Indistinguishable;
  3629. }
  3630. /// Determine whether one of the given reference bindings is better
  3631. /// than the other based on what kind of bindings they are.
  3632. static bool
  3633. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3634. const StandardConversionSequence &SCS2) {
  3635. // C++0x [over.ics.rank]p3b4:
  3636. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3637. // implicit object parameter of a non-static member function declared
  3638. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3639. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3640. // lvalue reference to a function lvalue and S2 binds an rvalue
  3641. // reference*.
  3642. //
  3643. // FIXME: Rvalue references. We're going rogue with the above edits,
  3644. // because the semantics in the current C++0x working paper (N3225 at the
  3645. // time of this writing) break the standard definition of std::forward
  3646. // and std::reference_wrapper when dealing with references to functions.
  3647. // Proposed wording changes submitted to CWG for consideration.
  3648. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3649. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3650. return false;
  3651. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3652. SCS2.IsLvalueReference) ||
  3653. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3654. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3655. }
  3656. enum class FixedEnumPromotion {
  3657. None,
  3658. ToUnderlyingType,
  3659. ToPromotedUnderlyingType
  3660. };
  3661. /// Returns kind of fixed enum promotion the \a SCS uses.
  3662. static FixedEnumPromotion
  3663. getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
  3664. if (SCS.Second != ICK_Integral_Promotion)
  3665. return FixedEnumPromotion::None;
  3666. QualType FromType = SCS.getFromType();
  3667. if (!FromType->isEnumeralType())
  3668. return FixedEnumPromotion::None;
  3669. EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
  3670. if (!Enum->isFixed())
  3671. return FixedEnumPromotion::None;
  3672. QualType UnderlyingType = Enum->getIntegerType();
  3673. if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
  3674. return FixedEnumPromotion::ToUnderlyingType;
  3675. return FixedEnumPromotion::ToPromotedUnderlyingType;
  3676. }
  3677. /// CompareStandardConversionSequences - Compare two standard
  3678. /// conversion sequences to determine whether one is better than the
  3679. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3680. static ImplicitConversionSequence::CompareKind
  3681. CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
  3682. const StandardConversionSequence& SCS1,
  3683. const StandardConversionSequence& SCS2)
  3684. {
  3685. // Standard conversion sequence S1 is a better conversion sequence
  3686. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3687. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3688. // sequences in the canonical form defined by 13.3.3.1.1,
  3689. // excluding any Lvalue Transformation; the identity conversion
  3690. // sequence is considered to be a subsequence of any
  3691. // non-identity conversion sequence) or, if not that,
  3692. if (ImplicitConversionSequence::CompareKind CK
  3693. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3694. return CK;
  3695. // -- the rank of S1 is better than the rank of S2 (by the rules
  3696. // defined below), or, if not that,
  3697. ImplicitConversionRank Rank1 = SCS1.getRank();
  3698. ImplicitConversionRank Rank2 = SCS2.getRank();
  3699. if (Rank1 < Rank2)
  3700. return ImplicitConversionSequence::Better;
  3701. else if (Rank2 < Rank1)
  3702. return ImplicitConversionSequence::Worse;
  3703. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3704. // are indistinguishable unless one of the following rules
  3705. // applies:
  3706. // A conversion that is not a conversion of a pointer, or
  3707. // pointer to member, to bool is better than another conversion
  3708. // that is such a conversion.
  3709. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3710. return SCS2.isPointerConversionToBool()
  3711. ? ImplicitConversionSequence::Better
  3712. : ImplicitConversionSequence::Worse;
  3713. // C++14 [over.ics.rank]p4b2:
  3714. // This is retroactively applied to C++11 by CWG 1601.
  3715. //
  3716. // A conversion that promotes an enumeration whose underlying type is fixed
  3717. // to its underlying type is better than one that promotes to the promoted
  3718. // underlying type, if the two are different.
  3719. FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
  3720. FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
  3721. if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
  3722. FEP1 != FEP2)
  3723. return FEP1 == FixedEnumPromotion::ToUnderlyingType
  3724. ? ImplicitConversionSequence::Better
  3725. : ImplicitConversionSequence::Worse;
  3726. // C++ [over.ics.rank]p4b2:
  3727. //
  3728. // If class B is derived directly or indirectly from class A,
  3729. // conversion of B* to A* is better than conversion of B* to
  3730. // void*, and conversion of A* to void* is better than conversion
  3731. // of B* to void*.
  3732. bool SCS1ConvertsToVoid
  3733. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3734. bool SCS2ConvertsToVoid
  3735. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3736. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3737. // Exactly one of the conversion sequences is a conversion to
  3738. // a void pointer; it's the worse conversion.
  3739. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3740. : ImplicitConversionSequence::Worse;
  3741. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3742. // Neither conversion sequence converts to a void pointer; compare
  3743. // their derived-to-base conversions.
  3744. if (ImplicitConversionSequence::CompareKind DerivedCK
  3745. = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
  3746. return DerivedCK;
  3747. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3748. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3749. // Both conversion sequences are conversions to void
  3750. // pointers. Compare the source types to determine if there's an
  3751. // inheritance relationship in their sources.
  3752. QualType FromType1 = SCS1.getFromType();
  3753. QualType FromType2 = SCS2.getFromType();
  3754. // Adjust the types we're converting from via the array-to-pointer
  3755. // conversion, if we need to.
  3756. if (SCS1.First == ICK_Array_To_Pointer)
  3757. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3758. if (SCS2.First == ICK_Array_To_Pointer)
  3759. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3760. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3761. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3762. if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3763. return ImplicitConversionSequence::Better;
  3764. else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3765. return ImplicitConversionSequence::Worse;
  3766. // Objective-C++: If one interface is more specific than the
  3767. // other, it is the better one.
  3768. const ObjCObjectPointerType* FromObjCPtr1
  3769. = FromType1->getAs<ObjCObjectPointerType>();
  3770. const ObjCObjectPointerType* FromObjCPtr2
  3771. = FromType2->getAs<ObjCObjectPointerType>();
  3772. if (FromObjCPtr1 && FromObjCPtr2) {
  3773. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3774. FromObjCPtr2);
  3775. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3776. FromObjCPtr1);
  3777. if (AssignLeft != AssignRight) {
  3778. return AssignLeft? ImplicitConversionSequence::Better
  3779. : ImplicitConversionSequence::Worse;
  3780. }
  3781. }
  3782. }
  3783. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3784. // Check for a better reference binding based on the kind of bindings.
  3785. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3786. return ImplicitConversionSequence::Better;
  3787. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3788. return ImplicitConversionSequence::Worse;
  3789. }
  3790. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3791. // bullet 3).
  3792. if (ImplicitConversionSequence::CompareKind QualCK
  3793. = CompareQualificationConversions(S, SCS1, SCS2))
  3794. return QualCK;
  3795. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3796. // C++ [over.ics.rank]p3b4:
  3797. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3798. // which the references refer are the same type except for
  3799. // top-level cv-qualifiers, and the type to which the reference
  3800. // initialized by S2 refers is more cv-qualified than the type
  3801. // to which the reference initialized by S1 refers.
  3802. QualType T1 = SCS1.getToType(2);
  3803. QualType T2 = SCS2.getToType(2);
  3804. T1 = S.Context.getCanonicalType(T1);
  3805. T2 = S.Context.getCanonicalType(T2);
  3806. Qualifiers T1Quals, T2Quals;
  3807. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3808. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3809. if (UnqualT1 == UnqualT2) {
  3810. // Objective-C++ ARC: If the references refer to objects with different
  3811. // lifetimes, prefer bindings that don't change lifetime.
  3812. if (SCS1.ObjCLifetimeConversionBinding !=
  3813. SCS2.ObjCLifetimeConversionBinding) {
  3814. return SCS1.ObjCLifetimeConversionBinding
  3815. ? ImplicitConversionSequence::Worse
  3816. : ImplicitConversionSequence::Better;
  3817. }
  3818. // If the type is an array type, promote the element qualifiers to the
  3819. // type for comparison.
  3820. if (isa<ArrayType>(T1) && T1Quals)
  3821. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3822. if (isa<ArrayType>(T2) && T2Quals)
  3823. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3824. if (T2.isMoreQualifiedThan(T1))
  3825. return ImplicitConversionSequence::Better;
  3826. if (T1.isMoreQualifiedThan(T2))
  3827. return ImplicitConversionSequence::Worse;
  3828. }
  3829. }
  3830. // In Microsoft mode (below 19.28), prefer an integral conversion to a
  3831. // floating-to-integral conversion if the integral conversion
  3832. // is between types of the same size.
  3833. // For example:
  3834. // void f(float);
  3835. // void f(int);
  3836. // int main {
  3837. // long a;
  3838. // f(a);
  3839. // }
  3840. // Here, MSVC will call f(int) instead of generating a compile error
  3841. // as clang will do in standard mode.
  3842. if (S.getLangOpts().MSVCCompat &&
  3843. !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
  3844. SCS1.Second == ICK_Integral_Conversion &&
  3845. SCS2.Second == ICK_Floating_Integral &&
  3846. S.Context.getTypeSize(SCS1.getFromType()) ==
  3847. S.Context.getTypeSize(SCS1.getToType(2)))
  3848. return ImplicitConversionSequence::Better;
  3849. // Prefer a compatible vector conversion over a lax vector conversion
  3850. // For example:
  3851. //
  3852. // typedef float __v4sf __attribute__((__vector_size__(16)));
  3853. // void f(vector float);
  3854. // void f(vector signed int);
  3855. // int main() {
  3856. // __v4sf a;
  3857. // f(a);
  3858. // }
  3859. // Here, we'd like to choose f(vector float) and not
  3860. // report an ambiguous call error
  3861. if (SCS1.Second == ICK_Vector_Conversion &&
  3862. SCS2.Second == ICK_Vector_Conversion) {
  3863. bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
  3864. SCS1.getFromType(), SCS1.getToType(2));
  3865. bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
  3866. SCS2.getFromType(), SCS2.getToType(2));
  3867. if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
  3868. return SCS1IsCompatibleVectorConversion
  3869. ? ImplicitConversionSequence::Better
  3870. : ImplicitConversionSequence::Worse;
  3871. }
  3872. if (SCS1.Second == ICK_SVE_Vector_Conversion &&
  3873. SCS2.Second == ICK_SVE_Vector_Conversion) {
  3874. bool SCS1IsCompatibleSVEVectorConversion =
  3875. S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
  3876. bool SCS2IsCompatibleSVEVectorConversion =
  3877. S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
  3878. if (SCS1IsCompatibleSVEVectorConversion !=
  3879. SCS2IsCompatibleSVEVectorConversion)
  3880. return SCS1IsCompatibleSVEVectorConversion
  3881. ? ImplicitConversionSequence::Better
  3882. : ImplicitConversionSequence::Worse;
  3883. }
  3884. return ImplicitConversionSequence::Indistinguishable;
  3885. }
  3886. /// CompareQualificationConversions - Compares two standard conversion
  3887. /// sequences to determine whether they can be ranked based on their
  3888. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3889. static ImplicitConversionSequence::CompareKind
  3890. CompareQualificationConversions(Sema &S,
  3891. const StandardConversionSequence& SCS1,
  3892. const StandardConversionSequence& SCS2) {
  3893. // C++ [over.ics.rank]p3:
  3894. // -- S1 and S2 differ only in their qualification conversion and
  3895. // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
  3896. // [C++98]
  3897. // [...] and the cv-qualification signature of type T1 is a proper subset
  3898. // of the cv-qualification signature of type T2, and S1 is not the
  3899. // deprecated string literal array-to-pointer conversion (4.2).
  3900. // [C++2a]
  3901. // [...] where T1 can be converted to T2 by a qualification conversion.
  3902. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3903. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3904. return ImplicitConversionSequence::Indistinguishable;
  3905. // FIXME: the example in the standard doesn't use a qualification
  3906. // conversion (!)
  3907. QualType T1 = SCS1.getToType(2);
  3908. QualType T2 = SCS2.getToType(2);
  3909. T1 = S.Context.getCanonicalType(T1);
  3910. T2 = S.Context.getCanonicalType(T2);
  3911. assert(!T1->isReferenceType() && !T2->isReferenceType());
  3912. Qualifiers T1Quals, T2Quals;
  3913. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3914. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3915. // If the types are the same, we won't learn anything by unwrapping
  3916. // them.
  3917. if (UnqualT1 == UnqualT2)
  3918. return ImplicitConversionSequence::Indistinguishable;
  3919. // Don't ever prefer a standard conversion sequence that uses the deprecated
  3920. // string literal array to pointer conversion.
  3921. bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
  3922. bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
  3923. // Objective-C++ ARC:
  3924. // Prefer qualification conversions not involving a change in lifetime
  3925. // to qualification conversions that do change lifetime.
  3926. if (SCS1.QualificationIncludesObjCLifetime &&
  3927. !SCS2.QualificationIncludesObjCLifetime)
  3928. CanPick1 = false;
  3929. if (SCS2.QualificationIncludesObjCLifetime &&
  3930. !SCS1.QualificationIncludesObjCLifetime)
  3931. CanPick2 = false;
  3932. bool ObjCLifetimeConversion;
  3933. if (CanPick1 &&
  3934. !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
  3935. CanPick1 = false;
  3936. // FIXME: In Objective-C ARC, we can have qualification conversions in both
  3937. // directions, so we can't short-cut this second check in general.
  3938. if (CanPick2 &&
  3939. !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
  3940. CanPick2 = false;
  3941. if (CanPick1 != CanPick2)
  3942. return CanPick1 ? ImplicitConversionSequence::Better
  3943. : ImplicitConversionSequence::Worse;
  3944. return ImplicitConversionSequence::Indistinguishable;
  3945. }
  3946. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3947. /// sequences to determine whether they can be ranked based on their
  3948. /// various kinds of derived-to-base conversions (C++
  3949. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3950. /// conversions between Objective-C interface types.
  3951. static ImplicitConversionSequence::CompareKind
  3952. CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
  3953. const StandardConversionSequence& SCS1,
  3954. const StandardConversionSequence& SCS2) {
  3955. QualType FromType1 = SCS1.getFromType();
  3956. QualType ToType1 = SCS1.getToType(1);
  3957. QualType FromType2 = SCS2.getFromType();
  3958. QualType ToType2 = SCS2.getToType(1);
  3959. // Adjust the types we're converting from via the array-to-pointer
  3960. // conversion, if we need to.
  3961. if (SCS1.First == ICK_Array_To_Pointer)
  3962. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3963. if (SCS2.First == ICK_Array_To_Pointer)
  3964. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3965. // Canonicalize all of the types.
  3966. FromType1 = S.Context.getCanonicalType(FromType1);
  3967. ToType1 = S.Context.getCanonicalType(ToType1);
  3968. FromType2 = S.Context.getCanonicalType(FromType2);
  3969. ToType2 = S.Context.getCanonicalType(ToType2);
  3970. // C++ [over.ics.rank]p4b3:
  3971. //
  3972. // If class B is derived directly or indirectly from class A and
  3973. // class C is derived directly or indirectly from B,
  3974. //
  3975. // Compare based on pointer conversions.
  3976. if (SCS1.Second == ICK_Pointer_Conversion &&
  3977. SCS2.Second == ICK_Pointer_Conversion &&
  3978. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3979. FromType1->isPointerType() && FromType2->isPointerType() &&
  3980. ToType1->isPointerType() && ToType2->isPointerType()) {
  3981. QualType FromPointee1 =
  3982. FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3983. QualType ToPointee1 =
  3984. ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3985. QualType FromPointee2 =
  3986. FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3987. QualType ToPointee2 =
  3988. ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3989. // -- conversion of C* to B* is better than conversion of C* to A*,
  3990. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3991. if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
  3992. return ImplicitConversionSequence::Better;
  3993. else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
  3994. return ImplicitConversionSequence::Worse;
  3995. }
  3996. // -- conversion of B* to A* is better than conversion of C* to A*,
  3997. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3998. if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3999. return ImplicitConversionSequence::Better;
  4000. else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  4001. return ImplicitConversionSequence::Worse;
  4002. }
  4003. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  4004. SCS2.Second == ICK_Pointer_Conversion) {
  4005. const ObjCObjectPointerType *FromPtr1
  4006. = FromType1->getAs<ObjCObjectPointerType>();
  4007. const ObjCObjectPointerType *FromPtr2
  4008. = FromType2->getAs<ObjCObjectPointerType>();
  4009. const ObjCObjectPointerType *ToPtr1
  4010. = ToType1->getAs<ObjCObjectPointerType>();
  4011. const ObjCObjectPointerType *ToPtr2
  4012. = ToType2->getAs<ObjCObjectPointerType>();
  4013. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  4014. // Apply the same conversion ranking rules for Objective-C pointer types
  4015. // that we do for C++ pointers to class types. However, we employ the
  4016. // Objective-C pseudo-subtyping relationship used for assignment of
  4017. // Objective-C pointer types.
  4018. bool FromAssignLeft
  4019. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  4020. bool FromAssignRight
  4021. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  4022. bool ToAssignLeft
  4023. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  4024. bool ToAssignRight
  4025. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  4026. // A conversion to an a non-id object pointer type or qualified 'id'
  4027. // type is better than a conversion to 'id'.
  4028. if (ToPtr1->isObjCIdType() &&
  4029. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  4030. return ImplicitConversionSequence::Worse;
  4031. if (ToPtr2->isObjCIdType() &&
  4032. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  4033. return ImplicitConversionSequence::Better;
  4034. // A conversion to a non-id object pointer type is better than a
  4035. // conversion to a qualified 'id' type
  4036. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  4037. return ImplicitConversionSequence::Worse;
  4038. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  4039. return ImplicitConversionSequence::Better;
  4040. // A conversion to an a non-Class object pointer type or qualified 'Class'
  4041. // type is better than a conversion to 'Class'.
  4042. if (ToPtr1->isObjCClassType() &&
  4043. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  4044. return ImplicitConversionSequence::Worse;
  4045. if (ToPtr2->isObjCClassType() &&
  4046. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  4047. return ImplicitConversionSequence::Better;
  4048. // A conversion to a non-Class object pointer type is better than a
  4049. // conversion to a qualified 'Class' type.
  4050. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  4051. return ImplicitConversionSequence::Worse;
  4052. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  4053. return ImplicitConversionSequence::Better;
  4054. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  4055. if (S.Context.hasSameType(FromType1, FromType2) &&
  4056. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  4057. (ToAssignLeft != ToAssignRight)) {
  4058. if (FromPtr1->isSpecialized()) {
  4059. // "conversion of B<A> * to B * is better than conversion of B * to
  4060. // C *.
  4061. bool IsFirstSame =
  4062. FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
  4063. bool IsSecondSame =
  4064. FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
  4065. if (IsFirstSame) {
  4066. if (!IsSecondSame)
  4067. return ImplicitConversionSequence::Better;
  4068. } else if (IsSecondSame)
  4069. return ImplicitConversionSequence::Worse;
  4070. }
  4071. return ToAssignLeft? ImplicitConversionSequence::Worse
  4072. : ImplicitConversionSequence::Better;
  4073. }
  4074. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  4075. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  4076. (FromAssignLeft != FromAssignRight))
  4077. return FromAssignLeft? ImplicitConversionSequence::Better
  4078. : ImplicitConversionSequence::Worse;
  4079. }
  4080. }
  4081. // Ranking of member-pointer types.
  4082. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  4083. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  4084. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  4085. const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
  4086. const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
  4087. const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
  4088. const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
  4089. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  4090. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  4091. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  4092. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  4093. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  4094. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  4095. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  4096. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  4097. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  4098. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  4099. if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
  4100. return ImplicitConversionSequence::Worse;
  4101. else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
  4102. return ImplicitConversionSequence::Better;
  4103. }
  4104. // conversion of B::* to C::* is better than conversion of A::* to C::*
  4105. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  4106. if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  4107. return ImplicitConversionSequence::Better;
  4108. else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  4109. return ImplicitConversionSequence::Worse;
  4110. }
  4111. }
  4112. if (SCS1.Second == ICK_Derived_To_Base) {
  4113. // -- conversion of C to B is better than conversion of C to A,
  4114. // -- binding of an expression of type C to a reference of type
  4115. // B& is better than binding an expression of type C to a
  4116. // reference of type A&,
  4117. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  4118. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  4119. if (S.IsDerivedFrom(Loc, ToType1, ToType2))
  4120. return ImplicitConversionSequence::Better;
  4121. else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
  4122. return ImplicitConversionSequence::Worse;
  4123. }
  4124. // -- conversion of B to A is better than conversion of C to A.
  4125. // -- binding of an expression of type B to a reference of type
  4126. // A& is better than binding an expression of type C to a
  4127. // reference of type A&,
  4128. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  4129. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  4130. if (S.IsDerivedFrom(Loc, FromType2, FromType1))
  4131. return ImplicitConversionSequence::Better;
  4132. else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
  4133. return ImplicitConversionSequence::Worse;
  4134. }
  4135. }
  4136. return ImplicitConversionSequence::Indistinguishable;
  4137. }
  4138. static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
  4139. if (!T.getQualifiers().hasUnaligned())
  4140. return T;
  4141. Qualifiers Q;
  4142. T = Ctx.getUnqualifiedArrayType(T, Q);
  4143. Q.removeUnaligned();
  4144. return Ctx.getQualifiedType(T, Q);
  4145. }
  4146. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  4147. /// determine whether they are reference-compatible,
  4148. /// reference-related, or incompatible, for use in C++ initialization by
  4149. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  4150. /// type, and the first type (T1) is the pointee type of the reference
  4151. /// type being initialized.
  4152. Sema::ReferenceCompareResult
  4153. Sema::CompareReferenceRelationship(SourceLocation Loc,
  4154. QualType OrigT1, QualType OrigT2,
  4155. ReferenceConversions *ConvOut) {
  4156. assert(!OrigT1->isReferenceType() &&
  4157. "T1 must be the pointee type of the reference type");
  4158. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  4159. QualType T1 = Context.getCanonicalType(OrigT1);
  4160. QualType T2 = Context.getCanonicalType(OrigT2);
  4161. Qualifiers T1Quals, T2Quals;
  4162. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  4163. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  4164. ReferenceConversions ConvTmp;
  4165. ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
  4166. Conv = ReferenceConversions();
  4167. // C++2a [dcl.init.ref]p4:
  4168. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  4169. // reference-related to "cv2 T2" if T1 is similar to T2, or
  4170. // T1 is a base class of T2.
  4171. // "cv1 T1" is reference-compatible with "cv2 T2" if
  4172. // a prvalue of type "pointer to cv2 T2" can be converted to the type
  4173. // "pointer to cv1 T1" via a standard conversion sequence.
  4174. // Check for standard conversions we can apply to pointers: derived-to-base
  4175. // conversions, ObjC pointer conversions, and function pointer conversions.
  4176. // (Qualification conversions are checked last.)
  4177. QualType ConvertedT2;
  4178. if (UnqualT1 == UnqualT2) {
  4179. // Nothing to do.
  4180. } else if (isCompleteType(Loc, OrigT2) &&
  4181. IsDerivedFrom(Loc, UnqualT2, UnqualT1))
  4182. Conv |= ReferenceConversions::DerivedToBase;
  4183. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  4184. UnqualT2->isObjCObjectOrInterfaceType() &&
  4185. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  4186. Conv |= ReferenceConversions::ObjC;
  4187. else if (UnqualT2->isFunctionType() &&
  4188. IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
  4189. Conv |= ReferenceConversions::Function;
  4190. // No need to check qualifiers; function types don't have them.
  4191. return Ref_Compatible;
  4192. }
  4193. bool ConvertedReferent = Conv != 0;
  4194. // We can have a qualification conversion. Compute whether the types are
  4195. // similar at the same time.
  4196. bool PreviousToQualsIncludeConst = true;
  4197. bool TopLevel = true;
  4198. do {
  4199. if (T1 == T2)
  4200. break;
  4201. // We will need a qualification conversion.
  4202. Conv |= ReferenceConversions::Qualification;
  4203. // Track whether we performed a qualification conversion anywhere other
  4204. // than the top level. This matters for ranking reference bindings in
  4205. // overload resolution.
  4206. if (!TopLevel)
  4207. Conv |= ReferenceConversions::NestedQualification;
  4208. // MS compiler ignores __unaligned qualifier for references; do the same.
  4209. T1 = withoutUnaligned(Context, T1);
  4210. T2 = withoutUnaligned(Context, T2);
  4211. // If we find a qualifier mismatch, the types are not reference-compatible,
  4212. // but are still be reference-related if they're similar.
  4213. bool ObjCLifetimeConversion = false;
  4214. if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
  4215. PreviousToQualsIncludeConst,
  4216. ObjCLifetimeConversion))
  4217. return (ConvertedReferent || Context.hasSimilarType(T1, T2))
  4218. ? Ref_Related
  4219. : Ref_Incompatible;
  4220. // FIXME: Should we track this for any level other than the first?
  4221. if (ObjCLifetimeConversion)
  4222. Conv |= ReferenceConversions::ObjCLifetime;
  4223. TopLevel = false;
  4224. } while (Context.UnwrapSimilarTypes(T1, T2));
  4225. // At this point, if the types are reference-related, we must either have the
  4226. // same inner type (ignoring qualifiers), or must have already worked out how
  4227. // to convert the referent.
  4228. return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
  4229. ? Ref_Compatible
  4230. : Ref_Incompatible;
  4231. }
  4232. /// Look for a user-defined conversion to a value reference-compatible
  4233. /// with DeclType. Return true if something definite is found.
  4234. static bool
  4235. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  4236. QualType DeclType, SourceLocation DeclLoc,
  4237. Expr *Init, QualType T2, bool AllowRvalues,
  4238. bool AllowExplicit) {
  4239. assert(T2->isRecordType() && "Can only find conversions of record types.");
  4240. auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
  4241. OverloadCandidateSet CandidateSet(
  4242. DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4243. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  4244. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4245. NamedDecl *D = *I;
  4246. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4247. if (isa<UsingShadowDecl>(D))
  4248. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4249. FunctionTemplateDecl *ConvTemplate
  4250. = dyn_cast<FunctionTemplateDecl>(D);
  4251. CXXConversionDecl *Conv;
  4252. if (ConvTemplate)
  4253. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4254. else
  4255. Conv = cast<CXXConversionDecl>(D);
  4256. if (AllowRvalues) {
  4257. // If we are initializing an rvalue reference, don't permit conversion
  4258. // functions that return lvalues.
  4259. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  4260. const ReferenceType *RefType
  4261. = Conv->getConversionType()->getAs<LValueReferenceType>();
  4262. if (RefType && !RefType->getPointeeType()->isFunctionType())
  4263. continue;
  4264. }
  4265. if (!ConvTemplate &&
  4266. S.CompareReferenceRelationship(
  4267. DeclLoc,
  4268. Conv->getConversionType()
  4269. .getNonReferenceType()
  4270. .getUnqualifiedType(),
  4271. DeclType.getNonReferenceType().getUnqualifiedType()) ==
  4272. Sema::Ref_Incompatible)
  4273. continue;
  4274. } else {
  4275. // If the conversion function doesn't return a reference type,
  4276. // it can't be considered for this conversion. An rvalue reference
  4277. // is only acceptable if its referencee is a function type.
  4278. const ReferenceType *RefType =
  4279. Conv->getConversionType()->getAs<ReferenceType>();
  4280. if (!RefType ||
  4281. (!RefType->isLValueReferenceType() &&
  4282. !RefType->getPointeeType()->isFunctionType()))
  4283. continue;
  4284. }
  4285. if (ConvTemplate)
  4286. S.AddTemplateConversionCandidate(
  4287. ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4288. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4289. else
  4290. S.AddConversionCandidate(
  4291. Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4292. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4293. }
  4294. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4295. OverloadCandidateSet::iterator Best;
  4296. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  4297. case OR_Success:
  4298. // C++ [over.ics.ref]p1:
  4299. //
  4300. // [...] If the parameter binds directly to the result of
  4301. // applying a conversion function to the argument
  4302. // expression, the implicit conversion sequence is a
  4303. // user-defined conversion sequence (13.3.3.1.2), with the
  4304. // second standard conversion sequence either an identity
  4305. // conversion or, if the conversion function returns an
  4306. // entity of a type that is a derived class of the parameter
  4307. // type, a derived-to-base Conversion.
  4308. if (!Best->FinalConversion.DirectBinding)
  4309. return false;
  4310. ICS.setUserDefined();
  4311. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  4312. ICS.UserDefined.After = Best->FinalConversion;
  4313. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  4314. ICS.UserDefined.ConversionFunction = Best->Function;
  4315. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  4316. ICS.UserDefined.EllipsisConversion = false;
  4317. assert(ICS.UserDefined.After.ReferenceBinding &&
  4318. ICS.UserDefined.After.DirectBinding &&
  4319. "Expected a direct reference binding!");
  4320. return true;
  4321. case OR_Ambiguous:
  4322. ICS.setAmbiguous();
  4323. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  4324. Cand != CandidateSet.end(); ++Cand)
  4325. if (Cand->Best)
  4326. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  4327. return true;
  4328. case OR_No_Viable_Function:
  4329. case OR_Deleted:
  4330. // There was no suitable conversion, or we found a deleted
  4331. // conversion; continue with other checks.
  4332. return false;
  4333. }
  4334. llvm_unreachable("Invalid OverloadResult!");
  4335. }
  4336. /// Compute an implicit conversion sequence for reference
  4337. /// initialization.
  4338. static ImplicitConversionSequence
  4339. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  4340. SourceLocation DeclLoc,
  4341. bool SuppressUserConversions,
  4342. bool AllowExplicit) {
  4343. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  4344. // Most paths end in a failed conversion.
  4345. ImplicitConversionSequence ICS;
  4346. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4347. QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
  4348. QualType T2 = Init->getType();
  4349. // If the initializer is the address of an overloaded function, try
  4350. // to resolve the overloaded function. If all goes well, T2 is the
  4351. // type of the resulting function.
  4352. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4353. DeclAccessPair Found;
  4354. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  4355. false, Found))
  4356. T2 = Fn->getType();
  4357. }
  4358. // Compute some basic properties of the types and the initializer.
  4359. bool isRValRef = DeclType->isRValueReferenceType();
  4360. Expr::Classification InitCategory = Init->Classify(S.Context);
  4361. Sema::ReferenceConversions RefConv;
  4362. Sema::ReferenceCompareResult RefRelationship =
  4363. S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
  4364. auto SetAsReferenceBinding = [&](bool BindsDirectly) {
  4365. ICS.setStandard();
  4366. ICS.Standard.First = ICK_Identity;
  4367. // FIXME: A reference binding can be a function conversion too. We should
  4368. // consider that when ordering reference-to-function bindings.
  4369. ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
  4370. ? ICK_Derived_To_Base
  4371. : (RefConv & Sema::ReferenceConversions::ObjC)
  4372. ? ICK_Compatible_Conversion
  4373. : ICK_Identity;
  4374. // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
  4375. // a reference binding that performs a non-top-level qualification
  4376. // conversion as a qualification conversion, not as an identity conversion.
  4377. ICS.Standard.Third = (RefConv &
  4378. Sema::ReferenceConversions::NestedQualification)
  4379. ? ICK_Qualification
  4380. : ICK_Identity;
  4381. ICS.Standard.setFromType(T2);
  4382. ICS.Standard.setToType(0, T2);
  4383. ICS.Standard.setToType(1, T1);
  4384. ICS.Standard.setToType(2, T1);
  4385. ICS.Standard.ReferenceBinding = true;
  4386. ICS.Standard.DirectBinding = BindsDirectly;
  4387. ICS.Standard.IsLvalueReference = !isRValRef;
  4388. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4389. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  4390. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4391. ICS.Standard.ObjCLifetimeConversionBinding =
  4392. (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
  4393. ICS.Standard.CopyConstructor = nullptr;
  4394. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4395. };
  4396. // C++0x [dcl.init.ref]p5:
  4397. // A reference to type "cv1 T1" is initialized by an expression
  4398. // of type "cv2 T2" as follows:
  4399. // -- If reference is an lvalue reference and the initializer expression
  4400. if (!isRValRef) {
  4401. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  4402. // reference-compatible with "cv2 T2," or
  4403. //
  4404. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  4405. if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
  4406. // C++ [over.ics.ref]p1:
  4407. // When a parameter of reference type binds directly (8.5.3)
  4408. // to an argument expression, the implicit conversion sequence
  4409. // is the identity conversion, unless the argument expression
  4410. // has a type that is a derived class of the parameter type,
  4411. // in which case the implicit conversion sequence is a
  4412. // derived-to-base Conversion (13.3.3.1).
  4413. SetAsReferenceBinding(/*BindsDirectly=*/true);
  4414. // Nothing more to do: the inaccessibility/ambiguity check for
  4415. // derived-to-base conversions is suppressed when we're
  4416. // computing the implicit conversion sequence (C++
  4417. // [over.best.ics]p2).
  4418. return ICS;
  4419. }
  4420. // -- has a class type (i.e., T2 is a class type), where T1 is
  4421. // not reference-related to T2, and can be implicitly
  4422. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  4423. // is reference-compatible with "cv3 T3" 92) (this
  4424. // conversion is selected by enumerating the applicable
  4425. // conversion functions (13.3.1.6) and choosing the best
  4426. // one through overload resolution (13.3)),
  4427. if (!SuppressUserConversions && T2->isRecordType() &&
  4428. S.isCompleteType(DeclLoc, T2) &&
  4429. RefRelationship == Sema::Ref_Incompatible) {
  4430. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4431. Init, T2, /*AllowRvalues=*/false,
  4432. AllowExplicit))
  4433. return ICS;
  4434. }
  4435. }
  4436. // -- Otherwise, the reference shall be an lvalue reference to a
  4437. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4438. // shall be an rvalue reference.
  4439. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
  4440. if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
  4441. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4442. return ICS;
  4443. }
  4444. // -- If the initializer expression
  4445. //
  4446. // -- is an xvalue, class prvalue, array prvalue or function
  4447. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  4448. if (RefRelationship == Sema::Ref_Compatible &&
  4449. (InitCategory.isXValue() ||
  4450. (InitCategory.isPRValue() &&
  4451. (T2->isRecordType() || T2->isArrayType())) ||
  4452. (InitCategory.isLValue() && T2->isFunctionType()))) {
  4453. // In C++11, this is always a direct binding. In C++98/03, it's a direct
  4454. // binding unless we're binding to a class prvalue.
  4455. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  4456. // allow the use of rvalue references in C++98/03 for the benefit of
  4457. // standard library implementors; therefore, we need the xvalue check here.
  4458. SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
  4459. !(InitCategory.isPRValue() || T2->isRecordType()));
  4460. return ICS;
  4461. }
  4462. // -- has a class type (i.e., T2 is a class type), where T1 is not
  4463. // reference-related to T2, and can be implicitly converted to
  4464. // an xvalue, class prvalue, or function lvalue of type
  4465. // "cv3 T3", where "cv1 T1" is reference-compatible with
  4466. // "cv3 T3",
  4467. //
  4468. // then the reference is bound to the value of the initializer
  4469. // expression in the first case and to the result of the conversion
  4470. // in the second case (or, in either case, to an appropriate base
  4471. // class subobject).
  4472. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4473. T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
  4474. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4475. Init, T2, /*AllowRvalues=*/true,
  4476. AllowExplicit)) {
  4477. // In the second case, if the reference is an rvalue reference
  4478. // and the second standard conversion sequence of the
  4479. // user-defined conversion sequence includes an lvalue-to-rvalue
  4480. // conversion, the program is ill-formed.
  4481. if (ICS.isUserDefined() && isRValRef &&
  4482. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  4483. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4484. return ICS;
  4485. }
  4486. // A temporary of function type cannot be created; don't even try.
  4487. if (T1->isFunctionType())
  4488. return ICS;
  4489. // -- Otherwise, a temporary of type "cv1 T1" is created and
  4490. // initialized from the initializer expression using the
  4491. // rules for a non-reference copy initialization (8.5). The
  4492. // reference is then bound to the temporary. If T1 is
  4493. // reference-related to T2, cv1 must be the same
  4494. // cv-qualification as, or greater cv-qualification than,
  4495. // cv2; otherwise, the program is ill-formed.
  4496. if (RefRelationship == Sema::Ref_Related) {
  4497. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  4498. // we would be reference-compatible or reference-compatible with
  4499. // added qualification. But that wasn't the case, so the reference
  4500. // initialization fails.
  4501. //
  4502. // Note that we only want to check address spaces and cvr-qualifiers here.
  4503. // ObjC GC, lifetime and unaligned qualifiers aren't important.
  4504. Qualifiers T1Quals = T1.getQualifiers();
  4505. Qualifiers T2Quals = T2.getQualifiers();
  4506. T1Quals.removeObjCGCAttr();
  4507. T1Quals.removeObjCLifetime();
  4508. T2Quals.removeObjCGCAttr();
  4509. T2Quals.removeObjCLifetime();
  4510. // MS compiler ignores __unaligned qualifier for references; do the same.
  4511. T1Quals.removeUnaligned();
  4512. T2Quals.removeUnaligned();
  4513. if (!T1Quals.compatiblyIncludes(T2Quals))
  4514. return ICS;
  4515. }
  4516. // If at least one of the types is a class type, the types are not
  4517. // related, and we aren't allowed any user conversions, the
  4518. // reference binding fails. This case is important for breaking
  4519. // recursion, since TryImplicitConversion below will attempt to
  4520. // create a temporary through the use of a copy constructor.
  4521. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4522. (T1->isRecordType() || T2->isRecordType()))
  4523. return ICS;
  4524. // If T1 is reference-related to T2 and the reference is an rvalue
  4525. // reference, the initializer expression shall not be an lvalue.
  4526. if (RefRelationship >= Sema::Ref_Related && isRValRef &&
  4527. Init->Classify(S.Context).isLValue()) {
  4528. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
  4529. return ICS;
  4530. }
  4531. // C++ [over.ics.ref]p2:
  4532. // When a parameter of reference type is not bound directly to
  4533. // an argument expression, the conversion sequence is the one
  4534. // required to convert the argument expression to the
  4535. // underlying type of the reference according to
  4536. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  4537. // to copy-initializing a temporary of the underlying type with
  4538. // the argument expression. Any difference in top-level
  4539. // cv-qualification is subsumed by the initialization itself
  4540. // and does not constitute a conversion.
  4541. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4542. AllowedExplicit::None,
  4543. /*InOverloadResolution=*/false,
  4544. /*CStyle=*/false,
  4545. /*AllowObjCWritebackConversion=*/false,
  4546. /*AllowObjCConversionOnExplicit=*/false);
  4547. // Of course, that's still a reference binding.
  4548. if (ICS.isStandard()) {
  4549. ICS.Standard.ReferenceBinding = true;
  4550. ICS.Standard.IsLvalueReference = !isRValRef;
  4551. ICS.Standard.BindsToFunctionLvalue = false;
  4552. ICS.Standard.BindsToRvalue = true;
  4553. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4554. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4555. } else if (ICS.isUserDefined()) {
  4556. const ReferenceType *LValRefType =
  4557. ICS.UserDefined.ConversionFunction->getReturnType()
  4558. ->getAs<LValueReferenceType>();
  4559. // C++ [over.ics.ref]p3:
  4560. // Except for an implicit object parameter, for which see 13.3.1, a
  4561. // standard conversion sequence cannot be formed if it requires [...]
  4562. // binding an rvalue reference to an lvalue other than a function
  4563. // lvalue.
  4564. // Note that the function case is not possible here.
  4565. if (isRValRef && LValRefType) {
  4566. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4567. return ICS;
  4568. }
  4569. ICS.UserDefined.After.ReferenceBinding = true;
  4570. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4571. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4572. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4573. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4574. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4575. }
  4576. return ICS;
  4577. }
  4578. static ImplicitConversionSequence
  4579. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4580. bool SuppressUserConversions,
  4581. bool InOverloadResolution,
  4582. bool AllowObjCWritebackConversion,
  4583. bool AllowExplicit = false);
  4584. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4585. /// initializer list From.
  4586. static ImplicitConversionSequence
  4587. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4588. bool SuppressUserConversions,
  4589. bool InOverloadResolution,
  4590. bool AllowObjCWritebackConversion) {
  4591. // C++11 [over.ics.list]p1:
  4592. // When an argument is an initializer list, it is not an expression and
  4593. // special rules apply for converting it to a parameter type.
  4594. ImplicitConversionSequence Result;
  4595. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4596. // We need a complete type for what follows. With one C++20 exception,
  4597. // incomplete types can never be initialized from init lists.
  4598. QualType InitTy = ToType;
  4599. const ArrayType *AT = S.Context.getAsArrayType(ToType);
  4600. if (AT && S.getLangOpts().CPlusPlus20)
  4601. if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
  4602. // C++20 allows list initialization of an incomplete array type.
  4603. InitTy = IAT->getElementType();
  4604. if (!S.isCompleteType(From->getBeginLoc(), InitTy))
  4605. return Result;
  4606. // Per DR1467:
  4607. // If the parameter type is a class X and the initializer list has a single
  4608. // element of type cv U, where U is X or a class derived from X, the
  4609. // implicit conversion sequence is the one required to convert the element
  4610. // to the parameter type.
  4611. //
  4612. // Otherwise, if the parameter type is a character array [... ]
  4613. // and the initializer list has a single element that is an
  4614. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4615. // implicit conversion sequence is the identity conversion.
  4616. if (From->getNumInits() == 1) {
  4617. if (ToType->isRecordType()) {
  4618. QualType InitType = From->getInit(0)->getType();
  4619. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4620. S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
  4621. return TryCopyInitialization(S, From->getInit(0), ToType,
  4622. SuppressUserConversions,
  4623. InOverloadResolution,
  4624. AllowObjCWritebackConversion);
  4625. }
  4626. if (AT && S.IsStringInit(From->getInit(0), AT)) {
  4627. InitializedEntity Entity =
  4628. InitializedEntity::InitializeParameter(S.Context, ToType,
  4629. /*Consumed=*/false);
  4630. if (S.CanPerformCopyInitialization(Entity, From)) {
  4631. Result.setStandard();
  4632. Result.Standard.setAsIdentityConversion();
  4633. Result.Standard.setFromType(ToType);
  4634. Result.Standard.setAllToTypes(ToType);
  4635. return Result;
  4636. }
  4637. }
  4638. }
  4639. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4640. // C++11 [over.ics.list]p2:
  4641. // If the parameter type is std::initializer_list<X> or "array of X" and
  4642. // all the elements can be implicitly converted to X, the implicit
  4643. // conversion sequence is the worst conversion necessary to convert an
  4644. // element of the list to X.
  4645. //
  4646. // C++14 [over.ics.list]p3:
  4647. // Otherwise, if the parameter type is "array of N X", if the initializer
  4648. // list has exactly N elements or if it has fewer than N elements and X is
  4649. // default-constructible, and if all the elements of the initializer list
  4650. // can be implicitly converted to X, the implicit conversion sequence is
  4651. // the worst conversion necessary to convert an element of the list to X.
  4652. if (AT || S.isStdInitializerList(ToType, &InitTy)) {
  4653. unsigned e = From->getNumInits();
  4654. ImplicitConversionSequence DfltElt;
  4655. DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
  4656. QualType());
  4657. QualType ContTy = ToType;
  4658. bool IsUnbounded = false;
  4659. if (AT) {
  4660. InitTy = AT->getElementType();
  4661. if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
  4662. if (CT->getSize().ult(e)) {
  4663. // Too many inits, fatally bad
  4664. Result.setBad(BadConversionSequence::too_many_initializers, From,
  4665. ToType);
  4666. Result.setInitializerListContainerType(ContTy, IsUnbounded);
  4667. return Result;
  4668. }
  4669. if (CT->getSize().ugt(e)) {
  4670. // Need an init from empty {}, is there one?
  4671. InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
  4672. From->getEndLoc());
  4673. EmptyList.setType(S.Context.VoidTy);
  4674. DfltElt = TryListConversion(
  4675. S, &EmptyList, InitTy, SuppressUserConversions,
  4676. InOverloadResolution, AllowObjCWritebackConversion);
  4677. if (DfltElt.isBad()) {
  4678. // No {} init, fatally bad
  4679. Result.setBad(BadConversionSequence::too_few_initializers, From,
  4680. ToType);
  4681. Result.setInitializerListContainerType(ContTy, IsUnbounded);
  4682. return Result;
  4683. }
  4684. }
  4685. } else {
  4686. assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
  4687. IsUnbounded = true;
  4688. if (!e) {
  4689. // Cannot convert to zero-sized.
  4690. Result.setBad(BadConversionSequence::too_few_initializers, From,
  4691. ToType);
  4692. Result.setInitializerListContainerType(ContTy, IsUnbounded);
  4693. return Result;
  4694. }
  4695. llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
  4696. ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
  4697. ArrayType::Normal, 0);
  4698. }
  4699. }
  4700. Result.setStandard();
  4701. Result.Standard.setAsIdentityConversion();
  4702. Result.Standard.setFromType(InitTy);
  4703. Result.Standard.setAllToTypes(InitTy);
  4704. for (unsigned i = 0; i < e; ++i) {
  4705. Expr *Init = From->getInit(i);
  4706. ImplicitConversionSequence ICS = TryCopyInitialization(
  4707. S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
  4708. AllowObjCWritebackConversion);
  4709. // Keep the worse conversion seen so far.
  4710. // FIXME: Sequences are not totally ordered, so 'worse' can be
  4711. // ambiguous. CWG has been informed.
  4712. if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
  4713. Result) ==
  4714. ImplicitConversionSequence::Worse) {
  4715. Result = ICS;
  4716. // Bail as soon as we find something unconvertible.
  4717. if (Result.isBad()) {
  4718. Result.setInitializerListContainerType(ContTy, IsUnbounded);
  4719. return Result;
  4720. }
  4721. }
  4722. }
  4723. // If we needed any implicit {} initialization, compare that now.
  4724. // over.ics.list/6 indicates we should compare that conversion. Again CWG
  4725. // has been informed that this might not be the best thing.
  4726. if (!DfltElt.isBad() && CompareImplicitConversionSequences(
  4727. S, From->getEndLoc(), DfltElt, Result) ==
  4728. ImplicitConversionSequence::Worse)
  4729. Result = DfltElt;
  4730. // Record the type being initialized so that we may compare sequences
  4731. Result.setInitializerListContainerType(ContTy, IsUnbounded);
  4732. return Result;
  4733. }
  4734. // C++14 [over.ics.list]p4:
  4735. // C++11 [over.ics.list]p3:
  4736. // Otherwise, if the parameter is a non-aggregate class X and overload
  4737. // resolution chooses a single best constructor [...] the implicit
  4738. // conversion sequence is a user-defined conversion sequence. If multiple
  4739. // constructors are viable but none is better than the others, the
  4740. // implicit conversion sequence is a user-defined conversion sequence.
  4741. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4742. // This function can deal with initializer lists.
  4743. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4744. AllowedExplicit::None,
  4745. InOverloadResolution, /*CStyle=*/false,
  4746. AllowObjCWritebackConversion,
  4747. /*AllowObjCConversionOnExplicit=*/false);
  4748. }
  4749. // C++14 [over.ics.list]p5:
  4750. // C++11 [over.ics.list]p4:
  4751. // Otherwise, if the parameter has an aggregate type which can be
  4752. // initialized from the initializer list [...] the implicit conversion
  4753. // sequence is a user-defined conversion sequence.
  4754. if (ToType->isAggregateType()) {
  4755. // Type is an aggregate, argument is an init list. At this point it comes
  4756. // down to checking whether the initialization works.
  4757. // FIXME: Find out whether this parameter is consumed or not.
  4758. InitializedEntity Entity =
  4759. InitializedEntity::InitializeParameter(S.Context, ToType,
  4760. /*Consumed=*/false);
  4761. if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
  4762. From)) {
  4763. Result.setUserDefined();
  4764. Result.UserDefined.Before.setAsIdentityConversion();
  4765. // Initializer lists don't have a type.
  4766. Result.UserDefined.Before.setFromType(QualType());
  4767. Result.UserDefined.Before.setAllToTypes(QualType());
  4768. Result.UserDefined.After.setAsIdentityConversion();
  4769. Result.UserDefined.After.setFromType(ToType);
  4770. Result.UserDefined.After.setAllToTypes(ToType);
  4771. Result.UserDefined.ConversionFunction = nullptr;
  4772. }
  4773. return Result;
  4774. }
  4775. // C++14 [over.ics.list]p6:
  4776. // C++11 [over.ics.list]p5:
  4777. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4778. if (ToType->isReferenceType()) {
  4779. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4780. // mention initializer lists in any way. So we go by what list-
  4781. // initialization would do and try to extrapolate from that.
  4782. QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
  4783. // If the initializer list has a single element that is reference-related
  4784. // to the parameter type, we initialize the reference from that.
  4785. if (From->getNumInits() == 1) {
  4786. Expr *Init = From->getInit(0);
  4787. QualType T2 = Init->getType();
  4788. // If the initializer is the address of an overloaded function, try
  4789. // to resolve the overloaded function. If all goes well, T2 is the
  4790. // type of the resulting function.
  4791. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4792. DeclAccessPair Found;
  4793. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4794. Init, ToType, false, Found))
  4795. T2 = Fn->getType();
  4796. }
  4797. // Compute some basic properties of the types and the initializer.
  4798. Sema::ReferenceCompareResult RefRelationship =
  4799. S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
  4800. if (RefRelationship >= Sema::Ref_Related) {
  4801. return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
  4802. SuppressUserConversions,
  4803. /*AllowExplicit=*/false);
  4804. }
  4805. }
  4806. // Otherwise, we bind the reference to a temporary created from the
  4807. // initializer list.
  4808. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4809. InOverloadResolution,
  4810. AllowObjCWritebackConversion);
  4811. if (Result.isFailure())
  4812. return Result;
  4813. assert(!Result.isEllipsis() &&
  4814. "Sub-initialization cannot result in ellipsis conversion.");
  4815. // Can we even bind to a temporary?
  4816. if (ToType->isRValueReferenceType() ||
  4817. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4818. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4819. Result.UserDefined.After;
  4820. SCS.ReferenceBinding = true;
  4821. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4822. SCS.BindsToRvalue = true;
  4823. SCS.BindsToFunctionLvalue = false;
  4824. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4825. SCS.ObjCLifetimeConversionBinding = false;
  4826. } else
  4827. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4828. From, ToType);
  4829. return Result;
  4830. }
  4831. // C++14 [over.ics.list]p7:
  4832. // C++11 [over.ics.list]p6:
  4833. // Otherwise, if the parameter type is not a class:
  4834. if (!ToType->isRecordType()) {
  4835. // - if the initializer list has one element that is not itself an
  4836. // initializer list, the implicit conversion sequence is the one
  4837. // required to convert the element to the parameter type.
  4838. unsigned NumInits = From->getNumInits();
  4839. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4840. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4841. SuppressUserConversions,
  4842. InOverloadResolution,
  4843. AllowObjCWritebackConversion);
  4844. // - if the initializer list has no elements, the implicit conversion
  4845. // sequence is the identity conversion.
  4846. else if (NumInits == 0) {
  4847. Result.setStandard();
  4848. Result.Standard.setAsIdentityConversion();
  4849. Result.Standard.setFromType(ToType);
  4850. Result.Standard.setAllToTypes(ToType);
  4851. }
  4852. return Result;
  4853. }
  4854. // C++14 [over.ics.list]p8:
  4855. // C++11 [over.ics.list]p7:
  4856. // In all cases other than those enumerated above, no conversion is possible
  4857. return Result;
  4858. }
  4859. /// TryCopyInitialization - Try to copy-initialize a value of type
  4860. /// ToType from the expression From. Return the implicit conversion
  4861. /// sequence required to pass this argument, which may be a bad
  4862. /// conversion sequence (meaning that the argument cannot be passed to
  4863. /// a parameter of this type). If @p SuppressUserConversions, then we
  4864. /// do not permit any user-defined conversion sequences.
  4865. static ImplicitConversionSequence
  4866. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4867. bool SuppressUserConversions,
  4868. bool InOverloadResolution,
  4869. bool AllowObjCWritebackConversion,
  4870. bool AllowExplicit) {
  4871. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4872. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4873. InOverloadResolution,AllowObjCWritebackConversion);
  4874. if (ToType->isReferenceType())
  4875. return TryReferenceInit(S, From, ToType,
  4876. /*FIXME:*/ From->getBeginLoc(),
  4877. SuppressUserConversions, AllowExplicit);
  4878. return TryImplicitConversion(S, From, ToType,
  4879. SuppressUserConversions,
  4880. AllowedExplicit::None,
  4881. InOverloadResolution,
  4882. /*CStyle=*/false,
  4883. AllowObjCWritebackConversion,
  4884. /*AllowObjCConversionOnExplicit=*/false);
  4885. }
  4886. static bool TryCopyInitialization(const CanQualType FromQTy,
  4887. const CanQualType ToQTy,
  4888. Sema &S,
  4889. SourceLocation Loc,
  4890. ExprValueKind FromVK) {
  4891. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4892. ImplicitConversionSequence ICS =
  4893. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4894. return !ICS.isBad();
  4895. }
  4896. /// TryObjectArgumentInitialization - Try to initialize the object
  4897. /// parameter of the given member function (@c Method) from the
  4898. /// expression @p From.
  4899. static ImplicitConversionSequence
  4900. TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
  4901. Expr::Classification FromClassification,
  4902. CXXMethodDecl *Method,
  4903. CXXRecordDecl *ActingContext) {
  4904. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4905. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4906. // const volatile object.
  4907. Qualifiers Quals = Method->getMethodQualifiers();
  4908. if (isa<CXXDestructorDecl>(Method)) {
  4909. Quals.addConst();
  4910. Quals.addVolatile();
  4911. }
  4912. QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
  4913. // Set up the conversion sequence as a "bad" conversion, to allow us
  4914. // to exit early.
  4915. ImplicitConversionSequence ICS;
  4916. // We need to have an object of class type.
  4917. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4918. FromType = PT->getPointeeType();
  4919. // When we had a pointer, it's implicitly dereferenced, so we
  4920. // better have an lvalue.
  4921. assert(FromClassification.isLValue());
  4922. }
  4923. assert(FromType->isRecordType());
  4924. // C++0x [over.match.funcs]p4:
  4925. // For non-static member functions, the type of the implicit object
  4926. // parameter is
  4927. //
  4928. // - "lvalue reference to cv X" for functions declared without a
  4929. // ref-qualifier or with the & ref-qualifier
  4930. // - "rvalue reference to cv X" for functions declared with the &&
  4931. // ref-qualifier
  4932. //
  4933. // where X is the class of which the function is a member and cv is the
  4934. // cv-qualification on the member function declaration.
  4935. //
  4936. // However, when finding an implicit conversion sequence for the argument, we
  4937. // are not allowed to perform user-defined conversions
  4938. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4939. // reference binding here, that allows class rvalues to bind to
  4940. // non-constant references.
  4941. // First check the qualifiers.
  4942. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4943. if (ImplicitParamType.getCVRQualifiers()
  4944. != FromTypeCanon.getLocalCVRQualifiers() &&
  4945. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4946. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4947. FromType, ImplicitParamType);
  4948. return ICS;
  4949. }
  4950. if (FromTypeCanon.hasAddressSpace()) {
  4951. Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
  4952. Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
  4953. if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
  4954. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4955. FromType, ImplicitParamType);
  4956. return ICS;
  4957. }
  4958. }
  4959. // Check that we have either the same type or a derived type. It
  4960. // affects the conversion rank.
  4961. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4962. ImplicitConversionKind SecondKind;
  4963. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4964. SecondKind = ICK_Identity;
  4965. } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
  4966. SecondKind = ICK_Derived_To_Base;
  4967. else {
  4968. ICS.setBad(BadConversionSequence::unrelated_class,
  4969. FromType, ImplicitParamType);
  4970. return ICS;
  4971. }
  4972. // Check the ref-qualifier.
  4973. switch (Method->getRefQualifier()) {
  4974. case RQ_None:
  4975. // Do nothing; we don't care about lvalueness or rvalueness.
  4976. break;
  4977. case RQ_LValue:
  4978. if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
  4979. // non-const lvalue reference cannot bind to an rvalue
  4980. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4981. ImplicitParamType);
  4982. return ICS;
  4983. }
  4984. break;
  4985. case RQ_RValue:
  4986. if (!FromClassification.isRValue()) {
  4987. // rvalue reference cannot bind to an lvalue
  4988. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4989. ImplicitParamType);
  4990. return ICS;
  4991. }
  4992. break;
  4993. }
  4994. // Success. Mark this as a reference binding.
  4995. ICS.setStandard();
  4996. ICS.Standard.setAsIdentityConversion();
  4997. ICS.Standard.Second = SecondKind;
  4998. ICS.Standard.setFromType(FromType);
  4999. ICS.Standard.setAllToTypes(ImplicitParamType);
  5000. ICS.Standard.ReferenceBinding = true;
  5001. ICS.Standard.DirectBinding = true;
  5002. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  5003. ICS.Standard.BindsToFunctionLvalue = false;
  5004. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  5005. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  5006. = (Method->getRefQualifier() == RQ_None);
  5007. return ICS;
  5008. }
  5009. /// PerformObjectArgumentInitialization - Perform initialization of
  5010. /// the implicit object parameter for the given Method with the given
  5011. /// expression.
  5012. ExprResult
  5013. Sema::PerformObjectArgumentInitialization(Expr *From,
  5014. NestedNameSpecifier *Qualifier,
  5015. NamedDecl *FoundDecl,
  5016. CXXMethodDecl *Method) {
  5017. QualType FromRecordType, DestType;
  5018. QualType ImplicitParamRecordType =
  5019. Method->getThisType()->castAs<PointerType>()->getPointeeType();
  5020. Expr::Classification FromClassification;
  5021. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  5022. FromRecordType = PT->getPointeeType();
  5023. DestType = Method->getThisType();
  5024. FromClassification = Expr::Classification::makeSimpleLValue();
  5025. } else {
  5026. FromRecordType = From->getType();
  5027. DestType = ImplicitParamRecordType;
  5028. FromClassification = From->Classify(Context);
  5029. // When performing member access on a prvalue, materialize a temporary.
  5030. if (From->isPRValue()) {
  5031. From = CreateMaterializeTemporaryExpr(FromRecordType, From,
  5032. Method->getRefQualifier() !=
  5033. RefQualifierKind::RQ_RValue);
  5034. }
  5035. }
  5036. // Note that we always use the true parent context when performing
  5037. // the actual argument initialization.
  5038. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  5039. *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
  5040. Method->getParent());
  5041. if (ICS.isBad()) {
  5042. switch (ICS.Bad.Kind) {
  5043. case BadConversionSequence::bad_qualifiers: {
  5044. Qualifiers FromQs = FromRecordType.getQualifiers();
  5045. Qualifiers ToQs = DestType.getQualifiers();
  5046. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  5047. if (CVR) {
  5048. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
  5049. << Method->getDeclName() << FromRecordType << (CVR - 1)
  5050. << From->getSourceRange();
  5051. Diag(Method->getLocation(), diag::note_previous_decl)
  5052. << Method->getDeclName();
  5053. return ExprError();
  5054. }
  5055. break;
  5056. }
  5057. case BadConversionSequence::lvalue_ref_to_rvalue:
  5058. case BadConversionSequence::rvalue_ref_to_lvalue: {
  5059. bool IsRValueQualified =
  5060. Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
  5061. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
  5062. << Method->getDeclName() << FromClassification.isRValue()
  5063. << IsRValueQualified;
  5064. Diag(Method->getLocation(), diag::note_previous_decl)
  5065. << Method->getDeclName();
  5066. return ExprError();
  5067. }
  5068. case BadConversionSequence::no_conversion:
  5069. case BadConversionSequence::unrelated_class:
  5070. break;
  5071. case BadConversionSequence::too_few_initializers:
  5072. case BadConversionSequence::too_many_initializers:
  5073. llvm_unreachable("Lists are not objects");
  5074. }
  5075. return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
  5076. << ImplicitParamRecordType << FromRecordType
  5077. << From->getSourceRange();
  5078. }
  5079. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  5080. ExprResult FromRes =
  5081. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  5082. if (FromRes.isInvalid())
  5083. return ExprError();
  5084. From = FromRes.get();
  5085. }
  5086. if (!Context.hasSameType(From->getType(), DestType)) {
  5087. CastKind CK;
  5088. QualType PteeTy = DestType->getPointeeType();
  5089. LangAS DestAS =
  5090. PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
  5091. if (FromRecordType.getAddressSpace() != DestAS)
  5092. CK = CK_AddressSpaceConversion;
  5093. else
  5094. CK = CK_NoOp;
  5095. From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
  5096. }
  5097. return From;
  5098. }
  5099. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  5100. /// expression From to bool (C++0x [conv]p3).
  5101. static ImplicitConversionSequence
  5102. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  5103. // C++ [dcl.init]/17.8:
  5104. // - Otherwise, if the initialization is direct-initialization, the source
  5105. // type is std::nullptr_t, and the destination type is bool, the initial
  5106. // value of the object being initialized is false.
  5107. if (From->getType()->isNullPtrType())
  5108. return ImplicitConversionSequence::getNullptrToBool(From->getType(),
  5109. S.Context.BoolTy,
  5110. From->isGLValue());
  5111. // All other direct-initialization of bool is equivalent to an implicit
  5112. // conversion to bool in which explicit conversions are permitted.
  5113. return TryImplicitConversion(S, From, S.Context.BoolTy,
  5114. /*SuppressUserConversions=*/false,
  5115. AllowedExplicit::Conversions,
  5116. /*InOverloadResolution=*/false,
  5117. /*CStyle=*/false,
  5118. /*AllowObjCWritebackConversion=*/false,
  5119. /*AllowObjCConversionOnExplicit=*/false);
  5120. }
  5121. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  5122. /// of the expression From to bool (C++0x [conv]p3).
  5123. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  5124. if (checkPlaceholderForOverload(*this, From))
  5125. return ExprError();
  5126. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  5127. if (!ICS.isBad())
  5128. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  5129. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  5130. return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
  5131. << From->getType() << From->getSourceRange();
  5132. return ExprError();
  5133. }
  5134. /// Check that the specified conversion is permitted in a converted constant
  5135. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  5136. /// is acceptable.
  5137. static bool CheckConvertedConstantConversions(Sema &S,
  5138. StandardConversionSequence &SCS) {
  5139. // Since we know that the target type is an integral or unscoped enumeration
  5140. // type, most conversion kinds are impossible. All possible First and Third
  5141. // conversions are fine.
  5142. switch (SCS.Second) {
  5143. case ICK_Identity:
  5144. case ICK_Integral_Promotion:
  5145. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  5146. case ICK_Zero_Queue_Conversion:
  5147. return true;
  5148. case ICK_Boolean_Conversion:
  5149. // Conversion from an integral or unscoped enumeration type to bool is
  5150. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  5151. // conversion, so we allow it in a converted constant expression.
  5152. //
  5153. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  5154. // a lot of popular code. We should at least add a warning for this
  5155. // (non-conforming) extension.
  5156. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  5157. SCS.getToType(2)->isBooleanType();
  5158. case ICK_Pointer_Conversion:
  5159. case ICK_Pointer_Member:
  5160. // C++1z: null pointer conversions and null member pointer conversions are
  5161. // only permitted if the source type is std::nullptr_t.
  5162. return SCS.getFromType()->isNullPtrType();
  5163. case ICK_Floating_Promotion:
  5164. case ICK_Complex_Promotion:
  5165. case ICK_Floating_Conversion:
  5166. case ICK_Complex_Conversion:
  5167. case ICK_Floating_Integral:
  5168. case ICK_Compatible_Conversion:
  5169. case ICK_Derived_To_Base:
  5170. case ICK_Vector_Conversion:
  5171. case ICK_SVE_Vector_Conversion:
  5172. case ICK_Vector_Splat:
  5173. case ICK_Complex_Real:
  5174. case ICK_Block_Pointer_Conversion:
  5175. case ICK_TransparentUnionConversion:
  5176. case ICK_Writeback_Conversion:
  5177. case ICK_Zero_Event_Conversion:
  5178. case ICK_C_Only_Conversion:
  5179. case ICK_Incompatible_Pointer_Conversion:
  5180. return false;
  5181. case ICK_Lvalue_To_Rvalue:
  5182. case ICK_Array_To_Pointer:
  5183. case ICK_Function_To_Pointer:
  5184. llvm_unreachable("found a first conversion kind in Second");
  5185. case ICK_Function_Conversion:
  5186. case ICK_Qualification:
  5187. llvm_unreachable("found a third conversion kind in Second");
  5188. case ICK_Num_Conversion_Kinds:
  5189. break;
  5190. }
  5191. llvm_unreachable("unknown conversion kind");
  5192. }
  5193. /// CheckConvertedConstantExpression - Check that the expression From is a
  5194. /// converted constant expression of type T, perform the conversion and produce
  5195. /// the converted expression, per C++11 [expr.const]p3.
  5196. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  5197. QualType T, APValue &Value,
  5198. Sema::CCEKind CCE,
  5199. bool RequireInt,
  5200. NamedDecl *Dest) {
  5201. assert(S.getLangOpts().CPlusPlus11 &&
  5202. "converted constant expression outside C++11");
  5203. if (checkPlaceholderForOverload(S, From))
  5204. return ExprError();
  5205. // C++1z [expr.const]p3:
  5206. // A converted constant expression of type T is an expression,
  5207. // implicitly converted to type T, where the converted
  5208. // expression is a constant expression and the implicit conversion
  5209. // sequence contains only [... list of conversions ...].
  5210. ImplicitConversionSequence ICS =
  5211. (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
  5212. ? TryContextuallyConvertToBool(S, From)
  5213. : TryCopyInitialization(S, From, T,
  5214. /*SuppressUserConversions=*/false,
  5215. /*InOverloadResolution=*/false,
  5216. /*AllowObjCWritebackConversion=*/false,
  5217. /*AllowExplicit=*/false);
  5218. StandardConversionSequence *SCS = nullptr;
  5219. switch (ICS.getKind()) {
  5220. case ImplicitConversionSequence::StandardConversion:
  5221. SCS = &ICS.Standard;
  5222. break;
  5223. case ImplicitConversionSequence::UserDefinedConversion:
  5224. if (T->isRecordType())
  5225. SCS = &ICS.UserDefined.Before;
  5226. else
  5227. SCS = &ICS.UserDefined.After;
  5228. break;
  5229. case ImplicitConversionSequence::AmbiguousConversion:
  5230. case ImplicitConversionSequence::BadConversion:
  5231. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  5232. return S.Diag(From->getBeginLoc(),
  5233. diag::err_typecheck_converted_constant_expression)
  5234. << From->getType() << From->getSourceRange() << T;
  5235. return ExprError();
  5236. case ImplicitConversionSequence::EllipsisConversion:
  5237. case ImplicitConversionSequence::StaticObjectArgumentConversion:
  5238. llvm_unreachable("bad conversion in converted constant expression");
  5239. }
  5240. // Check that we would only use permitted conversions.
  5241. if (!CheckConvertedConstantConversions(S, *SCS)) {
  5242. return S.Diag(From->getBeginLoc(),
  5243. diag::err_typecheck_converted_constant_expression_disallowed)
  5244. << From->getType() << From->getSourceRange() << T;
  5245. }
  5246. // [...] and where the reference binding (if any) binds directly.
  5247. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  5248. return S.Diag(From->getBeginLoc(),
  5249. diag::err_typecheck_converted_constant_expression_indirect)
  5250. << From->getType() << From->getSourceRange() << T;
  5251. }
  5252. // Usually we can simply apply the ImplicitConversionSequence we formed
  5253. // earlier, but that's not guaranteed to work when initializing an object of
  5254. // class type.
  5255. ExprResult Result;
  5256. if (T->isRecordType()) {
  5257. assert(CCE == Sema::CCEK_TemplateArg &&
  5258. "unexpected class type converted constant expr");
  5259. Result = S.PerformCopyInitialization(
  5260. InitializedEntity::InitializeTemplateParameter(
  5261. T, cast<NonTypeTemplateParmDecl>(Dest)),
  5262. SourceLocation(), From);
  5263. } else {
  5264. Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  5265. }
  5266. if (Result.isInvalid())
  5267. return Result;
  5268. // C++2a [intro.execution]p5:
  5269. // A full-expression is [...] a constant-expression [...]
  5270. Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
  5271. /*DiscardedValue=*/false, /*IsConstexpr=*/true,
  5272. CCE == Sema::CCEKind::CCEK_TemplateArg);
  5273. if (Result.isInvalid())
  5274. return Result;
  5275. // Check for a narrowing implicit conversion.
  5276. bool ReturnPreNarrowingValue = false;
  5277. APValue PreNarrowingValue;
  5278. QualType PreNarrowingType;
  5279. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  5280. PreNarrowingType)) {
  5281. case NK_Dependent_Narrowing:
  5282. // Implicit conversion to a narrower type, but the expression is
  5283. // value-dependent so we can't tell whether it's actually narrowing.
  5284. case NK_Variable_Narrowing:
  5285. // Implicit conversion to a narrower type, and the value is not a constant
  5286. // expression. We'll diagnose this in a moment.
  5287. case NK_Not_Narrowing:
  5288. break;
  5289. case NK_Constant_Narrowing:
  5290. if (CCE == Sema::CCEK_ArrayBound &&
  5291. PreNarrowingType->isIntegralOrEnumerationType() &&
  5292. PreNarrowingValue.isInt()) {
  5293. // Don't diagnose array bound narrowing here; we produce more precise
  5294. // errors by allowing the un-narrowed value through.
  5295. ReturnPreNarrowingValue = true;
  5296. break;
  5297. }
  5298. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  5299. << CCE << /*Constant*/ 1
  5300. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  5301. break;
  5302. case NK_Type_Narrowing:
  5303. // FIXME: It would be better to diagnose that the expression is not a
  5304. // constant expression.
  5305. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  5306. << CCE << /*Constant*/ 0 << From->getType() << T;
  5307. break;
  5308. }
  5309. if (Result.get()->isValueDependent()) {
  5310. Value = APValue();
  5311. return Result;
  5312. }
  5313. // Check the expression is a constant expression.
  5314. SmallVector<PartialDiagnosticAt, 8> Notes;
  5315. Expr::EvalResult Eval;
  5316. Eval.Diag = &Notes;
  5317. ConstantExprKind Kind;
  5318. if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
  5319. Kind = ConstantExprKind::ClassTemplateArgument;
  5320. else if (CCE == Sema::CCEK_TemplateArg)
  5321. Kind = ConstantExprKind::NonClassTemplateArgument;
  5322. else
  5323. Kind = ConstantExprKind::Normal;
  5324. if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
  5325. (RequireInt && !Eval.Val.isInt())) {
  5326. // The expression can't be folded, so we can't keep it at this position in
  5327. // the AST.
  5328. Result = ExprError();
  5329. } else {
  5330. Value = Eval.Val;
  5331. if (Notes.empty()) {
  5332. // It's a constant expression.
  5333. Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
  5334. if (ReturnPreNarrowingValue)
  5335. Value = std::move(PreNarrowingValue);
  5336. return E;
  5337. }
  5338. }
  5339. // It's not a constant expression. Produce an appropriate diagnostic.
  5340. if (Notes.size() == 1 &&
  5341. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
  5342. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  5343. } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
  5344. diag::note_constexpr_invalid_template_arg) {
  5345. Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
  5346. for (unsigned I = 0; I < Notes.size(); ++I)
  5347. S.Diag(Notes[I].first, Notes[I].second);
  5348. } else {
  5349. S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
  5350. << CCE << From->getSourceRange();
  5351. for (unsigned I = 0; I < Notes.size(); ++I)
  5352. S.Diag(Notes[I].first, Notes[I].second);
  5353. }
  5354. return ExprError();
  5355. }
  5356. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  5357. APValue &Value, CCEKind CCE,
  5358. NamedDecl *Dest) {
  5359. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
  5360. Dest);
  5361. }
  5362. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  5363. llvm::APSInt &Value,
  5364. CCEKind CCE) {
  5365. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  5366. APValue V;
  5367. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
  5368. /*Dest=*/nullptr);
  5369. if (!R.isInvalid() && !R.get()->isValueDependent())
  5370. Value = V.getInt();
  5371. return R;
  5372. }
  5373. /// dropPointerConversions - If the given standard conversion sequence
  5374. /// involves any pointer conversions, remove them. This may change
  5375. /// the result type of the conversion sequence.
  5376. static void dropPointerConversion(StandardConversionSequence &SCS) {
  5377. if (SCS.Second == ICK_Pointer_Conversion) {
  5378. SCS.Second = ICK_Identity;
  5379. SCS.Third = ICK_Identity;
  5380. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  5381. }
  5382. }
  5383. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  5384. /// convert the expression From to an Objective-C pointer type.
  5385. static ImplicitConversionSequence
  5386. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  5387. // Do an implicit conversion to 'id'.
  5388. QualType Ty = S.Context.getObjCIdType();
  5389. ImplicitConversionSequence ICS
  5390. = TryImplicitConversion(S, From, Ty,
  5391. // FIXME: Are these flags correct?
  5392. /*SuppressUserConversions=*/false,
  5393. AllowedExplicit::Conversions,
  5394. /*InOverloadResolution=*/false,
  5395. /*CStyle=*/false,
  5396. /*AllowObjCWritebackConversion=*/false,
  5397. /*AllowObjCConversionOnExplicit=*/true);
  5398. // Strip off any final conversions to 'id'.
  5399. switch (ICS.getKind()) {
  5400. case ImplicitConversionSequence::BadConversion:
  5401. case ImplicitConversionSequence::AmbiguousConversion:
  5402. case ImplicitConversionSequence::EllipsisConversion:
  5403. case ImplicitConversionSequence::StaticObjectArgumentConversion:
  5404. break;
  5405. case ImplicitConversionSequence::UserDefinedConversion:
  5406. dropPointerConversion(ICS.UserDefined.After);
  5407. break;
  5408. case ImplicitConversionSequence::StandardConversion:
  5409. dropPointerConversion(ICS.Standard);
  5410. break;
  5411. }
  5412. return ICS;
  5413. }
  5414. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  5415. /// conversion of the expression From to an Objective-C pointer type.
  5416. /// Returns a valid but null ExprResult if no conversion sequence exists.
  5417. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  5418. if (checkPlaceholderForOverload(*this, From))
  5419. return ExprError();
  5420. QualType Ty = Context.getObjCIdType();
  5421. ImplicitConversionSequence ICS =
  5422. TryContextuallyConvertToObjCPointer(*this, From);
  5423. if (!ICS.isBad())
  5424. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  5425. return ExprResult();
  5426. }
  5427. /// Determine whether the provided type is an integral type, or an enumeration
  5428. /// type of a permitted flavor.
  5429. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  5430. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  5431. : T->isIntegralOrUnscopedEnumerationType();
  5432. }
  5433. static ExprResult
  5434. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  5435. Sema::ContextualImplicitConverter &Converter,
  5436. QualType T, UnresolvedSetImpl &ViableConversions) {
  5437. if (Converter.Suppress)
  5438. return ExprError();
  5439. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  5440. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5441. CXXConversionDecl *Conv =
  5442. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  5443. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  5444. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  5445. }
  5446. return From;
  5447. }
  5448. static bool
  5449. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5450. Sema::ContextualImplicitConverter &Converter,
  5451. QualType T, bool HadMultipleCandidates,
  5452. UnresolvedSetImpl &ExplicitConversions) {
  5453. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  5454. DeclAccessPair Found = ExplicitConversions[0];
  5455. CXXConversionDecl *Conversion =
  5456. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5457. // The user probably meant to invoke the given explicit
  5458. // conversion; use it.
  5459. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  5460. std::string TypeStr;
  5461. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  5462. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  5463. << FixItHint::CreateInsertion(From->getBeginLoc(),
  5464. "static_cast<" + TypeStr + ">(")
  5465. << FixItHint::CreateInsertion(
  5466. SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
  5467. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  5468. // If we aren't in a SFINAE context, build a call to the
  5469. // explicit conversion function.
  5470. if (SemaRef.isSFINAEContext())
  5471. return true;
  5472. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5473. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5474. HadMultipleCandidates);
  5475. if (Result.isInvalid())
  5476. return true;
  5477. // Record usage of conversion in an implicit cast.
  5478. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5479. CK_UserDefinedConversion, Result.get(),
  5480. nullptr, Result.get()->getValueKind(),
  5481. SemaRef.CurFPFeatureOverrides());
  5482. }
  5483. return false;
  5484. }
  5485. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5486. Sema::ContextualImplicitConverter &Converter,
  5487. QualType T, bool HadMultipleCandidates,
  5488. DeclAccessPair &Found) {
  5489. CXXConversionDecl *Conversion =
  5490. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5491. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5492. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  5493. if (!Converter.SuppressConversion) {
  5494. if (SemaRef.isSFINAEContext())
  5495. return true;
  5496. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  5497. << From->getSourceRange();
  5498. }
  5499. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5500. HadMultipleCandidates);
  5501. if (Result.isInvalid())
  5502. return true;
  5503. // Record usage of conversion in an implicit cast.
  5504. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5505. CK_UserDefinedConversion, Result.get(),
  5506. nullptr, Result.get()->getValueKind(),
  5507. SemaRef.CurFPFeatureOverrides());
  5508. return false;
  5509. }
  5510. static ExprResult finishContextualImplicitConversion(
  5511. Sema &SemaRef, SourceLocation Loc, Expr *From,
  5512. Sema::ContextualImplicitConverter &Converter) {
  5513. if (!Converter.match(From->getType()) && !Converter.Suppress)
  5514. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  5515. << From->getSourceRange();
  5516. return SemaRef.DefaultLvalueConversion(From);
  5517. }
  5518. static void
  5519. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  5520. UnresolvedSetImpl &ViableConversions,
  5521. OverloadCandidateSet &CandidateSet) {
  5522. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5523. DeclAccessPair FoundDecl = ViableConversions[I];
  5524. NamedDecl *D = FoundDecl.getDecl();
  5525. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  5526. if (isa<UsingShadowDecl>(D))
  5527. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  5528. CXXConversionDecl *Conv;
  5529. FunctionTemplateDecl *ConvTemplate;
  5530. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  5531. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5532. else
  5533. Conv = cast<CXXConversionDecl>(D);
  5534. if (ConvTemplate)
  5535. SemaRef.AddTemplateConversionCandidate(
  5536. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  5537. /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
  5538. else
  5539. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  5540. ToType, CandidateSet,
  5541. /*AllowObjCConversionOnExplicit=*/false,
  5542. /*AllowExplicit*/ true);
  5543. }
  5544. }
  5545. /// Attempt to convert the given expression to a type which is accepted
  5546. /// by the given converter.
  5547. ///
  5548. /// This routine will attempt to convert an expression of class type to a
  5549. /// type accepted by the specified converter. In C++11 and before, the class
  5550. /// must have a single non-explicit conversion function converting to a matching
  5551. /// type. In C++1y, there can be multiple such conversion functions, but only
  5552. /// one target type.
  5553. ///
  5554. /// \param Loc The source location of the construct that requires the
  5555. /// conversion.
  5556. ///
  5557. /// \param From The expression we're converting from.
  5558. ///
  5559. /// \param Converter Used to control and diagnose the conversion process.
  5560. ///
  5561. /// \returns The expression, converted to an integral or enumeration type if
  5562. /// successful.
  5563. ExprResult Sema::PerformContextualImplicitConversion(
  5564. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  5565. // We can't perform any more checking for type-dependent expressions.
  5566. if (From->isTypeDependent())
  5567. return From;
  5568. // Process placeholders immediately.
  5569. if (From->hasPlaceholderType()) {
  5570. ExprResult result = CheckPlaceholderExpr(From);
  5571. if (result.isInvalid())
  5572. return result;
  5573. From = result.get();
  5574. }
  5575. // If the expression already has a matching type, we're golden.
  5576. QualType T = From->getType();
  5577. if (Converter.match(T))
  5578. return DefaultLvalueConversion(From);
  5579. // FIXME: Check for missing '()' if T is a function type?
  5580. // We can only perform contextual implicit conversions on objects of class
  5581. // type.
  5582. const RecordType *RecordTy = T->getAs<RecordType>();
  5583. if (!RecordTy || !getLangOpts().CPlusPlus) {
  5584. if (!Converter.Suppress)
  5585. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  5586. return From;
  5587. }
  5588. // We must have a complete class type.
  5589. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  5590. ContextualImplicitConverter &Converter;
  5591. Expr *From;
  5592. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  5593. : Converter(Converter), From(From) {}
  5594. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  5595. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  5596. }
  5597. } IncompleteDiagnoser(Converter, From);
  5598. if (Converter.Suppress ? !isCompleteType(Loc, T)
  5599. : RequireCompleteType(Loc, T, IncompleteDiagnoser))
  5600. return From;
  5601. // Look for a conversion to an integral or enumeration type.
  5602. UnresolvedSet<4>
  5603. ViableConversions; // These are *potentially* viable in C++1y.
  5604. UnresolvedSet<4> ExplicitConversions;
  5605. const auto &Conversions =
  5606. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  5607. bool HadMultipleCandidates =
  5608. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  5609. // To check that there is only one target type, in C++1y:
  5610. QualType ToType;
  5611. bool HasUniqueTargetType = true;
  5612. // Collect explicit or viable (potentially in C++1y) conversions.
  5613. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  5614. NamedDecl *D = (*I)->getUnderlyingDecl();
  5615. CXXConversionDecl *Conversion;
  5616. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  5617. if (ConvTemplate) {
  5618. if (getLangOpts().CPlusPlus14)
  5619. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5620. else
  5621. continue; // C++11 does not consider conversion operator templates(?).
  5622. } else
  5623. Conversion = cast<CXXConversionDecl>(D);
  5624. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  5625. "Conversion operator templates are considered potentially "
  5626. "viable in C++1y");
  5627. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  5628. if (Converter.match(CurToType) || ConvTemplate) {
  5629. if (Conversion->isExplicit()) {
  5630. // FIXME: For C++1y, do we need this restriction?
  5631. // cf. diagnoseNoViableConversion()
  5632. if (!ConvTemplate)
  5633. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  5634. } else {
  5635. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  5636. if (ToType.isNull())
  5637. ToType = CurToType.getUnqualifiedType();
  5638. else if (HasUniqueTargetType &&
  5639. (CurToType.getUnqualifiedType() != ToType))
  5640. HasUniqueTargetType = false;
  5641. }
  5642. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5643. }
  5644. }
  5645. }
  5646. if (getLangOpts().CPlusPlus14) {
  5647. // C++1y [conv]p6:
  5648. // ... An expression e of class type E appearing in such a context
  5649. // is said to be contextually implicitly converted to a specified
  5650. // type T and is well-formed if and only if e can be implicitly
  5651. // converted to a type T that is determined as follows: E is searched
  5652. // for conversion functions whose return type is cv T or reference to
  5653. // cv T such that T is allowed by the context. There shall be
  5654. // exactly one such T.
  5655. // If no unique T is found:
  5656. if (ToType.isNull()) {
  5657. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5658. HadMultipleCandidates,
  5659. ExplicitConversions))
  5660. return ExprError();
  5661. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5662. }
  5663. // If more than one unique Ts are found:
  5664. if (!HasUniqueTargetType)
  5665. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5666. ViableConversions);
  5667. // If one unique T is found:
  5668. // First, build a candidate set from the previously recorded
  5669. // potentially viable conversions.
  5670. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5671. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5672. CandidateSet);
  5673. // Then, perform overload resolution over the candidate set.
  5674. OverloadCandidateSet::iterator Best;
  5675. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5676. case OR_Success: {
  5677. // Apply this conversion.
  5678. DeclAccessPair Found =
  5679. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5680. if (recordConversion(*this, Loc, From, Converter, T,
  5681. HadMultipleCandidates, Found))
  5682. return ExprError();
  5683. break;
  5684. }
  5685. case OR_Ambiguous:
  5686. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5687. ViableConversions);
  5688. case OR_No_Viable_Function:
  5689. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5690. HadMultipleCandidates,
  5691. ExplicitConversions))
  5692. return ExprError();
  5693. [[fallthrough]];
  5694. case OR_Deleted:
  5695. // We'll complain below about a non-integral condition type.
  5696. break;
  5697. }
  5698. } else {
  5699. switch (ViableConversions.size()) {
  5700. case 0: {
  5701. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5702. HadMultipleCandidates,
  5703. ExplicitConversions))
  5704. return ExprError();
  5705. // We'll complain below about a non-integral condition type.
  5706. break;
  5707. }
  5708. case 1: {
  5709. // Apply this conversion.
  5710. DeclAccessPair Found = ViableConversions[0];
  5711. if (recordConversion(*this, Loc, From, Converter, T,
  5712. HadMultipleCandidates, Found))
  5713. return ExprError();
  5714. break;
  5715. }
  5716. default:
  5717. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5718. ViableConversions);
  5719. }
  5720. }
  5721. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5722. }
  5723. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5724. /// an acceptable non-member overloaded operator for a call whose
  5725. /// arguments have types T1 (and, if non-empty, T2). This routine
  5726. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5727. /// enumeration types.
  5728. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5729. FunctionDecl *Fn,
  5730. ArrayRef<Expr *> Args) {
  5731. QualType T1 = Args[0]->getType();
  5732. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5733. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5734. return true;
  5735. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5736. return true;
  5737. const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
  5738. if (Proto->getNumParams() < 1)
  5739. return false;
  5740. if (T1->isEnumeralType()) {
  5741. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5742. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5743. return true;
  5744. }
  5745. if (Proto->getNumParams() < 2)
  5746. return false;
  5747. if (!T2.isNull() && T2->isEnumeralType()) {
  5748. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5749. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5750. return true;
  5751. }
  5752. return false;
  5753. }
  5754. /// AddOverloadCandidate - Adds the given function to the set of
  5755. /// candidate functions, using the given function call arguments. If
  5756. /// @p SuppressUserConversions, then don't allow user-defined
  5757. /// conversions via constructors or conversion operators.
  5758. ///
  5759. /// \param PartialOverloading true if we are performing "partial" overloading
  5760. /// based on an incomplete set of function arguments. This feature is used by
  5761. /// code completion.
  5762. void Sema::AddOverloadCandidate(
  5763. FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
  5764. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  5765. bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
  5766. ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
  5767. OverloadCandidateParamOrder PO) {
  5768. const FunctionProtoType *Proto
  5769. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5770. assert(Proto && "Functions without a prototype cannot be overloaded");
  5771. assert(!Function->getDescribedFunctionTemplate() &&
  5772. "Use AddTemplateOverloadCandidate for function templates");
  5773. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5774. if (!isa<CXXConstructorDecl>(Method)) {
  5775. // If we get here, it's because we're calling a member function
  5776. // that is named without a member access expression (e.g.,
  5777. // "this->f") that was either written explicitly or created
  5778. // implicitly. This can happen with a qualified call to a member
  5779. // function, e.g., X::f(). We use an empty type for the implied
  5780. // object argument (C++ [over.call.func]p3), and the acting context
  5781. // is irrelevant.
  5782. AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
  5783. Expr::Classification::makeSimpleLValue(), Args,
  5784. CandidateSet, SuppressUserConversions,
  5785. PartialOverloading, EarlyConversions, PO);
  5786. return;
  5787. }
  5788. // We treat a constructor like a non-member function, since its object
  5789. // argument doesn't participate in overload resolution.
  5790. }
  5791. if (!CandidateSet.isNewCandidate(Function, PO))
  5792. return;
  5793. // C++11 [class.copy]p11: [DR1402]
  5794. // A defaulted move constructor that is defined as deleted is ignored by
  5795. // overload resolution.
  5796. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5797. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5798. Constructor->isMoveConstructor())
  5799. return;
  5800. // Overload resolution is always an unevaluated context.
  5801. EnterExpressionEvaluationContext Unevaluated(
  5802. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5803. // C++ [over.match.oper]p3:
  5804. // if no operand has a class type, only those non-member functions in the
  5805. // lookup set that have a first parameter of type T1 or "reference to
  5806. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5807. // is a right operand) a second parameter of type T2 or "reference to
  5808. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5809. // candidate functions.
  5810. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5811. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5812. return;
  5813. // Add this candidate
  5814. OverloadCandidate &Candidate =
  5815. CandidateSet.addCandidate(Args.size(), EarlyConversions);
  5816. Candidate.FoundDecl = FoundDecl;
  5817. Candidate.Function = Function;
  5818. Candidate.Viable = true;
  5819. Candidate.RewriteKind =
  5820. CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
  5821. Candidate.IsSurrogate = false;
  5822. Candidate.IsADLCandidate = IsADLCandidate;
  5823. Candidate.IgnoreObjectArgument = false;
  5824. Candidate.ExplicitCallArguments = Args.size();
  5825. // Explicit functions are not actually candidates at all if we're not
  5826. // allowing them in this context, but keep them around so we can point
  5827. // to them in diagnostics.
  5828. if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
  5829. Candidate.Viable = false;
  5830. Candidate.FailureKind = ovl_fail_explicit;
  5831. return;
  5832. }
  5833. // Functions with internal linkage are only viable in the same module unit.
  5834. if (auto *MF = Function->getOwningModule()) {
  5835. if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
  5836. !isModuleUnitOfCurrentTU(MF)) {
  5837. /// FIXME: Currently, the semantics of linkage in clang is slightly
  5838. /// different from the semantics in C++ spec. In C++ spec, only names
  5839. /// have linkage. So that all entities of the same should share one
  5840. /// linkage. But in clang, different entities of the same could have
  5841. /// different linkage.
  5842. NamedDecl *ND = Function;
  5843. if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
  5844. ND = SpecInfo->getTemplate();
  5845. if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
  5846. Candidate.Viable = false;
  5847. Candidate.FailureKind = ovl_fail_module_mismatched;
  5848. return;
  5849. }
  5850. }
  5851. }
  5852. if (Function->isMultiVersion() &&
  5853. ((Function->hasAttr<TargetAttr>() &&
  5854. !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
  5855. (Function->hasAttr<TargetVersionAttr>() &&
  5856. !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
  5857. Candidate.Viable = false;
  5858. Candidate.FailureKind = ovl_non_default_multiversion_function;
  5859. return;
  5860. }
  5861. if (Constructor) {
  5862. // C++ [class.copy]p3:
  5863. // A member function template is never instantiated to perform the copy
  5864. // of a class object to an object of its class type.
  5865. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5866. if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
  5867. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5868. IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
  5869. ClassType))) {
  5870. Candidate.Viable = false;
  5871. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5872. return;
  5873. }
  5874. // C++ [over.match.funcs]p8: (proposed DR resolution)
  5875. // A constructor inherited from class type C that has a first parameter
  5876. // of type "reference to P" (including such a constructor instantiated
  5877. // from a template) is excluded from the set of candidate functions when
  5878. // constructing an object of type cv D if the argument list has exactly
  5879. // one argument and D is reference-related to P and P is reference-related
  5880. // to C.
  5881. auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
  5882. if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
  5883. Constructor->getParamDecl(0)->getType()->isReferenceType()) {
  5884. QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
  5885. QualType C = Context.getRecordType(Constructor->getParent());
  5886. QualType D = Context.getRecordType(Shadow->getParent());
  5887. SourceLocation Loc = Args.front()->getExprLoc();
  5888. if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
  5889. (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
  5890. Candidate.Viable = false;
  5891. Candidate.FailureKind = ovl_fail_inhctor_slice;
  5892. return;
  5893. }
  5894. }
  5895. // Check that the constructor is capable of constructing an object in the
  5896. // destination address space.
  5897. if (!Qualifiers::isAddressSpaceSupersetOf(
  5898. Constructor->getMethodQualifiers().getAddressSpace(),
  5899. CandidateSet.getDestAS())) {
  5900. Candidate.Viable = false;
  5901. Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
  5902. }
  5903. }
  5904. unsigned NumParams = Proto->getNumParams();
  5905. // (C++ 13.3.2p2): A candidate function having fewer than m
  5906. // parameters is viable only if it has an ellipsis in its parameter
  5907. // list (8.3.5).
  5908. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5909. !Proto->isVariadic() &&
  5910. shouldEnforceArgLimit(PartialOverloading, Function)) {
  5911. Candidate.Viable = false;
  5912. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5913. return;
  5914. }
  5915. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5916. // is viable only if the (m+1)st parameter has a default argument
  5917. // (8.3.6). For the purposes of overload resolution, the
  5918. // parameter list is truncated on the right, so that there are
  5919. // exactly m parameters.
  5920. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5921. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5922. // Not enough arguments.
  5923. Candidate.Viable = false;
  5924. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5925. return;
  5926. }
  5927. // (CUDA B.1): Check for invalid calls between targets.
  5928. if (getLangOpts().CUDA)
  5929. if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
  5930. // Skip the check for callers that are implicit members, because in this
  5931. // case we may not yet know what the member's target is; the target is
  5932. // inferred for the member automatically, based on the bases and fields of
  5933. // the class.
  5934. if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
  5935. Candidate.Viable = false;
  5936. Candidate.FailureKind = ovl_fail_bad_target;
  5937. return;
  5938. }
  5939. if (Function->getTrailingRequiresClause()) {
  5940. ConstraintSatisfaction Satisfaction;
  5941. if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
  5942. /*ForOverloadResolution*/ true) ||
  5943. !Satisfaction.IsSatisfied) {
  5944. Candidate.Viable = false;
  5945. Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
  5946. return;
  5947. }
  5948. }
  5949. // Determine the implicit conversion sequences for each of the
  5950. // arguments.
  5951. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5952. unsigned ConvIdx =
  5953. PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
  5954. if (Candidate.Conversions[ConvIdx].isInitialized()) {
  5955. // We already formed a conversion sequence for this parameter during
  5956. // template argument deduction.
  5957. } else if (ArgIdx < NumParams) {
  5958. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5959. // exist for each argument an implicit conversion sequence
  5960. // (13.3.3.1) that converts that argument to the corresponding
  5961. // parameter of F.
  5962. QualType ParamType = Proto->getParamType(ArgIdx);
  5963. Candidate.Conversions[ConvIdx] = TryCopyInitialization(
  5964. *this, Args[ArgIdx], ParamType, SuppressUserConversions,
  5965. /*InOverloadResolution=*/true,
  5966. /*AllowObjCWritebackConversion=*/
  5967. getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
  5968. if (Candidate.Conversions[ConvIdx].isBad()) {
  5969. Candidate.Viable = false;
  5970. Candidate.FailureKind = ovl_fail_bad_conversion;
  5971. return;
  5972. }
  5973. } else {
  5974. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5975. // argument for which there is no corresponding parameter is
  5976. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5977. Candidate.Conversions[ConvIdx].setEllipsis();
  5978. }
  5979. }
  5980. if (EnableIfAttr *FailedAttr =
  5981. CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
  5982. Candidate.Viable = false;
  5983. Candidate.FailureKind = ovl_fail_enable_if;
  5984. Candidate.DeductionFailure.Data = FailedAttr;
  5985. return;
  5986. }
  5987. }
  5988. ObjCMethodDecl *
  5989. Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
  5990. SmallVectorImpl<ObjCMethodDecl *> &Methods) {
  5991. if (Methods.size() <= 1)
  5992. return nullptr;
  5993. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5994. bool Match = true;
  5995. ObjCMethodDecl *Method = Methods[b];
  5996. unsigned NumNamedArgs = Sel.getNumArgs();
  5997. // Method might have more arguments than selector indicates. This is due
  5998. // to addition of c-style arguments in method.
  5999. if (Method->param_size() > NumNamedArgs)
  6000. NumNamedArgs = Method->param_size();
  6001. if (Args.size() < NumNamedArgs)
  6002. continue;
  6003. for (unsigned i = 0; i < NumNamedArgs; i++) {
  6004. // We can't do any type-checking on a type-dependent argument.
  6005. if (Args[i]->isTypeDependent()) {
  6006. Match = false;
  6007. break;
  6008. }
  6009. ParmVarDecl *param = Method->parameters()[i];
  6010. Expr *argExpr = Args[i];
  6011. assert(argExpr && "SelectBestMethod(): missing expression");
  6012. // Strip the unbridged-cast placeholder expression off unless it's
  6013. // a consumed argument.
  6014. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  6015. !param->hasAttr<CFConsumedAttr>())
  6016. argExpr = stripARCUnbridgedCast(argExpr);
  6017. // If the parameter is __unknown_anytype, move on to the next method.
  6018. if (param->getType() == Context.UnknownAnyTy) {
  6019. Match = false;
  6020. break;
  6021. }
  6022. ImplicitConversionSequence ConversionState
  6023. = TryCopyInitialization(*this, argExpr, param->getType(),
  6024. /*SuppressUserConversions*/false,
  6025. /*InOverloadResolution=*/true,
  6026. /*AllowObjCWritebackConversion=*/
  6027. getLangOpts().ObjCAutoRefCount,
  6028. /*AllowExplicit*/false);
  6029. // This function looks for a reasonably-exact match, so we consider
  6030. // incompatible pointer conversions to be a failure here.
  6031. if (ConversionState.isBad() ||
  6032. (ConversionState.isStandard() &&
  6033. ConversionState.Standard.Second ==
  6034. ICK_Incompatible_Pointer_Conversion)) {
  6035. Match = false;
  6036. break;
  6037. }
  6038. }
  6039. // Promote additional arguments to variadic methods.
  6040. if (Match && Method->isVariadic()) {
  6041. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  6042. if (Args[i]->isTypeDependent()) {
  6043. Match = false;
  6044. break;
  6045. }
  6046. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  6047. nullptr);
  6048. if (Arg.isInvalid()) {
  6049. Match = false;
  6050. break;
  6051. }
  6052. }
  6053. } else {
  6054. // Check for extra arguments to non-variadic methods.
  6055. if (Args.size() != NumNamedArgs)
  6056. Match = false;
  6057. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  6058. // Special case when selectors have no argument. In this case, select
  6059. // one with the most general result type of 'id'.
  6060. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  6061. QualType ReturnT = Methods[b]->getReturnType();
  6062. if (ReturnT->isObjCIdType())
  6063. return Methods[b];
  6064. }
  6065. }
  6066. }
  6067. if (Match)
  6068. return Method;
  6069. }
  6070. return nullptr;
  6071. }
  6072. static bool convertArgsForAvailabilityChecks(
  6073. Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
  6074. ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
  6075. Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
  6076. if (ThisArg) {
  6077. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  6078. assert(!isa<CXXConstructorDecl>(Method) &&
  6079. "Shouldn't have `this` for ctors!");
  6080. assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
  6081. ExprResult R = S.PerformObjectArgumentInitialization(
  6082. ThisArg, /*Qualifier=*/nullptr, Method, Method);
  6083. if (R.isInvalid())
  6084. return false;
  6085. ConvertedThis = R.get();
  6086. } else {
  6087. if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
  6088. (void)MD;
  6089. assert((MissingImplicitThis || MD->isStatic() ||
  6090. isa<CXXConstructorDecl>(MD)) &&
  6091. "Expected `this` for non-ctor instance methods");
  6092. }
  6093. ConvertedThis = nullptr;
  6094. }
  6095. // Ignore any variadic arguments. Converting them is pointless, since the
  6096. // user can't refer to them in the function condition.
  6097. unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
  6098. // Convert the arguments.
  6099. for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
  6100. ExprResult R;
  6101. R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  6102. S.Context, Function->getParamDecl(I)),
  6103. SourceLocation(), Args[I]);
  6104. if (R.isInvalid())
  6105. return false;
  6106. ConvertedArgs.push_back(R.get());
  6107. }
  6108. if (Trap.hasErrorOccurred())
  6109. return false;
  6110. // Push default arguments if needed.
  6111. if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
  6112. for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
  6113. ParmVarDecl *P = Function->getParamDecl(i);
  6114. if (!P->hasDefaultArg())
  6115. return false;
  6116. ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
  6117. if (R.isInvalid())
  6118. return false;
  6119. ConvertedArgs.push_back(R.get());
  6120. }
  6121. if (Trap.hasErrorOccurred())
  6122. return false;
  6123. }
  6124. return true;
  6125. }
  6126. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
  6127. SourceLocation CallLoc,
  6128. ArrayRef<Expr *> Args,
  6129. bool MissingImplicitThis) {
  6130. auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
  6131. if (EnableIfAttrs.begin() == EnableIfAttrs.end())
  6132. return nullptr;
  6133. SFINAETrap Trap(*this);
  6134. SmallVector<Expr *, 16> ConvertedArgs;
  6135. // FIXME: We should look into making enable_if late-parsed.
  6136. Expr *DiscardedThis;
  6137. if (!convertArgsForAvailabilityChecks(
  6138. *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
  6139. /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
  6140. return *EnableIfAttrs.begin();
  6141. for (auto *EIA : EnableIfAttrs) {
  6142. APValue Result;
  6143. // FIXME: This doesn't consider value-dependent cases, because doing so is
  6144. // very difficult. Ideally, we should handle them more gracefully.
  6145. if (EIA->getCond()->isValueDependent() ||
  6146. !EIA->getCond()->EvaluateWithSubstitution(
  6147. Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
  6148. return EIA;
  6149. if (!Result.isInt() || !Result.getInt().getBoolValue())
  6150. return EIA;
  6151. }
  6152. return nullptr;
  6153. }
  6154. template <typename CheckFn>
  6155. static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
  6156. bool ArgDependent, SourceLocation Loc,
  6157. CheckFn &&IsSuccessful) {
  6158. SmallVector<const DiagnoseIfAttr *, 8> Attrs;
  6159. for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
  6160. if (ArgDependent == DIA->getArgDependent())
  6161. Attrs.push_back(DIA);
  6162. }
  6163. // Common case: No diagnose_if attributes, so we can quit early.
  6164. if (Attrs.empty())
  6165. return false;
  6166. auto WarningBegin = std::stable_partition(
  6167. Attrs.begin(), Attrs.end(),
  6168. [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
  6169. // Note that diagnose_if attributes are late-parsed, so they appear in the
  6170. // correct order (unlike enable_if attributes).
  6171. auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
  6172. IsSuccessful);
  6173. if (ErrAttr != WarningBegin) {
  6174. const DiagnoseIfAttr *DIA = *ErrAttr;
  6175. S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
  6176. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  6177. << DIA->getParent() << DIA->getCond()->getSourceRange();
  6178. return true;
  6179. }
  6180. for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
  6181. if (IsSuccessful(DIA)) {
  6182. S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
  6183. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  6184. << DIA->getParent() << DIA->getCond()->getSourceRange();
  6185. }
  6186. return false;
  6187. }
  6188. bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
  6189. const Expr *ThisArg,
  6190. ArrayRef<const Expr *> Args,
  6191. SourceLocation Loc) {
  6192. return diagnoseDiagnoseIfAttrsWith(
  6193. *this, Function, /*ArgDependent=*/true, Loc,
  6194. [&](const DiagnoseIfAttr *DIA) {
  6195. APValue Result;
  6196. // It's sane to use the same Args for any redecl of this function, since
  6197. // EvaluateWithSubstitution only cares about the position of each
  6198. // argument in the arg list, not the ParmVarDecl* it maps to.
  6199. if (!DIA->getCond()->EvaluateWithSubstitution(
  6200. Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
  6201. return false;
  6202. return Result.isInt() && Result.getInt().getBoolValue();
  6203. });
  6204. }
  6205. bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
  6206. SourceLocation Loc) {
  6207. return diagnoseDiagnoseIfAttrsWith(
  6208. *this, ND, /*ArgDependent=*/false, Loc,
  6209. [&](const DiagnoseIfAttr *DIA) {
  6210. bool Result;
  6211. return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
  6212. Result;
  6213. });
  6214. }
  6215. /// Add all of the function declarations in the given function set to
  6216. /// the overload candidate set.
  6217. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  6218. ArrayRef<Expr *> Args,
  6219. OverloadCandidateSet &CandidateSet,
  6220. TemplateArgumentListInfo *ExplicitTemplateArgs,
  6221. bool SuppressUserConversions,
  6222. bool PartialOverloading,
  6223. bool FirstArgumentIsBase) {
  6224. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  6225. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  6226. ArrayRef<Expr *> FunctionArgs = Args;
  6227. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  6228. FunctionDecl *FD =
  6229. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  6230. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
  6231. QualType ObjectType;
  6232. Expr::Classification ObjectClassification;
  6233. if (Args.size() > 0) {
  6234. if (Expr *E = Args[0]) {
  6235. // Use the explicit base to restrict the lookup:
  6236. ObjectType = E->getType();
  6237. // Pointers in the object arguments are implicitly dereferenced, so we
  6238. // always classify them as l-values.
  6239. if (!ObjectType.isNull() && ObjectType->isPointerType())
  6240. ObjectClassification = Expr::Classification::makeSimpleLValue();
  6241. else
  6242. ObjectClassification = E->Classify(Context);
  6243. } // .. else there is an implicit base.
  6244. FunctionArgs = Args.slice(1);
  6245. }
  6246. if (FunTmpl) {
  6247. AddMethodTemplateCandidate(
  6248. FunTmpl, F.getPair(),
  6249. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  6250. ExplicitTemplateArgs, ObjectType, ObjectClassification,
  6251. FunctionArgs, CandidateSet, SuppressUserConversions,
  6252. PartialOverloading);
  6253. } else {
  6254. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  6255. cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
  6256. ObjectClassification, FunctionArgs, CandidateSet,
  6257. SuppressUserConversions, PartialOverloading);
  6258. }
  6259. } else {
  6260. // This branch handles both standalone functions and static methods.
  6261. // Slice the first argument (which is the base) when we access
  6262. // static method as non-static.
  6263. if (Args.size() > 0 &&
  6264. (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
  6265. !isa<CXXConstructorDecl>(FD)))) {
  6266. assert(cast<CXXMethodDecl>(FD)->isStatic());
  6267. FunctionArgs = Args.slice(1);
  6268. }
  6269. if (FunTmpl) {
  6270. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  6271. ExplicitTemplateArgs, FunctionArgs,
  6272. CandidateSet, SuppressUserConversions,
  6273. PartialOverloading);
  6274. } else {
  6275. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
  6276. SuppressUserConversions, PartialOverloading);
  6277. }
  6278. }
  6279. }
  6280. }
  6281. /// AddMethodCandidate - Adds a named decl (which is some kind of
  6282. /// method) as a method candidate to the given overload set.
  6283. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
  6284. Expr::Classification ObjectClassification,
  6285. ArrayRef<Expr *> Args,
  6286. OverloadCandidateSet &CandidateSet,
  6287. bool SuppressUserConversions,
  6288. OverloadCandidateParamOrder PO) {
  6289. NamedDecl *Decl = FoundDecl.getDecl();
  6290. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  6291. if (isa<UsingShadowDecl>(Decl))
  6292. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  6293. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  6294. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  6295. "Expected a member function template");
  6296. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  6297. /*ExplicitArgs*/ nullptr, ObjectType,
  6298. ObjectClassification, Args, CandidateSet,
  6299. SuppressUserConversions, false, PO);
  6300. } else {
  6301. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  6302. ObjectType, ObjectClassification, Args, CandidateSet,
  6303. SuppressUserConversions, false, std::nullopt, PO);
  6304. }
  6305. }
  6306. /// AddMethodCandidate - Adds the given C++ member function to the set
  6307. /// of candidate functions, using the given function call arguments
  6308. /// and the object argument (@c Object). For example, in a call
  6309. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  6310. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  6311. /// allow user-defined conversions via constructors or conversion
  6312. /// operators.
  6313. void
  6314. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  6315. CXXRecordDecl *ActingContext, QualType ObjectType,
  6316. Expr::Classification ObjectClassification,
  6317. ArrayRef<Expr *> Args,
  6318. OverloadCandidateSet &CandidateSet,
  6319. bool SuppressUserConversions,
  6320. bool PartialOverloading,
  6321. ConversionSequenceList EarlyConversions,
  6322. OverloadCandidateParamOrder PO) {
  6323. const FunctionProtoType *Proto
  6324. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  6325. assert(Proto && "Methods without a prototype cannot be overloaded");
  6326. assert(!isa<CXXConstructorDecl>(Method) &&
  6327. "Use AddOverloadCandidate for constructors");
  6328. if (!CandidateSet.isNewCandidate(Method, PO))
  6329. return;
  6330. // C++11 [class.copy]p23: [DR1402]
  6331. // A defaulted move assignment operator that is defined as deleted is
  6332. // ignored by overload resolution.
  6333. if (Method->isDefaulted() && Method->isDeleted() &&
  6334. Method->isMoveAssignmentOperator())
  6335. return;
  6336. // Overload resolution is always an unevaluated context.
  6337. EnterExpressionEvaluationContext Unevaluated(
  6338. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6339. // Add this candidate
  6340. OverloadCandidate &Candidate =
  6341. CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
  6342. Candidate.FoundDecl = FoundDecl;
  6343. Candidate.Function = Method;
  6344. Candidate.RewriteKind =
  6345. CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
  6346. Candidate.IsSurrogate = false;
  6347. Candidate.IgnoreObjectArgument = false;
  6348. Candidate.ExplicitCallArguments = Args.size();
  6349. unsigned NumParams = Proto->getNumParams();
  6350. // (C++ 13.3.2p2): A candidate function having fewer than m
  6351. // parameters is viable only if it has an ellipsis in its parameter
  6352. // list (8.3.5).
  6353. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  6354. !Proto->isVariadic() &&
  6355. shouldEnforceArgLimit(PartialOverloading, Method)) {
  6356. Candidate.Viable = false;
  6357. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6358. return;
  6359. }
  6360. // (C++ 13.3.2p2): A candidate function having more than m parameters
  6361. // is viable only if the (m+1)st parameter has a default argument
  6362. // (8.3.6). For the purposes of overload resolution, the
  6363. // parameter list is truncated on the right, so that there are
  6364. // exactly m parameters.
  6365. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  6366. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  6367. // Not enough arguments.
  6368. Candidate.Viable = false;
  6369. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6370. return;
  6371. }
  6372. Candidate.Viable = true;
  6373. unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
  6374. if (ObjectType.isNull())
  6375. Candidate.IgnoreObjectArgument = true;
  6376. else if (Method->isStatic()) {
  6377. // [over.best.ics.general]p8
  6378. // When the parameter is the implicit object parameter of a static member
  6379. // function, the implicit conversion sequence is a standard conversion
  6380. // sequence that is neither better nor worse than any other standard
  6381. // conversion sequence.
  6382. //
  6383. // This is a rule that was introduced in C++23 to support static lambdas. We
  6384. // apply it retroactively because we want to support static lambdas as an
  6385. // extension and it doesn't hurt previous code.
  6386. Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
  6387. } else {
  6388. // Determine the implicit conversion sequence for the object
  6389. // parameter.
  6390. Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
  6391. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6392. Method, ActingContext);
  6393. if (Candidate.Conversions[FirstConvIdx].isBad()) {
  6394. Candidate.Viable = false;
  6395. Candidate.FailureKind = ovl_fail_bad_conversion;
  6396. return;
  6397. }
  6398. }
  6399. // (CUDA B.1): Check for invalid calls between targets.
  6400. if (getLangOpts().CUDA)
  6401. if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
  6402. if (!IsAllowedCUDACall(Caller, Method)) {
  6403. Candidate.Viable = false;
  6404. Candidate.FailureKind = ovl_fail_bad_target;
  6405. return;
  6406. }
  6407. if (Method->getTrailingRequiresClause()) {
  6408. ConstraintSatisfaction Satisfaction;
  6409. if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
  6410. /*ForOverloadResolution*/ true) ||
  6411. !Satisfaction.IsSatisfied) {
  6412. Candidate.Viable = false;
  6413. Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
  6414. return;
  6415. }
  6416. }
  6417. // Determine the implicit conversion sequences for each of the
  6418. // arguments.
  6419. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  6420. unsigned ConvIdx =
  6421. PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
  6422. if (Candidate.Conversions[ConvIdx].isInitialized()) {
  6423. // We already formed a conversion sequence for this parameter during
  6424. // template argument deduction.
  6425. } else if (ArgIdx < NumParams) {
  6426. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6427. // exist for each argument an implicit conversion sequence
  6428. // (13.3.3.1) that converts that argument to the corresponding
  6429. // parameter of F.
  6430. QualType ParamType = Proto->getParamType(ArgIdx);
  6431. Candidate.Conversions[ConvIdx]
  6432. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6433. SuppressUserConversions,
  6434. /*InOverloadResolution=*/true,
  6435. /*AllowObjCWritebackConversion=*/
  6436. getLangOpts().ObjCAutoRefCount);
  6437. if (Candidate.Conversions[ConvIdx].isBad()) {
  6438. Candidate.Viable = false;
  6439. Candidate.FailureKind = ovl_fail_bad_conversion;
  6440. return;
  6441. }
  6442. } else {
  6443. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6444. // argument for which there is no corresponding parameter is
  6445. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  6446. Candidate.Conversions[ConvIdx].setEllipsis();
  6447. }
  6448. }
  6449. if (EnableIfAttr *FailedAttr =
  6450. CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
  6451. Candidate.Viable = false;
  6452. Candidate.FailureKind = ovl_fail_enable_if;
  6453. Candidate.DeductionFailure.Data = FailedAttr;
  6454. return;
  6455. }
  6456. if (Method->isMultiVersion() &&
  6457. ((Method->hasAttr<TargetAttr>() &&
  6458. !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
  6459. (Method->hasAttr<TargetVersionAttr>() &&
  6460. !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
  6461. Candidate.Viable = false;
  6462. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6463. }
  6464. }
  6465. /// Add a C++ member function template as a candidate to the candidate
  6466. /// set, using template argument deduction to produce an appropriate member
  6467. /// function template specialization.
  6468. void Sema::AddMethodTemplateCandidate(
  6469. FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
  6470. CXXRecordDecl *ActingContext,
  6471. TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
  6472. Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
  6473. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6474. bool PartialOverloading, OverloadCandidateParamOrder PO) {
  6475. if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
  6476. return;
  6477. // C++ [over.match.funcs]p7:
  6478. // In each case where a candidate is a function template, candidate
  6479. // function template specializations are generated using template argument
  6480. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6481. // candidate functions in the usual way.113) A given name can refer to one
  6482. // or more function templates and also to a set of overloaded non-template
  6483. // functions. In such a case, the candidate functions generated from each
  6484. // function template are combined with the set of non-template candidate
  6485. // functions.
  6486. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6487. FunctionDecl *Specialization = nullptr;
  6488. ConversionSequenceList Conversions;
  6489. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6490. MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
  6491. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6492. return CheckNonDependentConversions(
  6493. MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
  6494. SuppressUserConversions, ActingContext, ObjectType,
  6495. ObjectClassification, PO);
  6496. })) {
  6497. OverloadCandidate &Candidate =
  6498. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6499. Candidate.FoundDecl = FoundDecl;
  6500. Candidate.Function = MethodTmpl->getTemplatedDecl();
  6501. Candidate.Viable = false;
  6502. Candidate.RewriteKind =
  6503. CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
  6504. Candidate.IsSurrogate = false;
  6505. Candidate.IgnoreObjectArgument =
  6506. cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
  6507. ObjectType.isNull();
  6508. Candidate.ExplicitCallArguments = Args.size();
  6509. if (Result == TDK_NonDependentConversionFailure)
  6510. Candidate.FailureKind = ovl_fail_bad_conversion;
  6511. else {
  6512. Candidate.FailureKind = ovl_fail_bad_deduction;
  6513. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6514. Info);
  6515. }
  6516. return;
  6517. }
  6518. // Add the function template specialization produced by template argument
  6519. // deduction as a candidate.
  6520. assert(Specialization && "Missing member function template specialization?");
  6521. assert(isa<CXXMethodDecl>(Specialization) &&
  6522. "Specialization is not a member function?");
  6523. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  6524. ActingContext, ObjectType, ObjectClassification, Args,
  6525. CandidateSet, SuppressUserConversions, PartialOverloading,
  6526. Conversions, PO);
  6527. }
  6528. /// Determine whether a given function template has a simple explicit specifier
  6529. /// or a non-value-dependent explicit-specification that evaluates to true.
  6530. static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
  6531. return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
  6532. }
  6533. /// Add a C++ function template specialization as a candidate
  6534. /// in the candidate set, using template argument deduction to produce
  6535. /// an appropriate function template specialization.
  6536. void Sema::AddTemplateOverloadCandidate(
  6537. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6538. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  6539. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6540. bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
  6541. OverloadCandidateParamOrder PO) {
  6542. if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
  6543. return;
  6544. // If the function template has a non-dependent explicit specification,
  6545. // exclude it now if appropriate; we are not permitted to perform deduction
  6546. // and substitution in this case.
  6547. if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
  6548. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  6549. Candidate.FoundDecl = FoundDecl;
  6550. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6551. Candidate.Viable = false;
  6552. Candidate.FailureKind = ovl_fail_explicit;
  6553. return;
  6554. }
  6555. // C++ [over.match.funcs]p7:
  6556. // In each case where a candidate is a function template, candidate
  6557. // function template specializations are generated using template argument
  6558. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6559. // candidate functions in the usual way.113) A given name can refer to one
  6560. // or more function templates and also to a set of overloaded non-template
  6561. // functions. In such a case, the candidate functions generated from each
  6562. // function template are combined with the set of non-template candidate
  6563. // functions.
  6564. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6565. FunctionDecl *Specialization = nullptr;
  6566. ConversionSequenceList Conversions;
  6567. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6568. FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
  6569. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6570. return CheckNonDependentConversions(
  6571. FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
  6572. SuppressUserConversions, nullptr, QualType(), {}, PO);
  6573. })) {
  6574. OverloadCandidate &Candidate =
  6575. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6576. Candidate.FoundDecl = FoundDecl;
  6577. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6578. Candidate.Viable = false;
  6579. Candidate.RewriteKind =
  6580. CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
  6581. Candidate.IsSurrogate = false;
  6582. Candidate.IsADLCandidate = IsADLCandidate;
  6583. // Ignore the object argument if there is one, since we don't have an object
  6584. // type.
  6585. Candidate.IgnoreObjectArgument =
  6586. isa<CXXMethodDecl>(Candidate.Function) &&
  6587. !isa<CXXConstructorDecl>(Candidate.Function);
  6588. Candidate.ExplicitCallArguments = Args.size();
  6589. if (Result == TDK_NonDependentConversionFailure)
  6590. Candidate.FailureKind = ovl_fail_bad_conversion;
  6591. else {
  6592. Candidate.FailureKind = ovl_fail_bad_deduction;
  6593. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6594. Info);
  6595. }
  6596. return;
  6597. }
  6598. // Add the function template specialization produced by template argument
  6599. // deduction as a candidate.
  6600. assert(Specialization && "Missing function template specialization?");
  6601. AddOverloadCandidate(
  6602. Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
  6603. PartialOverloading, AllowExplicit,
  6604. /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
  6605. }
  6606. /// Check that implicit conversion sequences can be formed for each argument
  6607. /// whose corresponding parameter has a non-dependent type, per DR1391's
  6608. /// [temp.deduct.call]p10.
  6609. bool Sema::CheckNonDependentConversions(
  6610. FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
  6611. ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
  6612. ConversionSequenceList &Conversions, bool SuppressUserConversions,
  6613. CXXRecordDecl *ActingContext, QualType ObjectType,
  6614. Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
  6615. // FIXME: The cases in which we allow explicit conversions for constructor
  6616. // arguments never consider calling a constructor template. It's not clear
  6617. // that is correct.
  6618. const bool AllowExplicit = false;
  6619. auto *FD = FunctionTemplate->getTemplatedDecl();
  6620. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  6621. bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
  6622. unsigned ThisConversions = HasThisConversion ? 1 : 0;
  6623. Conversions =
  6624. CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
  6625. // Overload resolution is always an unevaluated context.
  6626. EnterExpressionEvaluationContext Unevaluated(
  6627. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6628. // For a method call, check the 'this' conversion here too. DR1391 doesn't
  6629. // require that, but this check should never result in a hard error, and
  6630. // overload resolution is permitted to sidestep instantiations.
  6631. if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
  6632. !ObjectType.isNull()) {
  6633. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
  6634. Conversions[ConvIdx] = TryObjectArgumentInitialization(
  6635. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6636. Method, ActingContext);
  6637. if (Conversions[ConvIdx].isBad())
  6638. return true;
  6639. }
  6640. for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
  6641. ++I) {
  6642. QualType ParamType = ParamTypes[I];
  6643. if (!ParamType->isDependentType()) {
  6644. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
  6645. ? 0
  6646. : (ThisConversions + I);
  6647. Conversions[ConvIdx]
  6648. = TryCopyInitialization(*this, Args[I], ParamType,
  6649. SuppressUserConversions,
  6650. /*InOverloadResolution=*/true,
  6651. /*AllowObjCWritebackConversion=*/
  6652. getLangOpts().ObjCAutoRefCount,
  6653. AllowExplicit);
  6654. if (Conversions[ConvIdx].isBad())
  6655. return true;
  6656. }
  6657. }
  6658. return false;
  6659. }
  6660. /// Determine whether this is an allowable conversion from the result
  6661. /// of an explicit conversion operator to the expected type, per C++
  6662. /// [over.match.conv]p1 and [over.match.ref]p1.
  6663. ///
  6664. /// \param ConvType The return type of the conversion function.
  6665. ///
  6666. /// \param ToType The type we are converting to.
  6667. ///
  6668. /// \param AllowObjCPointerConversion Allow a conversion from one
  6669. /// Objective-C pointer to another.
  6670. ///
  6671. /// \returns true if the conversion is allowable, false otherwise.
  6672. static bool isAllowableExplicitConversion(Sema &S,
  6673. QualType ConvType, QualType ToType,
  6674. bool AllowObjCPointerConversion) {
  6675. QualType ToNonRefType = ToType.getNonReferenceType();
  6676. // Easy case: the types are the same.
  6677. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  6678. return true;
  6679. // Allow qualification conversions.
  6680. bool ObjCLifetimeConversion;
  6681. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  6682. ObjCLifetimeConversion))
  6683. return true;
  6684. // If we're not allowed to consider Objective-C pointer conversions,
  6685. // we're done.
  6686. if (!AllowObjCPointerConversion)
  6687. return false;
  6688. // Is this an Objective-C pointer conversion?
  6689. bool IncompatibleObjC = false;
  6690. QualType ConvertedType;
  6691. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  6692. IncompatibleObjC);
  6693. }
  6694. /// AddConversionCandidate - Add a C++ conversion function as a
  6695. /// candidate in the candidate set (C++ [over.match.conv],
  6696. /// C++ [over.match.copy]). From is the expression we're converting from,
  6697. /// and ToType is the type that we're eventually trying to convert to
  6698. /// (which may or may not be the same type as the type that the
  6699. /// conversion function produces).
  6700. void Sema::AddConversionCandidate(
  6701. CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
  6702. CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
  6703. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6704. bool AllowExplicit, bool AllowResultConversion) {
  6705. assert(!Conversion->getDescribedFunctionTemplate() &&
  6706. "Conversion function templates use AddTemplateConversionCandidate");
  6707. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  6708. if (!CandidateSet.isNewCandidate(Conversion))
  6709. return;
  6710. // If the conversion function has an undeduced return type, trigger its
  6711. // deduction now.
  6712. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  6713. if (DeduceReturnType(Conversion, From->getExprLoc()))
  6714. return;
  6715. ConvType = Conversion->getConversionType().getNonReferenceType();
  6716. }
  6717. // If we don't allow any conversion of the result type, ignore conversion
  6718. // functions that don't convert to exactly (possibly cv-qualified) T.
  6719. if (!AllowResultConversion &&
  6720. !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
  6721. return;
  6722. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  6723. // operator is only a candidate if its return type is the target type or
  6724. // can be converted to the target type with a qualification conversion.
  6725. //
  6726. // FIXME: Include such functions in the candidate list and explain why we
  6727. // can't select them.
  6728. if (Conversion->isExplicit() &&
  6729. !isAllowableExplicitConversion(*this, ConvType, ToType,
  6730. AllowObjCConversionOnExplicit))
  6731. return;
  6732. // Overload resolution is always an unevaluated context.
  6733. EnterExpressionEvaluationContext Unevaluated(
  6734. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6735. // Add this candidate
  6736. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  6737. Candidate.FoundDecl = FoundDecl;
  6738. Candidate.Function = Conversion;
  6739. Candidate.IsSurrogate = false;
  6740. Candidate.IgnoreObjectArgument = false;
  6741. Candidate.FinalConversion.setAsIdentityConversion();
  6742. Candidate.FinalConversion.setFromType(ConvType);
  6743. Candidate.FinalConversion.setAllToTypes(ToType);
  6744. Candidate.Viable = true;
  6745. Candidate.ExplicitCallArguments = 1;
  6746. // Explicit functions are not actually candidates at all if we're not
  6747. // allowing them in this context, but keep them around so we can point
  6748. // to them in diagnostics.
  6749. if (!AllowExplicit && Conversion->isExplicit()) {
  6750. Candidate.Viable = false;
  6751. Candidate.FailureKind = ovl_fail_explicit;
  6752. return;
  6753. }
  6754. // C++ [over.match.funcs]p4:
  6755. // For conversion functions, the function is considered to be a member of
  6756. // the class of the implicit implied object argument for the purpose of
  6757. // defining the type of the implicit object parameter.
  6758. //
  6759. // Determine the implicit conversion sequence for the implicit
  6760. // object parameter.
  6761. QualType ImplicitParamType = From->getType();
  6762. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  6763. ImplicitParamType = FromPtrType->getPointeeType();
  6764. CXXRecordDecl *ConversionContext
  6765. = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
  6766. Candidate.Conversions[0] = TryObjectArgumentInitialization(
  6767. *this, CandidateSet.getLocation(), From->getType(),
  6768. From->Classify(Context), Conversion, ConversionContext);
  6769. if (Candidate.Conversions[0].isBad()) {
  6770. Candidate.Viable = false;
  6771. Candidate.FailureKind = ovl_fail_bad_conversion;
  6772. return;
  6773. }
  6774. if (Conversion->getTrailingRequiresClause()) {
  6775. ConstraintSatisfaction Satisfaction;
  6776. if (CheckFunctionConstraints(Conversion, Satisfaction) ||
  6777. !Satisfaction.IsSatisfied) {
  6778. Candidate.Viable = false;
  6779. Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
  6780. return;
  6781. }
  6782. }
  6783. // We won't go through a user-defined type conversion function to convert a
  6784. // derived to base as such conversions are given Conversion Rank. They only
  6785. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  6786. QualType FromCanon
  6787. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  6788. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  6789. if (FromCanon == ToCanon ||
  6790. IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
  6791. Candidate.Viable = false;
  6792. Candidate.FailureKind = ovl_fail_trivial_conversion;
  6793. return;
  6794. }
  6795. // To determine what the conversion from the result of calling the
  6796. // conversion function to the type we're eventually trying to
  6797. // convert to (ToType), we need to synthesize a call to the
  6798. // conversion function and attempt copy initialization from it. This
  6799. // makes sure that we get the right semantics with respect to
  6800. // lvalues/rvalues and the type. Fortunately, we can allocate this
  6801. // call on the stack and we don't need its arguments to be
  6802. // well-formed.
  6803. DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
  6804. VK_LValue, From->getBeginLoc());
  6805. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  6806. Context.getPointerType(Conversion->getType()),
  6807. CK_FunctionToPointerDecay, &ConversionRef,
  6808. VK_PRValue, FPOptionsOverride());
  6809. QualType ConversionType = Conversion->getConversionType();
  6810. if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
  6811. Candidate.Viable = false;
  6812. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6813. return;
  6814. }
  6815. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  6816. // Note that it is safe to allocate CallExpr on the stack here because
  6817. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  6818. // allocator).
  6819. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  6820. alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
  6821. CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
  6822. Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
  6823. ImplicitConversionSequence ICS =
  6824. TryCopyInitialization(*this, TheTemporaryCall, ToType,
  6825. /*SuppressUserConversions=*/true,
  6826. /*InOverloadResolution=*/false,
  6827. /*AllowObjCWritebackConversion=*/false);
  6828. switch (ICS.getKind()) {
  6829. case ImplicitConversionSequence::StandardConversion:
  6830. Candidate.FinalConversion = ICS.Standard;
  6831. // C++ [over.ics.user]p3:
  6832. // If the user-defined conversion is specified by a specialization of a
  6833. // conversion function template, the second standard conversion sequence
  6834. // shall have exact match rank.
  6835. if (Conversion->getPrimaryTemplate() &&
  6836. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  6837. Candidate.Viable = false;
  6838. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  6839. return;
  6840. }
  6841. // C++0x [dcl.init.ref]p5:
  6842. // In the second case, if the reference is an rvalue reference and
  6843. // the second standard conversion sequence of the user-defined
  6844. // conversion sequence includes an lvalue-to-rvalue conversion, the
  6845. // program is ill-formed.
  6846. if (ToType->isRValueReferenceType() &&
  6847. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  6848. Candidate.Viable = false;
  6849. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6850. return;
  6851. }
  6852. break;
  6853. case ImplicitConversionSequence::BadConversion:
  6854. Candidate.Viable = false;
  6855. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6856. return;
  6857. default:
  6858. llvm_unreachable(
  6859. "Can only end up with a standard conversion sequence or failure");
  6860. }
  6861. if (EnableIfAttr *FailedAttr =
  6862. CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
  6863. Candidate.Viable = false;
  6864. Candidate.FailureKind = ovl_fail_enable_if;
  6865. Candidate.DeductionFailure.Data = FailedAttr;
  6866. return;
  6867. }
  6868. if (Conversion->isMultiVersion() &&
  6869. ((Conversion->hasAttr<TargetAttr>() &&
  6870. !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
  6871. (Conversion->hasAttr<TargetVersionAttr>() &&
  6872. !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
  6873. Candidate.Viable = false;
  6874. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6875. }
  6876. }
  6877. /// Adds a conversion function template specialization
  6878. /// candidate to the overload set, using template argument deduction
  6879. /// to deduce the template arguments of the conversion function
  6880. /// template from the type that we are converting to (C++
  6881. /// [temp.deduct.conv]).
  6882. void Sema::AddTemplateConversionCandidate(
  6883. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6884. CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
  6885. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6886. bool AllowExplicit, bool AllowResultConversion) {
  6887. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  6888. "Only conversion function templates permitted here");
  6889. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  6890. return;
  6891. // If the function template has a non-dependent explicit specification,
  6892. // exclude it now if appropriate; we are not permitted to perform deduction
  6893. // and substitution in this case.
  6894. if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
  6895. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  6896. Candidate.FoundDecl = FoundDecl;
  6897. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6898. Candidate.Viable = false;
  6899. Candidate.FailureKind = ovl_fail_explicit;
  6900. return;
  6901. }
  6902. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6903. CXXConversionDecl *Specialization = nullptr;
  6904. if (TemplateDeductionResult Result
  6905. = DeduceTemplateArguments(FunctionTemplate, ToType,
  6906. Specialization, Info)) {
  6907. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  6908. Candidate.FoundDecl = FoundDecl;
  6909. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6910. Candidate.Viable = false;
  6911. Candidate.FailureKind = ovl_fail_bad_deduction;
  6912. Candidate.IsSurrogate = false;
  6913. Candidate.IgnoreObjectArgument = false;
  6914. Candidate.ExplicitCallArguments = 1;
  6915. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6916. Info);
  6917. return;
  6918. }
  6919. // Add the conversion function template specialization produced by
  6920. // template argument deduction as a candidate.
  6921. assert(Specialization && "Missing function template specialization?");
  6922. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  6923. CandidateSet, AllowObjCConversionOnExplicit,
  6924. AllowExplicit, AllowResultConversion);
  6925. }
  6926. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  6927. /// converts the given @c Object to a function pointer via the
  6928. /// conversion function @c Conversion, and then attempts to call it
  6929. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  6930. /// the type of function that we'll eventually be calling.
  6931. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  6932. DeclAccessPair FoundDecl,
  6933. CXXRecordDecl *ActingContext,
  6934. const FunctionProtoType *Proto,
  6935. Expr *Object,
  6936. ArrayRef<Expr *> Args,
  6937. OverloadCandidateSet& CandidateSet) {
  6938. if (!CandidateSet.isNewCandidate(Conversion))
  6939. return;
  6940. // Overload resolution is always an unevaluated context.
  6941. EnterExpressionEvaluationContext Unevaluated(
  6942. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6943. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  6944. Candidate.FoundDecl = FoundDecl;
  6945. Candidate.Function = nullptr;
  6946. Candidate.Surrogate = Conversion;
  6947. Candidate.Viable = true;
  6948. Candidate.IsSurrogate = true;
  6949. Candidate.IgnoreObjectArgument = false;
  6950. Candidate.ExplicitCallArguments = Args.size();
  6951. // Determine the implicit conversion sequence for the implicit
  6952. // object parameter.
  6953. ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
  6954. *this, CandidateSet.getLocation(), Object->getType(),
  6955. Object->Classify(Context), Conversion, ActingContext);
  6956. if (ObjectInit.isBad()) {
  6957. Candidate.Viable = false;
  6958. Candidate.FailureKind = ovl_fail_bad_conversion;
  6959. Candidate.Conversions[0] = ObjectInit;
  6960. return;
  6961. }
  6962. // The first conversion is actually a user-defined conversion whose
  6963. // first conversion is ObjectInit's standard conversion (which is
  6964. // effectively a reference binding). Record it as such.
  6965. Candidate.Conversions[0].setUserDefined();
  6966. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  6967. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  6968. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  6969. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  6970. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  6971. Candidate.Conversions[0].UserDefined.After
  6972. = Candidate.Conversions[0].UserDefined.Before;
  6973. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  6974. // Find the
  6975. unsigned NumParams = Proto->getNumParams();
  6976. // (C++ 13.3.2p2): A candidate function having fewer than m
  6977. // parameters is viable only if it has an ellipsis in its parameter
  6978. // list (8.3.5).
  6979. if (Args.size() > NumParams && !Proto->isVariadic()) {
  6980. Candidate.Viable = false;
  6981. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6982. return;
  6983. }
  6984. // Function types don't have any default arguments, so just check if
  6985. // we have enough arguments.
  6986. if (Args.size() < NumParams) {
  6987. // Not enough arguments.
  6988. Candidate.Viable = false;
  6989. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6990. return;
  6991. }
  6992. // Determine the implicit conversion sequences for each of the
  6993. // arguments.
  6994. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6995. if (ArgIdx < NumParams) {
  6996. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6997. // exist for each argument an implicit conversion sequence
  6998. // (13.3.3.1) that converts that argument to the corresponding
  6999. // parameter of F.
  7000. QualType ParamType = Proto->getParamType(ArgIdx);
  7001. Candidate.Conversions[ArgIdx + 1]
  7002. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  7003. /*SuppressUserConversions=*/false,
  7004. /*InOverloadResolution=*/false,
  7005. /*AllowObjCWritebackConversion=*/
  7006. getLangOpts().ObjCAutoRefCount);
  7007. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  7008. Candidate.Viable = false;
  7009. Candidate.FailureKind = ovl_fail_bad_conversion;
  7010. return;
  7011. }
  7012. } else {
  7013. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  7014. // argument for which there is no corresponding parameter is
  7015. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  7016. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  7017. }
  7018. }
  7019. if (EnableIfAttr *FailedAttr =
  7020. CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
  7021. Candidate.Viable = false;
  7022. Candidate.FailureKind = ovl_fail_enable_if;
  7023. Candidate.DeductionFailure.Data = FailedAttr;
  7024. return;
  7025. }
  7026. }
  7027. /// Add all of the non-member operator function declarations in the given
  7028. /// function set to the overload candidate set.
  7029. void Sema::AddNonMemberOperatorCandidates(
  7030. const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
  7031. OverloadCandidateSet &CandidateSet,
  7032. TemplateArgumentListInfo *ExplicitTemplateArgs) {
  7033. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  7034. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  7035. ArrayRef<Expr *> FunctionArgs = Args;
  7036. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  7037. FunctionDecl *FD =
  7038. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  7039. // Don't consider rewritten functions if we're not rewriting.
  7040. if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
  7041. continue;
  7042. assert(!isa<CXXMethodDecl>(FD) &&
  7043. "unqualified operator lookup found a member function");
  7044. if (FunTmpl) {
  7045. AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
  7046. FunctionArgs, CandidateSet);
  7047. if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
  7048. AddTemplateOverloadCandidate(
  7049. FunTmpl, F.getPair(), ExplicitTemplateArgs,
  7050. {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
  7051. true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
  7052. } else {
  7053. if (ExplicitTemplateArgs)
  7054. continue;
  7055. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
  7056. if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
  7057. AddOverloadCandidate(
  7058. FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
  7059. false, false, true, false, ADLCallKind::NotADL, std::nullopt,
  7060. OverloadCandidateParamOrder::Reversed);
  7061. }
  7062. }
  7063. }
  7064. /// Add overload candidates for overloaded operators that are
  7065. /// member functions.
  7066. ///
  7067. /// Add the overloaded operator candidates that are member functions
  7068. /// for the operator Op that was used in an operator expression such
  7069. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  7070. /// CandidateSet will store the added overload candidates. (C++
  7071. /// [over.match.oper]).
  7072. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  7073. SourceLocation OpLoc,
  7074. ArrayRef<Expr *> Args,
  7075. OverloadCandidateSet &CandidateSet,
  7076. OverloadCandidateParamOrder PO) {
  7077. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  7078. // C++ [over.match.oper]p3:
  7079. // For a unary operator @ with an operand of a type whose
  7080. // cv-unqualified version is T1, and for a binary operator @ with
  7081. // a left operand of a type whose cv-unqualified version is T1 and
  7082. // a right operand of a type whose cv-unqualified version is T2,
  7083. // three sets of candidate functions, designated member
  7084. // candidates, non-member candidates and built-in candidates, are
  7085. // constructed as follows:
  7086. QualType T1 = Args[0]->getType();
  7087. // -- If T1 is a complete class type or a class currently being
  7088. // defined, the set of member candidates is the result of the
  7089. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  7090. // the set of member candidates is empty.
  7091. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  7092. // Complete the type if it can be completed.
  7093. if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
  7094. return;
  7095. // If the type is neither complete nor being defined, bail out now.
  7096. if (!T1Rec->getDecl()->getDefinition())
  7097. return;
  7098. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  7099. LookupQualifiedName(Operators, T1Rec->getDecl());
  7100. Operators.suppressDiagnostics();
  7101. for (LookupResult::iterator Oper = Operators.begin(),
  7102. OperEnd = Operators.end();
  7103. Oper != OperEnd; ++Oper) {
  7104. if (Oper->getAsFunction() &&
  7105. PO == OverloadCandidateParamOrder::Reversed &&
  7106. !CandidateSet.getRewriteInfo().shouldAddReversed(
  7107. *this, {Args[1], Args[0]}, Oper->getAsFunction()))
  7108. continue;
  7109. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  7110. Args[0]->Classify(Context), Args.slice(1),
  7111. CandidateSet, /*SuppressUserConversion=*/false, PO);
  7112. }
  7113. }
  7114. }
  7115. /// AddBuiltinCandidate - Add a candidate for a built-in
  7116. /// operator. ResultTy and ParamTys are the result and parameter types
  7117. /// of the built-in candidate, respectively. Args and NumArgs are the
  7118. /// arguments being passed to the candidate. IsAssignmentOperator
  7119. /// should be true when this built-in candidate is an assignment
  7120. /// operator. NumContextualBoolArguments is the number of arguments
  7121. /// (at the beginning of the argument list) that will be contextually
  7122. /// converted to bool.
  7123. void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
  7124. OverloadCandidateSet& CandidateSet,
  7125. bool IsAssignmentOperator,
  7126. unsigned NumContextualBoolArguments) {
  7127. // Overload resolution is always an unevaluated context.
  7128. EnterExpressionEvaluationContext Unevaluated(
  7129. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  7130. // Add this candidate
  7131. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  7132. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  7133. Candidate.Function = nullptr;
  7134. Candidate.IsSurrogate = false;
  7135. Candidate.IgnoreObjectArgument = false;
  7136. std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
  7137. // Determine the implicit conversion sequences for each of the
  7138. // arguments.
  7139. Candidate.Viable = true;
  7140. Candidate.ExplicitCallArguments = Args.size();
  7141. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7142. // C++ [over.match.oper]p4:
  7143. // For the built-in assignment operators, conversions of the
  7144. // left operand are restricted as follows:
  7145. // -- no temporaries are introduced to hold the left operand, and
  7146. // -- no user-defined conversions are applied to the left
  7147. // operand to achieve a type match with the left-most
  7148. // parameter of a built-in candidate.
  7149. //
  7150. // We block these conversions by turning off user-defined
  7151. // conversions, since that is the only way that initialization of
  7152. // a reference to a non-class type can occur from something that
  7153. // is not of the same type.
  7154. if (ArgIdx < NumContextualBoolArguments) {
  7155. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  7156. "Contextual conversion to bool requires bool type");
  7157. Candidate.Conversions[ArgIdx]
  7158. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  7159. } else {
  7160. Candidate.Conversions[ArgIdx]
  7161. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  7162. ArgIdx == 0 && IsAssignmentOperator,
  7163. /*InOverloadResolution=*/false,
  7164. /*AllowObjCWritebackConversion=*/
  7165. getLangOpts().ObjCAutoRefCount);
  7166. }
  7167. if (Candidate.Conversions[ArgIdx].isBad()) {
  7168. Candidate.Viable = false;
  7169. Candidate.FailureKind = ovl_fail_bad_conversion;
  7170. break;
  7171. }
  7172. }
  7173. }
  7174. namespace {
  7175. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  7176. /// candidate operator functions for built-in operators (C++
  7177. /// [over.built]). The types are separated into pointer types and
  7178. /// enumeration types.
  7179. class BuiltinCandidateTypeSet {
  7180. /// TypeSet - A set of types.
  7181. typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
  7182. llvm::SmallPtrSet<QualType, 8>> TypeSet;
  7183. /// PointerTypes - The set of pointer types that will be used in the
  7184. /// built-in candidates.
  7185. TypeSet PointerTypes;
  7186. /// MemberPointerTypes - The set of member pointer types that will be
  7187. /// used in the built-in candidates.
  7188. TypeSet MemberPointerTypes;
  7189. /// EnumerationTypes - The set of enumeration types that will be
  7190. /// used in the built-in candidates.
  7191. TypeSet EnumerationTypes;
  7192. /// The set of vector types that will be used in the built-in
  7193. /// candidates.
  7194. TypeSet VectorTypes;
  7195. /// The set of matrix types that will be used in the built-in
  7196. /// candidates.
  7197. TypeSet MatrixTypes;
  7198. /// A flag indicating non-record types are viable candidates
  7199. bool HasNonRecordTypes;
  7200. /// A flag indicating whether either arithmetic or enumeration types
  7201. /// were present in the candidate set.
  7202. bool HasArithmeticOrEnumeralTypes;
  7203. /// A flag indicating whether the nullptr type was present in the
  7204. /// candidate set.
  7205. bool HasNullPtrType;
  7206. /// Sema - The semantic analysis instance where we are building the
  7207. /// candidate type set.
  7208. Sema &SemaRef;
  7209. /// Context - The AST context in which we will build the type sets.
  7210. ASTContext &Context;
  7211. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  7212. const Qualifiers &VisibleQuals);
  7213. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  7214. public:
  7215. /// iterator - Iterates through the types that are part of the set.
  7216. typedef TypeSet::iterator iterator;
  7217. BuiltinCandidateTypeSet(Sema &SemaRef)
  7218. : HasNonRecordTypes(false),
  7219. HasArithmeticOrEnumeralTypes(false),
  7220. HasNullPtrType(false),
  7221. SemaRef(SemaRef),
  7222. Context(SemaRef.Context) { }
  7223. void AddTypesConvertedFrom(QualType Ty,
  7224. SourceLocation Loc,
  7225. bool AllowUserConversions,
  7226. bool AllowExplicitConversions,
  7227. const Qualifiers &VisibleTypeConversionsQuals);
  7228. llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
  7229. llvm::iterator_range<iterator> member_pointer_types() {
  7230. return MemberPointerTypes;
  7231. }
  7232. llvm::iterator_range<iterator> enumeration_types() {
  7233. return EnumerationTypes;
  7234. }
  7235. llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
  7236. llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
  7237. bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
  7238. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  7239. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  7240. bool hasNullPtrType() const { return HasNullPtrType; }
  7241. };
  7242. } // end anonymous namespace
  7243. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  7244. /// the set of pointer types along with any more-qualified variants of
  7245. /// that type. For example, if @p Ty is "int const *", this routine
  7246. /// will add "int const *", "int const volatile *", "int const
  7247. /// restrict *", and "int const volatile restrict *" to the set of
  7248. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  7249. /// false otherwise.
  7250. ///
  7251. /// FIXME: what to do about extended qualifiers?
  7252. bool
  7253. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  7254. const Qualifiers &VisibleQuals) {
  7255. // Insert this type.
  7256. if (!PointerTypes.insert(Ty))
  7257. return false;
  7258. QualType PointeeTy;
  7259. const PointerType *PointerTy = Ty->getAs<PointerType>();
  7260. bool buildObjCPtr = false;
  7261. if (!PointerTy) {
  7262. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  7263. PointeeTy = PTy->getPointeeType();
  7264. buildObjCPtr = true;
  7265. } else {
  7266. PointeeTy = PointerTy->getPointeeType();
  7267. }
  7268. // Don't add qualified variants of arrays. For one, they're not allowed
  7269. // (the qualifier would sink to the element type), and for another, the
  7270. // only overload situation where it matters is subscript or pointer +- int,
  7271. // and those shouldn't have qualifier variants anyway.
  7272. if (PointeeTy->isArrayType())
  7273. return true;
  7274. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  7275. bool hasVolatile = VisibleQuals.hasVolatile();
  7276. bool hasRestrict = VisibleQuals.hasRestrict();
  7277. // Iterate through all strict supersets of BaseCVR.
  7278. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  7279. if ((CVR | BaseCVR) != CVR) continue;
  7280. // Skip over volatile if no volatile found anywhere in the types.
  7281. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  7282. // Skip over restrict if no restrict found anywhere in the types, or if
  7283. // the type cannot be restrict-qualified.
  7284. if ((CVR & Qualifiers::Restrict) &&
  7285. (!hasRestrict ||
  7286. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  7287. continue;
  7288. // Build qualified pointee type.
  7289. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  7290. // Build qualified pointer type.
  7291. QualType QPointerTy;
  7292. if (!buildObjCPtr)
  7293. QPointerTy = Context.getPointerType(QPointeeTy);
  7294. else
  7295. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  7296. // Insert qualified pointer type.
  7297. PointerTypes.insert(QPointerTy);
  7298. }
  7299. return true;
  7300. }
  7301. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  7302. /// to the set of pointer types along with any more-qualified variants of
  7303. /// that type. For example, if @p Ty is "int const *", this routine
  7304. /// will add "int const *", "int const volatile *", "int const
  7305. /// restrict *", and "int const volatile restrict *" to the set of
  7306. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  7307. /// false otherwise.
  7308. ///
  7309. /// FIXME: what to do about extended qualifiers?
  7310. bool
  7311. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  7312. QualType Ty) {
  7313. // Insert this type.
  7314. if (!MemberPointerTypes.insert(Ty))
  7315. return false;
  7316. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  7317. assert(PointerTy && "type was not a member pointer type!");
  7318. QualType PointeeTy = PointerTy->getPointeeType();
  7319. // Don't add qualified variants of arrays. For one, they're not allowed
  7320. // (the qualifier would sink to the element type), and for another, the
  7321. // only overload situation where it matters is subscript or pointer +- int,
  7322. // and those shouldn't have qualifier variants anyway.
  7323. if (PointeeTy->isArrayType())
  7324. return true;
  7325. const Type *ClassTy = PointerTy->getClass();
  7326. // Iterate through all strict supersets of the pointee type's CVR
  7327. // qualifiers.
  7328. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  7329. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  7330. if ((CVR | BaseCVR) != CVR) continue;
  7331. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  7332. MemberPointerTypes.insert(
  7333. Context.getMemberPointerType(QPointeeTy, ClassTy));
  7334. }
  7335. return true;
  7336. }
  7337. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  7338. /// Ty can be implicit converted to the given set of @p Types. We're
  7339. /// primarily interested in pointer types and enumeration types. We also
  7340. /// take member pointer types, for the conditional operator.
  7341. /// AllowUserConversions is true if we should look at the conversion
  7342. /// functions of a class type, and AllowExplicitConversions if we
  7343. /// should also include the explicit conversion functions of a class
  7344. /// type.
  7345. void
  7346. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  7347. SourceLocation Loc,
  7348. bool AllowUserConversions,
  7349. bool AllowExplicitConversions,
  7350. const Qualifiers &VisibleQuals) {
  7351. // Only deal with canonical types.
  7352. Ty = Context.getCanonicalType(Ty);
  7353. // Look through reference types; they aren't part of the type of an
  7354. // expression for the purposes of conversions.
  7355. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  7356. Ty = RefTy->getPointeeType();
  7357. // If we're dealing with an array type, decay to the pointer.
  7358. if (Ty->isArrayType())
  7359. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  7360. // Otherwise, we don't care about qualifiers on the type.
  7361. Ty = Ty.getLocalUnqualifiedType();
  7362. // Flag if we ever add a non-record type.
  7363. const RecordType *TyRec = Ty->getAs<RecordType>();
  7364. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  7365. // Flag if we encounter an arithmetic type.
  7366. HasArithmeticOrEnumeralTypes =
  7367. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  7368. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  7369. PointerTypes.insert(Ty);
  7370. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  7371. // Insert our type, and its more-qualified variants, into the set
  7372. // of types.
  7373. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  7374. return;
  7375. } else if (Ty->isMemberPointerType()) {
  7376. // Member pointers are far easier, since the pointee can't be converted.
  7377. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  7378. return;
  7379. } else if (Ty->isEnumeralType()) {
  7380. HasArithmeticOrEnumeralTypes = true;
  7381. EnumerationTypes.insert(Ty);
  7382. } else if (Ty->isVectorType()) {
  7383. // We treat vector types as arithmetic types in many contexts as an
  7384. // extension.
  7385. HasArithmeticOrEnumeralTypes = true;
  7386. VectorTypes.insert(Ty);
  7387. } else if (Ty->isMatrixType()) {
  7388. // Similar to vector types, we treat vector types as arithmetic types in
  7389. // many contexts as an extension.
  7390. HasArithmeticOrEnumeralTypes = true;
  7391. MatrixTypes.insert(Ty);
  7392. } else if (Ty->isNullPtrType()) {
  7393. HasNullPtrType = true;
  7394. } else if (AllowUserConversions && TyRec) {
  7395. // No conversion functions in incomplete types.
  7396. if (!SemaRef.isCompleteType(Loc, Ty))
  7397. return;
  7398. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  7399. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  7400. if (isa<UsingShadowDecl>(D))
  7401. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  7402. // Skip conversion function templates; they don't tell us anything
  7403. // about which builtin types we can convert to.
  7404. if (isa<FunctionTemplateDecl>(D))
  7405. continue;
  7406. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  7407. if (AllowExplicitConversions || !Conv->isExplicit()) {
  7408. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  7409. VisibleQuals);
  7410. }
  7411. }
  7412. }
  7413. }
  7414. /// Helper function for adjusting address spaces for the pointer or reference
  7415. /// operands of builtin operators depending on the argument.
  7416. static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
  7417. Expr *Arg) {
  7418. return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
  7419. }
  7420. /// Helper function for AddBuiltinOperatorCandidates() that adds
  7421. /// the volatile- and non-volatile-qualified assignment operators for the
  7422. /// given type to the candidate set.
  7423. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  7424. QualType T,
  7425. ArrayRef<Expr *> Args,
  7426. OverloadCandidateSet &CandidateSet) {
  7427. QualType ParamTypes[2];
  7428. // T& operator=(T&, T)
  7429. ParamTypes[0] = S.Context.getLValueReferenceType(
  7430. AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
  7431. ParamTypes[1] = T;
  7432. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7433. /*IsAssignmentOperator=*/true);
  7434. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  7435. // volatile T& operator=(volatile T&, T)
  7436. ParamTypes[0] = S.Context.getLValueReferenceType(
  7437. AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
  7438. Args[0]));
  7439. ParamTypes[1] = T;
  7440. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7441. /*IsAssignmentOperator=*/true);
  7442. }
  7443. }
  7444. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  7445. /// if any, found in visible type conversion functions found in ArgExpr's type.
  7446. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  7447. Qualifiers VRQuals;
  7448. const RecordType *TyRec;
  7449. if (const MemberPointerType *RHSMPType =
  7450. ArgExpr->getType()->getAs<MemberPointerType>())
  7451. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  7452. else
  7453. TyRec = ArgExpr->getType()->getAs<RecordType>();
  7454. if (!TyRec) {
  7455. // Just to be safe, assume the worst case.
  7456. VRQuals.addVolatile();
  7457. VRQuals.addRestrict();
  7458. return VRQuals;
  7459. }
  7460. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  7461. if (!ClassDecl->hasDefinition())
  7462. return VRQuals;
  7463. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  7464. if (isa<UsingShadowDecl>(D))
  7465. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  7466. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  7467. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  7468. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  7469. CanTy = ResTypeRef->getPointeeType();
  7470. // Need to go down the pointer/mempointer chain and add qualifiers
  7471. // as see them.
  7472. bool done = false;
  7473. while (!done) {
  7474. if (CanTy.isRestrictQualified())
  7475. VRQuals.addRestrict();
  7476. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  7477. CanTy = ResTypePtr->getPointeeType();
  7478. else if (const MemberPointerType *ResTypeMPtr =
  7479. CanTy->getAs<MemberPointerType>())
  7480. CanTy = ResTypeMPtr->getPointeeType();
  7481. else
  7482. done = true;
  7483. if (CanTy.isVolatileQualified())
  7484. VRQuals.addVolatile();
  7485. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  7486. return VRQuals;
  7487. }
  7488. }
  7489. }
  7490. return VRQuals;
  7491. }
  7492. // Note: We're currently only handling qualifiers that are meaningful for the
  7493. // LHS of compound assignment overloading.
  7494. static void forAllQualifierCombinationsImpl(
  7495. QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
  7496. llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
  7497. // _Atomic
  7498. if (Available.hasAtomic()) {
  7499. Available.removeAtomic();
  7500. forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
  7501. forAllQualifierCombinationsImpl(Available, Applied, Callback);
  7502. return;
  7503. }
  7504. // volatile
  7505. if (Available.hasVolatile()) {
  7506. Available.removeVolatile();
  7507. assert(!Applied.hasVolatile());
  7508. forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
  7509. Callback);
  7510. forAllQualifierCombinationsImpl(Available, Applied, Callback);
  7511. return;
  7512. }
  7513. Callback(Applied);
  7514. }
  7515. static void forAllQualifierCombinations(
  7516. QualifiersAndAtomic Quals,
  7517. llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
  7518. return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
  7519. Callback);
  7520. }
  7521. static QualType makeQualifiedLValueReferenceType(QualType Base,
  7522. QualifiersAndAtomic Quals,
  7523. Sema &S) {
  7524. if (Quals.hasAtomic())
  7525. Base = S.Context.getAtomicType(Base);
  7526. if (Quals.hasVolatile())
  7527. Base = S.Context.getVolatileType(Base);
  7528. return S.Context.getLValueReferenceType(Base);
  7529. }
  7530. namespace {
  7531. /// Helper class to manage the addition of builtin operator overload
  7532. /// candidates. It provides shared state and utility methods used throughout
  7533. /// the process, as well as a helper method to add each group of builtin
  7534. /// operator overloads from the standard to a candidate set.
  7535. class BuiltinOperatorOverloadBuilder {
  7536. // Common instance state available to all overload candidate addition methods.
  7537. Sema &S;
  7538. ArrayRef<Expr *> Args;
  7539. QualifiersAndAtomic VisibleTypeConversionsQuals;
  7540. bool HasArithmeticOrEnumeralCandidateType;
  7541. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  7542. OverloadCandidateSet &CandidateSet;
  7543. static constexpr int ArithmeticTypesCap = 24;
  7544. SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
  7545. // Define some indices used to iterate over the arithmetic types in
  7546. // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
  7547. // types are that preserved by promotion (C++ [over.built]p2).
  7548. unsigned FirstIntegralType,
  7549. LastIntegralType;
  7550. unsigned FirstPromotedIntegralType,
  7551. LastPromotedIntegralType;
  7552. unsigned FirstPromotedArithmeticType,
  7553. LastPromotedArithmeticType;
  7554. unsigned NumArithmeticTypes;
  7555. void InitArithmeticTypes() {
  7556. // Start of promoted types.
  7557. FirstPromotedArithmeticType = 0;
  7558. ArithmeticTypes.push_back(S.Context.FloatTy);
  7559. ArithmeticTypes.push_back(S.Context.DoubleTy);
  7560. ArithmeticTypes.push_back(S.Context.LongDoubleTy);
  7561. if (S.Context.getTargetInfo().hasFloat128Type())
  7562. ArithmeticTypes.push_back(S.Context.Float128Ty);
  7563. if (S.Context.getTargetInfo().hasIbm128Type())
  7564. ArithmeticTypes.push_back(S.Context.Ibm128Ty);
  7565. // Start of integral types.
  7566. FirstIntegralType = ArithmeticTypes.size();
  7567. FirstPromotedIntegralType = ArithmeticTypes.size();
  7568. ArithmeticTypes.push_back(S.Context.IntTy);
  7569. ArithmeticTypes.push_back(S.Context.LongTy);
  7570. ArithmeticTypes.push_back(S.Context.LongLongTy);
  7571. if (S.Context.getTargetInfo().hasInt128Type() ||
  7572. (S.Context.getAuxTargetInfo() &&
  7573. S.Context.getAuxTargetInfo()->hasInt128Type()))
  7574. ArithmeticTypes.push_back(S.Context.Int128Ty);
  7575. ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
  7576. ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
  7577. ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
  7578. if (S.Context.getTargetInfo().hasInt128Type() ||
  7579. (S.Context.getAuxTargetInfo() &&
  7580. S.Context.getAuxTargetInfo()->hasInt128Type()))
  7581. ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
  7582. LastPromotedIntegralType = ArithmeticTypes.size();
  7583. LastPromotedArithmeticType = ArithmeticTypes.size();
  7584. // End of promoted types.
  7585. ArithmeticTypes.push_back(S.Context.BoolTy);
  7586. ArithmeticTypes.push_back(S.Context.CharTy);
  7587. ArithmeticTypes.push_back(S.Context.WCharTy);
  7588. if (S.Context.getLangOpts().Char8)
  7589. ArithmeticTypes.push_back(S.Context.Char8Ty);
  7590. ArithmeticTypes.push_back(S.Context.Char16Ty);
  7591. ArithmeticTypes.push_back(S.Context.Char32Ty);
  7592. ArithmeticTypes.push_back(S.Context.SignedCharTy);
  7593. ArithmeticTypes.push_back(S.Context.ShortTy);
  7594. ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
  7595. ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
  7596. LastIntegralType = ArithmeticTypes.size();
  7597. NumArithmeticTypes = ArithmeticTypes.size();
  7598. // End of integral types.
  7599. // FIXME: What about complex? What about half?
  7600. assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
  7601. "Enough inline storage for all arithmetic types.");
  7602. }
  7603. /// Helper method to factor out the common pattern of adding overloads
  7604. /// for '++' and '--' builtin operators.
  7605. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  7606. bool HasVolatile,
  7607. bool HasRestrict) {
  7608. QualType ParamTypes[2] = {
  7609. S.Context.getLValueReferenceType(CandidateTy),
  7610. S.Context.IntTy
  7611. };
  7612. // Non-volatile version.
  7613. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7614. // Use a heuristic to reduce number of builtin candidates in the set:
  7615. // add volatile version only if there are conversions to a volatile type.
  7616. if (HasVolatile) {
  7617. ParamTypes[0] =
  7618. S.Context.getLValueReferenceType(
  7619. S.Context.getVolatileType(CandidateTy));
  7620. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7621. }
  7622. // Add restrict version only if there are conversions to a restrict type
  7623. // and our candidate type is a non-restrict-qualified pointer.
  7624. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  7625. !CandidateTy.isRestrictQualified()) {
  7626. ParamTypes[0]
  7627. = S.Context.getLValueReferenceType(
  7628. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  7629. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7630. if (HasVolatile) {
  7631. ParamTypes[0]
  7632. = S.Context.getLValueReferenceType(
  7633. S.Context.getCVRQualifiedType(CandidateTy,
  7634. (Qualifiers::Volatile |
  7635. Qualifiers::Restrict)));
  7636. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7637. }
  7638. }
  7639. }
  7640. /// Helper to add an overload candidate for a binary builtin with types \p L
  7641. /// and \p R.
  7642. void AddCandidate(QualType L, QualType R) {
  7643. QualType LandR[2] = {L, R};
  7644. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7645. }
  7646. public:
  7647. BuiltinOperatorOverloadBuilder(
  7648. Sema &S, ArrayRef<Expr *> Args,
  7649. QualifiersAndAtomic VisibleTypeConversionsQuals,
  7650. bool HasArithmeticOrEnumeralCandidateType,
  7651. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  7652. OverloadCandidateSet &CandidateSet)
  7653. : S(S), Args(Args),
  7654. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  7655. HasArithmeticOrEnumeralCandidateType(
  7656. HasArithmeticOrEnumeralCandidateType),
  7657. CandidateTypes(CandidateTypes),
  7658. CandidateSet(CandidateSet) {
  7659. InitArithmeticTypes();
  7660. }
  7661. // Increment is deprecated for bool since C++17.
  7662. //
  7663. // C++ [over.built]p3:
  7664. //
  7665. // For every pair (T, VQ), where T is an arithmetic type other
  7666. // than bool, and VQ is either volatile or empty, there exist
  7667. // candidate operator functions of the form
  7668. //
  7669. // VQ T& operator++(VQ T&);
  7670. // T operator++(VQ T&, int);
  7671. //
  7672. // C++ [over.built]p4:
  7673. //
  7674. // For every pair (T, VQ), where T is an arithmetic type other
  7675. // than bool, and VQ is either volatile or empty, there exist
  7676. // candidate operator functions of the form
  7677. //
  7678. // VQ T& operator--(VQ T&);
  7679. // T operator--(VQ T&, int);
  7680. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  7681. if (!HasArithmeticOrEnumeralCandidateType)
  7682. return;
  7683. for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
  7684. const auto TypeOfT = ArithmeticTypes[Arith];
  7685. if (TypeOfT == S.Context.BoolTy) {
  7686. if (Op == OO_MinusMinus)
  7687. continue;
  7688. if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
  7689. continue;
  7690. }
  7691. addPlusPlusMinusMinusStyleOverloads(
  7692. TypeOfT,
  7693. VisibleTypeConversionsQuals.hasVolatile(),
  7694. VisibleTypeConversionsQuals.hasRestrict());
  7695. }
  7696. }
  7697. // C++ [over.built]p5:
  7698. //
  7699. // For every pair (T, VQ), where T is a cv-qualified or
  7700. // cv-unqualified object type, and VQ is either volatile or
  7701. // empty, there exist candidate operator functions of the form
  7702. //
  7703. // T*VQ& operator++(T*VQ&);
  7704. // T*VQ& operator--(T*VQ&);
  7705. // T* operator++(T*VQ&, int);
  7706. // T* operator--(T*VQ&, int);
  7707. void addPlusPlusMinusMinusPointerOverloads() {
  7708. for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
  7709. // Skip pointer types that aren't pointers to object types.
  7710. if (!PtrTy->getPointeeType()->isObjectType())
  7711. continue;
  7712. addPlusPlusMinusMinusStyleOverloads(
  7713. PtrTy,
  7714. (!PtrTy.isVolatileQualified() &&
  7715. VisibleTypeConversionsQuals.hasVolatile()),
  7716. (!PtrTy.isRestrictQualified() &&
  7717. VisibleTypeConversionsQuals.hasRestrict()));
  7718. }
  7719. }
  7720. // C++ [over.built]p6:
  7721. // For every cv-qualified or cv-unqualified object type T, there
  7722. // exist candidate operator functions of the form
  7723. //
  7724. // T& operator*(T*);
  7725. //
  7726. // C++ [over.built]p7:
  7727. // For every function type T that does not have cv-qualifiers or a
  7728. // ref-qualifier, there exist candidate operator functions of the form
  7729. // T& operator*(T*);
  7730. void addUnaryStarPointerOverloads() {
  7731. for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
  7732. QualType PointeeTy = ParamTy->getPointeeType();
  7733. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  7734. continue;
  7735. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  7736. if (Proto->getMethodQuals() || Proto->getRefQualifier())
  7737. continue;
  7738. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7739. }
  7740. }
  7741. // C++ [over.built]p9:
  7742. // For every promoted arithmetic type T, there exist candidate
  7743. // operator functions of the form
  7744. //
  7745. // T operator+(T);
  7746. // T operator-(T);
  7747. void addUnaryPlusOrMinusArithmeticOverloads() {
  7748. if (!HasArithmeticOrEnumeralCandidateType)
  7749. return;
  7750. for (unsigned Arith = FirstPromotedArithmeticType;
  7751. Arith < LastPromotedArithmeticType; ++Arith) {
  7752. QualType ArithTy = ArithmeticTypes[Arith];
  7753. S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
  7754. }
  7755. // Extension: We also add these operators for vector types.
  7756. for (QualType VecTy : CandidateTypes[0].vector_types())
  7757. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7758. }
  7759. // C++ [over.built]p8:
  7760. // For every type T, there exist candidate operator functions of
  7761. // the form
  7762. //
  7763. // T* operator+(T*);
  7764. void addUnaryPlusPointerOverloads() {
  7765. for (QualType ParamTy : CandidateTypes[0].pointer_types())
  7766. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7767. }
  7768. // C++ [over.built]p10:
  7769. // For every promoted integral type T, there exist candidate
  7770. // operator functions of the form
  7771. //
  7772. // T operator~(T);
  7773. void addUnaryTildePromotedIntegralOverloads() {
  7774. if (!HasArithmeticOrEnumeralCandidateType)
  7775. return;
  7776. for (unsigned Int = FirstPromotedIntegralType;
  7777. Int < LastPromotedIntegralType; ++Int) {
  7778. QualType IntTy = ArithmeticTypes[Int];
  7779. S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
  7780. }
  7781. // Extension: We also add this operator for vector types.
  7782. for (QualType VecTy : CandidateTypes[0].vector_types())
  7783. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7784. }
  7785. // C++ [over.match.oper]p16:
  7786. // For every pointer to member type T or type std::nullptr_t, there
  7787. // exist candidate operator functions of the form
  7788. //
  7789. // bool operator==(T,T);
  7790. // bool operator!=(T,T);
  7791. void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
  7792. /// Set of (canonical) types that we've already handled.
  7793. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7794. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7795. for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
  7796. // Don't add the same builtin candidate twice.
  7797. if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
  7798. continue;
  7799. QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
  7800. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7801. }
  7802. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  7803. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  7804. if (AddedTypes.insert(NullPtrTy).second) {
  7805. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  7806. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7807. }
  7808. }
  7809. }
  7810. }
  7811. // C++ [over.built]p15:
  7812. //
  7813. // For every T, where T is an enumeration type or a pointer type,
  7814. // there exist candidate operator functions of the form
  7815. //
  7816. // bool operator<(T, T);
  7817. // bool operator>(T, T);
  7818. // bool operator<=(T, T);
  7819. // bool operator>=(T, T);
  7820. // bool operator==(T, T);
  7821. // bool operator!=(T, T);
  7822. // R operator<=>(T, T)
  7823. void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
  7824. // C++ [over.match.oper]p3:
  7825. // [...]the built-in candidates include all of the candidate operator
  7826. // functions defined in 13.6 that, compared to the given operator, [...]
  7827. // do not have the same parameter-type-list as any non-template non-member
  7828. // candidate.
  7829. //
  7830. // Note that in practice, this only affects enumeration types because there
  7831. // aren't any built-in candidates of record type, and a user-defined operator
  7832. // must have an operand of record or enumeration type. Also, the only other
  7833. // overloaded operator with enumeration arguments, operator=,
  7834. // cannot be overloaded for enumeration types, so this is the only place
  7835. // where we must suppress candidates like this.
  7836. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  7837. UserDefinedBinaryOperators;
  7838. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7839. if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
  7840. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  7841. CEnd = CandidateSet.end();
  7842. C != CEnd; ++C) {
  7843. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  7844. continue;
  7845. if (C->Function->isFunctionTemplateSpecialization())
  7846. continue;
  7847. // We interpret "same parameter-type-list" as applying to the
  7848. // "synthesized candidate, with the order of the two parameters
  7849. // reversed", not to the original function.
  7850. bool Reversed = C->isReversed();
  7851. QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
  7852. ->getType()
  7853. .getUnqualifiedType();
  7854. QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
  7855. ->getType()
  7856. .getUnqualifiedType();
  7857. // Skip if either parameter isn't of enumeral type.
  7858. if (!FirstParamType->isEnumeralType() ||
  7859. !SecondParamType->isEnumeralType())
  7860. continue;
  7861. // Add this operator to the set of known user-defined operators.
  7862. UserDefinedBinaryOperators.insert(
  7863. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  7864. S.Context.getCanonicalType(SecondParamType)));
  7865. }
  7866. }
  7867. }
  7868. /// Set of (canonical) types that we've already handled.
  7869. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7870. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7871. for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
  7872. // Don't add the same builtin candidate twice.
  7873. if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
  7874. continue;
  7875. if (IsSpaceship && PtrTy->isFunctionPointerType())
  7876. continue;
  7877. QualType ParamTypes[2] = {PtrTy, PtrTy};
  7878. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7879. }
  7880. for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
  7881. CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
  7882. // Don't add the same builtin candidate twice, or if a user defined
  7883. // candidate exists.
  7884. if (!AddedTypes.insert(CanonType).second ||
  7885. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  7886. CanonType)))
  7887. continue;
  7888. QualType ParamTypes[2] = {EnumTy, EnumTy};
  7889. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7890. }
  7891. }
  7892. }
  7893. // C++ [over.built]p13:
  7894. //
  7895. // For every cv-qualified or cv-unqualified object type T
  7896. // there exist candidate operator functions of the form
  7897. //
  7898. // T* operator+(T*, ptrdiff_t);
  7899. // T& operator[](T*, ptrdiff_t); [BELOW]
  7900. // T* operator-(T*, ptrdiff_t);
  7901. // T* operator+(ptrdiff_t, T*);
  7902. // T& operator[](ptrdiff_t, T*); [BELOW]
  7903. //
  7904. // C++ [over.built]p14:
  7905. //
  7906. // For every T, where T is a pointer to object type, there
  7907. // exist candidate operator functions of the form
  7908. //
  7909. // ptrdiff_t operator-(T, T);
  7910. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  7911. /// Set of (canonical) types that we've already handled.
  7912. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7913. for (int Arg = 0; Arg < 2; ++Arg) {
  7914. QualType AsymmetricParamTypes[2] = {
  7915. S.Context.getPointerDiffType(),
  7916. S.Context.getPointerDiffType(),
  7917. };
  7918. for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
  7919. QualType PointeeTy = PtrTy->getPointeeType();
  7920. if (!PointeeTy->isObjectType())
  7921. continue;
  7922. AsymmetricParamTypes[Arg] = PtrTy;
  7923. if (Arg == 0 || Op == OO_Plus) {
  7924. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  7925. // T* operator+(ptrdiff_t, T*);
  7926. S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
  7927. }
  7928. if (Op == OO_Minus) {
  7929. // ptrdiff_t operator-(T, T);
  7930. if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
  7931. continue;
  7932. QualType ParamTypes[2] = {PtrTy, PtrTy};
  7933. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7934. }
  7935. }
  7936. }
  7937. }
  7938. // C++ [over.built]p12:
  7939. //
  7940. // For every pair of promoted arithmetic types L and R, there
  7941. // exist candidate operator functions of the form
  7942. //
  7943. // LR operator*(L, R);
  7944. // LR operator/(L, R);
  7945. // LR operator+(L, R);
  7946. // LR operator-(L, R);
  7947. // bool operator<(L, R);
  7948. // bool operator>(L, R);
  7949. // bool operator<=(L, R);
  7950. // bool operator>=(L, R);
  7951. // bool operator==(L, R);
  7952. // bool operator!=(L, R);
  7953. //
  7954. // where LR is the result of the usual arithmetic conversions
  7955. // between types L and R.
  7956. //
  7957. // C++ [over.built]p24:
  7958. //
  7959. // For every pair of promoted arithmetic types L and R, there exist
  7960. // candidate operator functions of the form
  7961. //
  7962. // LR operator?(bool, L, R);
  7963. //
  7964. // where LR is the result of the usual arithmetic conversions
  7965. // between types L and R.
  7966. // Our candidates ignore the first parameter.
  7967. void addGenericBinaryArithmeticOverloads() {
  7968. if (!HasArithmeticOrEnumeralCandidateType)
  7969. return;
  7970. for (unsigned Left = FirstPromotedArithmeticType;
  7971. Left < LastPromotedArithmeticType; ++Left) {
  7972. for (unsigned Right = FirstPromotedArithmeticType;
  7973. Right < LastPromotedArithmeticType; ++Right) {
  7974. QualType LandR[2] = { ArithmeticTypes[Left],
  7975. ArithmeticTypes[Right] };
  7976. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7977. }
  7978. }
  7979. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  7980. // conditional operator for vector types.
  7981. for (QualType Vec1Ty : CandidateTypes[0].vector_types())
  7982. for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
  7983. QualType LandR[2] = {Vec1Ty, Vec2Ty};
  7984. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7985. }
  7986. }
  7987. /// Add binary operator overloads for each candidate matrix type M1, M2:
  7988. /// * (M1, M1) -> M1
  7989. /// * (M1, M1.getElementType()) -> M1
  7990. /// * (M2.getElementType(), M2) -> M2
  7991. /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
  7992. void addMatrixBinaryArithmeticOverloads() {
  7993. if (!HasArithmeticOrEnumeralCandidateType)
  7994. return;
  7995. for (QualType M1 : CandidateTypes[0].matrix_types()) {
  7996. AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
  7997. AddCandidate(M1, M1);
  7998. }
  7999. for (QualType M2 : CandidateTypes[1].matrix_types()) {
  8000. AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
  8001. if (!CandidateTypes[0].containsMatrixType(M2))
  8002. AddCandidate(M2, M2);
  8003. }
  8004. }
  8005. // C++2a [over.built]p14:
  8006. //
  8007. // For every integral type T there exists a candidate operator function
  8008. // of the form
  8009. //
  8010. // std::strong_ordering operator<=>(T, T)
  8011. //
  8012. // C++2a [over.built]p15:
  8013. //
  8014. // For every pair of floating-point types L and R, there exists a candidate
  8015. // operator function of the form
  8016. //
  8017. // std::partial_ordering operator<=>(L, R);
  8018. //
  8019. // FIXME: The current specification for integral types doesn't play nice with
  8020. // the direction of p0946r0, which allows mixed integral and unscoped-enum
  8021. // comparisons. Under the current spec this can lead to ambiguity during
  8022. // overload resolution. For example:
  8023. //
  8024. // enum A : int {a};
  8025. // auto x = (a <=> (long)42);
  8026. //
  8027. // error: call is ambiguous for arguments 'A' and 'long'.
  8028. // note: candidate operator<=>(int, int)
  8029. // note: candidate operator<=>(long, long)
  8030. //
  8031. // To avoid this error, this function deviates from the specification and adds
  8032. // the mixed overloads `operator<=>(L, R)` where L and R are promoted
  8033. // arithmetic types (the same as the generic relational overloads).
  8034. //
  8035. // For now this function acts as a placeholder.
  8036. void addThreeWayArithmeticOverloads() {
  8037. addGenericBinaryArithmeticOverloads();
  8038. }
  8039. // C++ [over.built]p17:
  8040. //
  8041. // For every pair of promoted integral types L and R, there
  8042. // exist candidate operator functions of the form
  8043. //
  8044. // LR operator%(L, R);
  8045. // LR operator&(L, R);
  8046. // LR operator^(L, R);
  8047. // LR operator|(L, R);
  8048. // L operator<<(L, R);
  8049. // L operator>>(L, R);
  8050. //
  8051. // where LR is the result of the usual arithmetic conversions
  8052. // between types L and R.
  8053. void addBinaryBitwiseArithmeticOverloads() {
  8054. if (!HasArithmeticOrEnumeralCandidateType)
  8055. return;
  8056. for (unsigned Left = FirstPromotedIntegralType;
  8057. Left < LastPromotedIntegralType; ++Left) {
  8058. for (unsigned Right = FirstPromotedIntegralType;
  8059. Right < LastPromotedIntegralType; ++Right) {
  8060. QualType LandR[2] = { ArithmeticTypes[Left],
  8061. ArithmeticTypes[Right] };
  8062. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  8063. }
  8064. }
  8065. }
  8066. // C++ [over.built]p20:
  8067. //
  8068. // For every pair (T, VQ), where T is an enumeration or
  8069. // pointer to member type and VQ is either volatile or
  8070. // empty, there exist candidate operator functions of the form
  8071. //
  8072. // VQ T& operator=(VQ T&, T);
  8073. void addAssignmentMemberPointerOrEnumeralOverloads() {
  8074. /// Set of (canonical) types that we've already handled.
  8075. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  8076. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  8077. for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
  8078. if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
  8079. continue;
  8080. AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
  8081. }
  8082. for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
  8083. if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
  8084. continue;
  8085. AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
  8086. }
  8087. }
  8088. }
  8089. // C++ [over.built]p19:
  8090. //
  8091. // For every pair (T, VQ), where T is any type and VQ is either
  8092. // volatile or empty, there exist candidate operator functions
  8093. // of the form
  8094. //
  8095. // T*VQ& operator=(T*VQ&, T*);
  8096. //
  8097. // C++ [over.built]p21:
  8098. //
  8099. // For every pair (T, VQ), where T is a cv-qualified or
  8100. // cv-unqualified object type and VQ is either volatile or
  8101. // empty, there exist candidate operator functions of the form
  8102. //
  8103. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  8104. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  8105. void addAssignmentPointerOverloads(bool isEqualOp) {
  8106. /// Set of (canonical) types that we've already handled.
  8107. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  8108. for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
  8109. // If this is operator=, keep track of the builtin candidates we added.
  8110. if (isEqualOp)
  8111. AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
  8112. else if (!PtrTy->getPointeeType()->isObjectType())
  8113. continue;
  8114. // non-volatile version
  8115. QualType ParamTypes[2] = {
  8116. S.Context.getLValueReferenceType(PtrTy),
  8117. isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
  8118. };
  8119. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8120. /*IsAssignmentOperator=*/ isEqualOp);
  8121. bool NeedVolatile = !PtrTy.isVolatileQualified() &&
  8122. VisibleTypeConversionsQuals.hasVolatile();
  8123. if (NeedVolatile) {
  8124. // volatile version
  8125. ParamTypes[0] =
  8126. S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
  8127. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8128. /*IsAssignmentOperator=*/isEqualOp);
  8129. }
  8130. if (!PtrTy.isRestrictQualified() &&
  8131. VisibleTypeConversionsQuals.hasRestrict()) {
  8132. // restrict version
  8133. ParamTypes[0] =
  8134. S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
  8135. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8136. /*IsAssignmentOperator=*/isEqualOp);
  8137. if (NeedVolatile) {
  8138. // volatile restrict version
  8139. ParamTypes[0] =
  8140. S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
  8141. PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
  8142. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8143. /*IsAssignmentOperator=*/isEqualOp);
  8144. }
  8145. }
  8146. }
  8147. if (isEqualOp) {
  8148. for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
  8149. // Make sure we don't add the same candidate twice.
  8150. if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
  8151. continue;
  8152. QualType ParamTypes[2] = {
  8153. S.Context.getLValueReferenceType(PtrTy),
  8154. PtrTy,
  8155. };
  8156. // non-volatile version
  8157. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8158. /*IsAssignmentOperator=*/true);
  8159. bool NeedVolatile = !PtrTy.isVolatileQualified() &&
  8160. VisibleTypeConversionsQuals.hasVolatile();
  8161. if (NeedVolatile) {
  8162. // volatile version
  8163. ParamTypes[0] = S.Context.getLValueReferenceType(
  8164. S.Context.getVolatileType(PtrTy));
  8165. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8166. /*IsAssignmentOperator=*/true);
  8167. }
  8168. if (!PtrTy.isRestrictQualified() &&
  8169. VisibleTypeConversionsQuals.hasRestrict()) {
  8170. // restrict version
  8171. ParamTypes[0] = S.Context.getLValueReferenceType(
  8172. S.Context.getRestrictType(PtrTy));
  8173. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8174. /*IsAssignmentOperator=*/true);
  8175. if (NeedVolatile) {
  8176. // volatile restrict version
  8177. ParamTypes[0] =
  8178. S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
  8179. PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
  8180. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8181. /*IsAssignmentOperator=*/true);
  8182. }
  8183. }
  8184. }
  8185. }
  8186. }
  8187. // C++ [over.built]p18:
  8188. //
  8189. // For every triple (L, VQ, R), where L is an arithmetic type,
  8190. // VQ is either volatile or empty, and R is a promoted
  8191. // arithmetic type, there exist candidate operator functions of
  8192. // the form
  8193. //
  8194. // VQ L& operator=(VQ L&, R);
  8195. // VQ L& operator*=(VQ L&, R);
  8196. // VQ L& operator/=(VQ L&, R);
  8197. // VQ L& operator+=(VQ L&, R);
  8198. // VQ L& operator-=(VQ L&, R);
  8199. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  8200. if (!HasArithmeticOrEnumeralCandidateType)
  8201. return;
  8202. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  8203. for (unsigned Right = FirstPromotedArithmeticType;
  8204. Right < LastPromotedArithmeticType; ++Right) {
  8205. QualType ParamTypes[2];
  8206. ParamTypes[1] = ArithmeticTypes[Right];
  8207. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  8208. S, ArithmeticTypes[Left], Args[0]);
  8209. forAllQualifierCombinations(
  8210. VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
  8211. ParamTypes[0] =
  8212. makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
  8213. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8214. /*IsAssignmentOperator=*/isEqualOp);
  8215. });
  8216. }
  8217. }
  8218. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  8219. for (QualType Vec1Ty : CandidateTypes[0].vector_types())
  8220. for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
  8221. QualType ParamTypes[2];
  8222. ParamTypes[1] = Vec2Ty;
  8223. // Add this built-in operator as a candidate (VQ is empty).
  8224. ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
  8225. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8226. /*IsAssignmentOperator=*/isEqualOp);
  8227. // Add this built-in operator as a candidate (VQ is 'volatile').
  8228. if (VisibleTypeConversionsQuals.hasVolatile()) {
  8229. ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
  8230. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  8231. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8232. /*IsAssignmentOperator=*/isEqualOp);
  8233. }
  8234. }
  8235. }
  8236. // C++ [over.built]p22:
  8237. //
  8238. // For every triple (L, VQ, R), where L is an integral type, VQ
  8239. // is either volatile or empty, and R is a promoted integral
  8240. // type, there exist candidate operator functions of the form
  8241. //
  8242. // VQ L& operator%=(VQ L&, R);
  8243. // VQ L& operator<<=(VQ L&, R);
  8244. // VQ L& operator>>=(VQ L&, R);
  8245. // VQ L& operator&=(VQ L&, R);
  8246. // VQ L& operator^=(VQ L&, R);
  8247. // VQ L& operator|=(VQ L&, R);
  8248. void addAssignmentIntegralOverloads() {
  8249. if (!HasArithmeticOrEnumeralCandidateType)
  8250. return;
  8251. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  8252. for (unsigned Right = FirstPromotedIntegralType;
  8253. Right < LastPromotedIntegralType; ++Right) {
  8254. QualType ParamTypes[2];
  8255. ParamTypes[1] = ArithmeticTypes[Right];
  8256. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  8257. S, ArithmeticTypes[Left], Args[0]);
  8258. forAllQualifierCombinations(
  8259. VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
  8260. ParamTypes[0] =
  8261. makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
  8262. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8263. });
  8264. }
  8265. }
  8266. }
  8267. // C++ [over.operator]p23:
  8268. //
  8269. // There also exist candidate operator functions of the form
  8270. //
  8271. // bool operator!(bool);
  8272. // bool operator&&(bool, bool);
  8273. // bool operator||(bool, bool);
  8274. void addExclaimOverload() {
  8275. QualType ParamTy = S.Context.BoolTy;
  8276. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
  8277. /*IsAssignmentOperator=*/false,
  8278. /*NumContextualBoolArguments=*/1);
  8279. }
  8280. void addAmpAmpOrPipePipeOverload() {
  8281. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  8282. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  8283. /*IsAssignmentOperator=*/false,
  8284. /*NumContextualBoolArguments=*/2);
  8285. }
  8286. // C++ [over.built]p13:
  8287. //
  8288. // For every cv-qualified or cv-unqualified object type T there
  8289. // exist candidate operator functions of the form
  8290. //
  8291. // T* operator+(T*, ptrdiff_t); [ABOVE]
  8292. // T& operator[](T*, ptrdiff_t);
  8293. // T* operator-(T*, ptrdiff_t); [ABOVE]
  8294. // T* operator+(ptrdiff_t, T*); [ABOVE]
  8295. // T& operator[](ptrdiff_t, T*);
  8296. void addSubscriptOverloads() {
  8297. for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
  8298. QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
  8299. QualType PointeeType = PtrTy->getPointeeType();
  8300. if (!PointeeType->isObjectType())
  8301. continue;
  8302. // T& operator[](T*, ptrdiff_t)
  8303. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8304. }
  8305. for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
  8306. QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
  8307. QualType PointeeType = PtrTy->getPointeeType();
  8308. if (!PointeeType->isObjectType())
  8309. continue;
  8310. // T& operator[](ptrdiff_t, T*)
  8311. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8312. }
  8313. }
  8314. // C++ [over.built]p11:
  8315. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  8316. // C1 is the same type as C2 or is a derived class of C2, T is an object
  8317. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  8318. // there exist candidate operator functions of the form
  8319. //
  8320. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  8321. //
  8322. // where CV12 is the union of CV1 and CV2.
  8323. void addArrowStarOverloads() {
  8324. for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
  8325. QualType C1Ty = PtrTy;
  8326. QualType C1;
  8327. QualifierCollector Q1;
  8328. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  8329. if (!isa<RecordType>(C1))
  8330. continue;
  8331. // heuristic to reduce number of builtin candidates in the set.
  8332. // Add volatile/restrict version only if there are conversions to a
  8333. // volatile/restrict type.
  8334. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  8335. continue;
  8336. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  8337. continue;
  8338. for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
  8339. const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
  8340. QualType C2 = QualType(mptr->getClass(), 0);
  8341. C2 = C2.getUnqualifiedType();
  8342. if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
  8343. break;
  8344. QualType ParamTypes[2] = {PtrTy, MemPtrTy};
  8345. // build CV12 T&
  8346. QualType T = mptr->getPointeeType();
  8347. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  8348. T.isVolatileQualified())
  8349. continue;
  8350. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  8351. T.isRestrictQualified())
  8352. continue;
  8353. T = Q1.apply(S.Context, T);
  8354. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8355. }
  8356. }
  8357. }
  8358. // Note that we don't consider the first argument, since it has been
  8359. // contextually converted to bool long ago. The candidates below are
  8360. // therefore added as binary.
  8361. //
  8362. // C++ [over.built]p25:
  8363. // For every type T, where T is a pointer, pointer-to-member, or scoped
  8364. // enumeration type, there exist candidate operator functions of the form
  8365. //
  8366. // T operator?(bool, T, T);
  8367. //
  8368. void addConditionalOperatorOverloads() {
  8369. /// Set of (canonical) types that we've already handled.
  8370. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  8371. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  8372. for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
  8373. if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
  8374. continue;
  8375. QualType ParamTypes[2] = {PtrTy, PtrTy};
  8376. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8377. }
  8378. for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
  8379. if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
  8380. continue;
  8381. QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
  8382. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8383. }
  8384. if (S.getLangOpts().CPlusPlus11) {
  8385. for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
  8386. if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
  8387. continue;
  8388. if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
  8389. continue;
  8390. QualType ParamTypes[2] = {EnumTy, EnumTy};
  8391. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  8392. }
  8393. }
  8394. }
  8395. }
  8396. };
  8397. } // end anonymous namespace
  8398. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  8399. /// operator overloads to the candidate set (C++ [over.built]), based
  8400. /// on the operator @p Op and the arguments given. For example, if the
  8401. /// operator is a binary '+', this routine might add "int
  8402. /// operator+(int, int)" to cover integer addition.
  8403. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  8404. SourceLocation OpLoc,
  8405. ArrayRef<Expr *> Args,
  8406. OverloadCandidateSet &CandidateSet) {
  8407. // Find all of the types that the arguments can convert to, but only
  8408. // if the operator we're looking at has built-in operator candidates
  8409. // that make use of these types. Also record whether we encounter non-record
  8410. // candidate types or either arithmetic or enumeral candidate types.
  8411. QualifiersAndAtomic VisibleTypeConversionsQuals;
  8412. VisibleTypeConversionsQuals.addConst();
  8413. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  8414. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  8415. if (Args[ArgIdx]->getType()->isAtomicType())
  8416. VisibleTypeConversionsQuals.addAtomic();
  8417. }
  8418. bool HasNonRecordCandidateType = false;
  8419. bool HasArithmeticOrEnumeralCandidateType = false;
  8420. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  8421. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  8422. CandidateTypes.emplace_back(*this);
  8423. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  8424. OpLoc,
  8425. true,
  8426. (Op == OO_Exclaim ||
  8427. Op == OO_AmpAmp ||
  8428. Op == OO_PipePipe),
  8429. VisibleTypeConversionsQuals);
  8430. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  8431. CandidateTypes[ArgIdx].hasNonRecordTypes();
  8432. HasArithmeticOrEnumeralCandidateType =
  8433. HasArithmeticOrEnumeralCandidateType ||
  8434. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  8435. }
  8436. // Exit early when no non-record types have been added to the candidate set
  8437. // for any of the arguments to the operator.
  8438. //
  8439. // We can't exit early for !, ||, or &&, since there we have always have
  8440. // 'bool' overloads.
  8441. if (!HasNonRecordCandidateType &&
  8442. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  8443. return;
  8444. // Setup an object to manage the common state for building overloads.
  8445. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  8446. VisibleTypeConversionsQuals,
  8447. HasArithmeticOrEnumeralCandidateType,
  8448. CandidateTypes, CandidateSet);
  8449. // Dispatch over the operation to add in only those overloads which apply.
  8450. switch (Op) {
  8451. case OO_None:
  8452. case NUM_OVERLOADED_OPERATORS:
  8453. llvm_unreachable("Expected an overloaded operator");
  8454. case OO_New:
  8455. case OO_Delete:
  8456. case OO_Array_New:
  8457. case OO_Array_Delete:
  8458. case OO_Call:
  8459. llvm_unreachable(
  8460. "Special operators don't use AddBuiltinOperatorCandidates");
  8461. case OO_Comma:
  8462. case OO_Arrow:
  8463. case OO_Coawait:
  8464. // C++ [over.match.oper]p3:
  8465. // -- For the operator ',', the unary operator '&', the
  8466. // operator '->', or the operator 'co_await', the
  8467. // built-in candidates set is empty.
  8468. break;
  8469. case OO_Plus: // '+' is either unary or binary
  8470. if (Args.size() == 1)
  8471. OpBuilder.addUnaryPlusPointerOverloads();
  8472. [[fallthrough]];
  8473. case OO_Minus: // '-' is either unary or binary
  8474. if (Args.size() == 1) {
  8475. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  8476. } else {
  8477. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  8478. OpBuilder.addGenericBinaryArithmeticOverloads();
  8479. OpBuilder.addMatrixBinaryArithmeticOverloads();
  8480. }
  8481. break;
  8482. case OO_Star: // '*' is either unary or binary
  8483. if (Args.size() == 1)
  8484. OpBuilder.addUnaryStarPointerOverloads();
  8485. else {
  8486. OpBuilder.addGenericBinaryArithmeticOverloads();
  8487. OpBuilder.addMatrixBinaryArithmeticOverloads();
  8488. }
  8489. break;
  8490. case OO_Slash:
  8491. OpBuilder.addGenericBinaryArithmeticOverloads();
  8492. break;
  8493. case OO_PlusPlus:
  8494. case OO_MinusMinus:
  8495. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  8496. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  8497. break;
  8498. case OO_EqualEqual:
  8499. case OO_ExclaimEqual:
  8500. OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
  8501. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
  8502. OpBuilder.addGenericBinaryArithmeticOverloads();
  8503. break;
  8504. case OO_Less:
  8505. case OO_Greater:
  8506. case OO_LessEqual:
  8507. case OO_GreaterEqual:
  8508. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
  8509. OpBuilder.addGenericBinaryArithmeticOverloads();
  8510. break;
  8511. case OO_Spaceship:
  8512. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
  8513. OpBuilder.addThreeWayArithmeticOverloads();
  8514. break;
  8515. case OO_Percent:
  8516. case OO_Caret:
  8517. case OO_Pipe:
  8518. case OO_LessLess:
  8519. case OO_GreaterGreater:
  8520. OpBuilder.addBinaryBitwiseArithmeticOverloads();
  8521. break;
  8522. case OO_Amp: // '&' is either unary or binary
  8523. if (Args.size() == 1)
  8524. // C++ [over.match.oper]p3:
  8525. // -- For the operator ',', the unary operator '&', or the
  8526. // operator '->', the built-in candidates set is empty.
  8527. break;
  8528. OpBuilder.addBinaryBitwiseArithmeticOverloads();
  8529. break;
  8530. case OO_Tilde:
  8531. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  8532. break;
  8533. case OO_Equal:
  8534. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  8535. [[fallthrough]];
  8536. case OO_PlusEqual:
  8537. case OO_MinusEqual:
  8538. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  8539. [[fallthrough]];
  8540. case OO_StarEqual:
  8541. case OO_SlashEqual:
  8542. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  8543. break;
  8544. case OO_PercentEqual:
  8545. case OO_LessLessEqual:
  8546. case OO_GreaterGreaterEqual:
  8547. case OO_AmpEqual:
  8548. case OO_CaretEqual:
  8549. case OO_PipeEqual:
  8550. OpBuilder.addAssignmentIntegralOverloads();
  8551. break;
  8552. case OO_Exclaim:
  8553. OpBuilder.addExclaimOverload();
  8554. break;
  8555. case OO_AmpAmp:
  8556. case OO_PipePipe:
  8557. OpBuilder.addAmpAmpOrPipePipeOverload();
  8558. break;
  8559. case OO_Subscript:
  8560. if (Args.size() == 2)
  8561. OpBuilder.addSubscriptOverloads();
  8562. break;
  8563. case OO_ArrowStar:
  8564. OpBuilder.addArrowStarOverloads();
  8565. break;
  8566. case OO_Conditional:
  8567. OpBuilder.addConditionalOperatorOverloads();
  8568. OpBuilder.addGenericBinaryArithmeticOverloads();
  8569. break;
  8570. }
  8571. }
  8572. /// Add function candidates found via argument-dependent lookup
  8573. /// to the set of overloading candidates.
  8574. ///
  8575. /// This routine performs argument-dependent name lookup based on the
  8576. /// given function name (which may also be an operator name) and adds
  8577. /// all of the overload candidates found by ADL to the overload
  8578. /// candidate set (C++ [basic.lookup.argdep]).
  8579. void
  8580. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  8581. SourceLocation Loc,
  8582. ArrayRef<Expr *> Args,
  8583. TemplateArgumentListInfo *ExplicitTemplateArgs,
  8584. OverloadCandidateSet& CandidateSet,
  8585. bool PartialOverloading) {
  8586. ADLResult Fns;
  8587. // FIXME: This approach for uniquing ADL results (and removing
  8588. // redundant candidates from the set) relies on pointer-equality,
  8589. // which means we need to key off the canonical decl. However,
  8590. // always going back to the canonical decl might not get us the
  8591. // right set of default arguments. What default arguments are
  8592. // we supposed to consider on ADL candidates, anyway?
  8593. // FIXME: Pass in the explicit template arguments?
  8594. ArgumentDependentLookup(Name, Loc, Args, Fns);
  8595. // Erase all of the candidates we already knew about.
  8596. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  8597. CandEnd = CandidateSet.end();
  8598. Cand != CandEnd; ++Cand)
  8599. if (Cand->Function) {
  8600. Fns.erase(Cand->Function);
  8601. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  8602. Fns.erase(FunTmpl);
  8603. }
  8604. // For each of the ADL candidates we found, add it to the overload
  8605. // set.
  8606. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  8607. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  8608. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  8609. if (ExplicitTemplateArgs)
  8610. continue;
  8611. AddOverloadCandidate(
  8612. FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
  8613. PartialOverloading, /*AllowExplicit=*/true,
  8614. /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
  8615. if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
  8616. AddOverloadCandidate(
  8617. FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
  8618. /*SuppressUserConversions=*/false, PartialOverloading,
  8619. /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
  8620. ADLCallKind::UsesADL, std::nullopt,
  8621. OverloadCandidateParamOrder::Reversed);
  8622. }
  8623. } else {
  8624. auto *FTD = cast<FunctionTemplateDecl>(*I);
  8625. AddTemplateOverloadCandidate(
  8626. FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
  8627. /*SuppressUserConversions=*/false, PartialOverloading,
  8628. /*AllowExplicit=*/true, ADLCallKind::UsesADL);
  8629. if (CandidateSet.getRewriteInfo().shouldAddReversed(
  8630. *this, Args, FTD->getTemplatedDecl())) {
  8631. AddTemplateOverloadCandidate(
  8632. FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
  8633. CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
  8634. /*AllowExplicit=*/true, ADLCallKind::UsesADL,
  8635. OverloadCandidateParamOrder::Reversed);
  8636. }
  8637. }
  8638. }
  8639. }
  8640. namespace {
  8641. enum class Comparison { Equal, Better, Worse };
  8642. }
  8643. /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
  8644. /// overload resolution.
  8645. ///
  8646. /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
  8647. /// Cand1's first N enable_if attributes have precisely the same conditions as
  8648. /// Cand2's first N enable_if attributes (where N = the number of enable_if
  8649. /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
  8650. ///
  8651. /// Note that you can have a pair of candidates such that Cand1's enable_if
  8652. /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
  8653. /// worse than Cand1's.
  8654. static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
  8655. const FunctionDecl *Cand2) {
  8656. // Common case: One (or both) decls don't have enable_if attrs.
  8657. bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
  8658. bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
  8659. if (!Cand1Attr || !Cand2Attr) {
  8660. if (Cand1Attr == Cand2Attr)
  8661. return Comparison::Equal;
  8662. return Cand1Attr ? Comparison::Better : Comparison::Worse;
  8663. }
  8664. auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
  8665. auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
  8666. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  8667. for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
  8668. std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  8669. std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  8670. // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
  8671. // has fewer enable_if attributes than Cand2, and vice versa.
  8672. if (!Cand1A)
  8673. return Comparison::Worse;
  8674. if (!Cand2A)
  8675. return Comparison::Better;
  8676. Cand1ID.clear();
  8677. Cand2ID.clear();
  8678. (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
  8679. (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
  8680. if (Cand1ID != Cand2ID)
  8681. return Comparison::Worse;
  8682. }
  8683. return Comparison::Equal;
  8684. }
  8685. static Comparison
  8686. isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
  8687. const OverloadCandidate &Cand2) {
  8688. if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
  8689. !Cand2.Function->isMultiVersion())
  8690. return Comparison::Equal;
  8691. // If both are invalid, they are equal. If one of them is invalid, the other
  8692. // is better.
  8693. if (Cand1.Function->isInvalidDecl()) {
  8694. if (Cand2.Function->isInvalidDecl())
  8695. return Comparison::Equal;
  8696. return Comparison::Worse;
  8697. }
  8698. if (Cand2.Function->isInvalidDecl())
  8699. return Comparison::Better;
  8700. // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
  8701. // cpu_dispatch, else arbitrarily based on the identifiers.
  8702. bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
  8703. bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
  8704. const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
  8705. const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
  8706. if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
  8707. return Comparison::Equal;
  8708. if (Cand1CPUDisp && !Cand2CPUDisp)
  8709. return Comparison::Better;
  8710. if (Cand2CPUDisp && !Cand1CPUDisp)
  8711. return Comparison::Worse;
  8712. if (Cand1CPUSpec && Cand2CPUSpec) {
  8713. if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
  8714. return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
  8715. ? Comparison::Better
  8716. : Comparison::Worse;
  8717. std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
  8718. FirstDiff = std::mismatch(
  8719. Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
  8720. Cand2CPUSpec->cpus_begin(),
  8721. [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
  8722. return LHS->getName() == RHS->getName();
  8723. });
  8724. assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
  8725. "Two different cpu-specific versions should not have the same "
  8726. "identifier list, otherwise they'd be the same decl!");
  8727. return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
  8728. ? Comparison::Better
  8729. : Comparison::Worse;
  8730. }
  8731. llvm_unreachable("No way to get here unless both had cpu_dispatch");
  8732. }
  8733. /// Compute the type of the implicit object parameter for the given function,
  8734. /// if any. Returns std::nullopt if there is no implicit object parameter, and a
  8735. /// null QualType if there is a 'matches anything' implicit object parameter.
  8736. static std::optional<QualType>
  8737. getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
  8738. if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
  8739. return std::nullopt;
  8740. auto *M = cast<CXXMethodDecl>(F);
  8741. // Static member functions' object parameters match all types.
  8742. if (M->isStatic())
  8743. return QualType();
  8744. QualType T = M->getThisObjectType();
  8745. if (M->getRefQualifier() == RQ_RValue)
  8746. return Context.getRValueReferenceType(T);
  8747. return Context.getLValueReferenceType(T);
  8748. }
  8749. static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
  8750. const FunctionDecl *F2, unsigned NumParams) {
  8751. if (declaresSameEntity(F1, F2))
  8752. return true;
  8753. auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
  8754. if (First) {
  8755. if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
  8756. return *T;
  8757. }
  8758. assert(I < F->getNumParams());
  8759. return F->getParamDecl(I++)->getType();
  8760. };
  8761. unsigned I1 = 0, I2 = 0;
  8762. for (unsigned I = 0; I != NumParams; ++I) {
  8763. QualType T1 = NextParam(F1, I1, I == 0);
  8764. QualType T2 = NextParam(F2, I2, I == 0);
  8765. assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
  8766. if (!Context.hasSameUnqualifiedType(T1, T2))
  8767. return false;
  8768. }
  8769. return true;
  8770. }
  8771. /// We're allowed to use constraints partial ordering only if the candidates
  8772. /// have the same parameter types:
  8773. /// [over.match.best]p2.6
  8774. /// F1 and F2 are non-template functions with the same parameter-type-lists,
  8775. /// and F1 is more constrained than F2 [...]
  8776. static bool sameFunctionParameterTypeLists(Sema &S,
  8777. const OverloadCandidate &Cand1,
  8778. const OverloadCandidate &Cand2) {
  8779. if (Cand1.Function && Cand2.Function) {
  8780. auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
  8781. auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
  8782. if (PT1->getNumParams() == PT2->getNumParams() &&
  8783. PT1->isVariadic() == PT2->isVariadic() &&
  8784. S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
  8785. Cand1.isReversed() ^ Cand2.isReversed()))
  8786. return true;
  8787. }
  8788. return false;
  8789. }
  8790. /// isBetterOverloadCandidate - Determines whether the first overload
  8791. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  8792. bool clang::isBetterOverloadCandidate(
  8793. Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
  8794. SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
  8795. // Define viable functions to be better candidates than non-viable
  8796. // functions.
  8797. if (!Cand2.Viable)
  8798. return Cand1.Viable;
  8799. else if (!Cand1.Viable)
  8800. return false;
  8801. // [CUDA] A function with 'never' preference is marked not viable, therefore
  8802. // is never shown up here. The worst preference shown up here is 'wrong side',
  8803. // e.g. an H function called by a HD function in device compilation. This is
  8804. // valid AST as long as the HD function is not emitted, e.g. it is an inline
  8805. // function which is called only by an H function. A deferred diagnostic will
  8806. // be triggered if it is emitted. However a wrong-sided function is still
  8807. // a viable candidate here.
  8808. //
  8809. // If Cand1 can be emitted and Cand2 cannot be emitted in the current
  8810. // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
  8811. // can be emitted, Cand1 is not better than Cand2. This rule should have
  8812. // precedence over other rules.
  8813. //
  8814. // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
  8815. // other rules should be used to determine which is better. This is because
  8816. // host/device based overloading resolution is mostly for determining
  8817. // viability of a function. If two functions are both viable, other factors
  8818. // should take precedence in preference, e.g. the standard-defined preferences
  8819. // like argument conversion ranks or enable_if partial-ordering. The
  8820. // preference for pass-object-size parameters is probably most similar to a
  8821. // type-based-overloading decision and so should take priority.
  8822. //
  8823. // If other rules cannot determine which is better, CUDA preference will be
  8824. // used again to determine which is better.
  8825. //
  8826. // TODO: Currently IdentifyCUDAPreference does not return correct values
  8827. // for functions called in global variable initializers due to missing
  8828. // correct context about device/host. Therefore we can only enforce this
  8829. // rule when there is a caller. We should enforce this rule for functions
  8830. // in global variable initializers once proper context is added.
  8831. //
  8832. // TODO: We can only enable the hostness based overloading resolution when
  8833. // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
  8834. // overloading resolution diagnostics.
  8835. if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
  8836. S.getLangOpts().GPUExcludeWrongSideOverloads) {
  8837. if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
  8838. bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
  8839. bool IsCand1ImplicitHD =
  8840. Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
  8841. bool IsCand2ImplicitHD =
  8842. Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
  8843. auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
  8844. auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
  8845. assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
  8846. // The implicit HD function may be a function in a system header which
  8847. // is forced by pragma. In device compilation, if we prefer HD candidates
  8848. // over wrong-sided candidates, overloading resolution may change, which
  8849. // may result in non-deferrable diagnostics. As a workaround, we let
  8850. // implicit HD candidates take equal preference as wrong-sided candidates.
  8851. // This will preserve the overloading resolution.
  8852. // TODO: We still need special handling of implicit HD functions since
  8853. // they may incur other diagnostics to be deferred. We should make all
  8854. // host/device related diagnostics deferrable and remove special handling
  8855. // of implicit HD functions.
  8856. auto EmitThreshold =
  8857. (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
  8858. (IsCand1ImplicitHD || IsCand2ImplicitHD))
  8859. ? Sema::CFP_Never
  8860. : Sema::CFP_WrongSide;
  8861. auto Cand1Emittable = P1 > EmitThreshold;
  8862. auto Cand2Emittable = P2 > EmitThreshold;
  8863. if (Cand1Emittable && !Cand2Emittable)
  8864. return true;
  8865. if (!Cand1Emittable && Cand2Emittable)
  8866. return false;
  8867. }
  8868. }
  8869. // C++ [over.match.best]p1: (Changed in C++2b)
  8870. //
  8871. // -- if F is a static member function, ICS1(F) is defined such
  8872. // that ICS1(F) is neither better nor worse than ICS1(G) for
  8873. // any function G, and, symmetrically, ICS1(G) is neither
  8874. // better nor worse than ICS1(F).
  8875. unsigned StartArg = 0;
  8876. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  8877. StartArg = 1;
  8878. auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
  8879. // We don't allow incompatible pointer conversions in C++.
  8880. if (!S.getLangOpts().CPlusPlus)
  8881. return ICS.isStandard() &&
  8882. ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
  8883. // The only ill-formed conversion we allow in C++ is the string literal to
  8884. // char* conversion, which is only considered ill-formed after C++11.
  8885. return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  8886. hasDeprecatedStringLiteralToCharPtrConversion(ICS);
  8887. };
  8888. // Define functions that don't require ill-formed conversions for a given
  8889. // argument to be better candidates than functions that do.
  8890. unsigned NumArgs = Cand1.Conversions.size();
  8891. assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
  8892. bool HasBetterConversion = false;
  8893. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8894. bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
  8895. bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
  8896. if (Cand1Bad != Cand2Bad) {
  8897. if (Cand1Bad)
  8898. return false;
  8899. HasBetterConversion = true;
  8900. }
  8901. }
  8902. if (HasBetterConversion)
  8903. return true;
  8904. // C++ [over.match.best]p1:
  8905. // A viable function F1 is defined to be a better function than another
  8906. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  8907. // conversion sequence than ICSi(F2), and then...
  8908. bool HasWorseConversion = false;
  8909. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8910. switch (CompareImplicitConversionSequences(S, Loc,
  8911. Cand1.Conversions[ArgIdx],
  8912. Cand2.Conversions[ArgIdx])) {
  8913. case ImplicitConversionSequence::Better:
  8914. // Cand1 has a better conversion sequence.
  8915. HasBetterConversion = true;
  8916. break;
  8917. case ImplicitConversionSequence::Worse:
  8918. if (Cand1.Function && Cand2.Function &&
  8919. Cand1.isReversed() != Cand2.isReversed() &&
  8920. haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
  8921. NumArgs)) {
  8922. // Work around large-scale breakage caused by considering reversed
  8923. // forms of operator== in C++20:
  8924. //
  8925. // When comparing a function against a reversed function with the same
  8926. // parameter types, if we have a better conversion for one argument and
  8927. // a worse conversion for the other, the implicit conversion sequences
  8928. // are treated as being equally good.
  8929. //
  8930. // This prevents a comparison function from being considered ambiguous
  8931. // with a reversed form that is written in the same way.
  8932. //
  8933. // We diagnose this as an extension from CreateOverloadedBinOp.
  8934. HasWorseConversion = true;
  8935. break;
  8936. }
  8937. // Cand1 can't be better than Cand2.
  8938. return false;
  8939. case ImplicitConversionSequence::Indistinguishable:
  8940. // Do nothing.
  8941. break;
  8942. }
  8943. }
  8944. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  8945. // ICSj(F2), or, if not that,
  8946. if (HasBetterConversion && !HasWorseConversion)
  8947. return true;
  8948. // -- the context is an initialization by user-defined conversion
  8949. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  8950. // from the return type of F1 to the destination type (i.e.,
  8951. // the type of the entity being initialized) is a better
  8952. // conversion sequence than the standard conversion sequence
  8953. // from the return type of F2 to the destination type.
  8954. if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
  8955. Cand1.Function && Cand2.Function &&
  8956. isa<CXXConversionDecl>(Cand1.Function) &&
  8957. isa<CXXConversionDecl>(Cand2.Function)) {
  8958. // First check whether we prefer one of the conversion functions over the
  8959. // other. This only distinguishes the results in non-standard, extension
  8960. // cases such as the conversion from a lambda closure type to a function
  8961. // pointer or block.
  8962. ImplicitConversionSequence::CompareKind Result =
  8963. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  8964. if (Result == ImplicitConversionSequence::Indistinguishable)
  8965. Result = CompareStandardConversionSequences(S, Loc,
  8966. Cand1.FinalConversion,
  8967. Cand2.FinalConversion);
  8968. if (Result != ImplicitConversionSequence::Indistinguishable)
  8969. return Result == ImplicitConversionSequence::Better;
  8970. // FIXME: Compare kind of reference binding if conversion functions
  8971. // convert to a reference type used in direct reference binding, per
  8972. // C++14 [over.match.best]p1 section 2 bullet 3.
  8973. }
  8974. // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
  8975. // as combined with the resolution to CWG issue 243.
  8976. //
  8977. // When the context is initialization by constructor ([over.match.ctor] or
  8978. // either phase of [over.match.list]), a constructor is preferred over
  8979. // a conversion function.
  8980. if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
  8981. Cand1.Function && Cand2.Function &&
  8982. isa<CXXConstructorDecl>(Cand1.Function) !=
  8983. isa<CXXConstructorDecl>(Cand2.Function))
  8984. return isa<CXXConstructorDecl>(Cand1.Function);
  8985. // -- F1 is a non-template function and F2 is a function template
  8986. // specialization, or, if not that,
  8987. bool Cand1IsSpecialization = Cand1.Function &&
  8988. Cand1.Function->getPrimaryTemplate();
  8989. bool Cand2IsSpecialization = Cand2.Function &&
  8990. Cand2.Function->getPrimaryTemplate();
  8991. if (Cand1IsSpecialization != Cand2IsSpecialization)
  8992. return Cand2IsSpecialization;
  8993. // -- F1 and F2 are function template specializations, and the function
  8994. // template for F1 is more specialized than the template for F2
  8995. // according to the partial ordering rules described in 14.5.5.2, or,
  8996. // if not that,
  8997. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  8998. if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
  8999. Cand1.Function->getPrimaryTemplate(),
  9000. Cand2.Function->getPrimaryTemplate(), Loc,
  9001. isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
  9002. : TPOC_Call,
  9003. Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
  9004. Cand1.isReversed() ^ Cand2.isReversed()))
  9005. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  9006. }
  9007. // -— F1 and F2 are non-template functions with the same
  9008. // parameter-type-lists, and F1 is more constrained than F2 [...],
  9009. if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
  9010. sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
  9011. FunctionDecl *Function1 = Cand1.Function;
  9012. FunctionDecl *Function2 = Cand2.Function;
  9013. if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
  9014. Function1 = MF;
  9015. if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
  9016. Function2 = MF;
  9017. const Expr *RC1 = Function1->getTrailingRequiresClause();
  9018. const Expr *RC2 = Function2->getTrailingRequiresClause();
  9019. if (RC1 && RC2) {
  9020. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  9021. if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
  9022. AtLeastAsConstrained1) ||
  9023. S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
  9024. AtLeastAsConstrained2))
  9025. return false;
  9026. if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
  9027. return AtLeastAsConstrained1;
  9028. } else if (RC1 || RC2) {
  9029. return RC1 != nullptr;
  9030. }
  9031. }
  9032. // -- F1 is a constructor for a class D, F2 is a constructor for a base
  9033. // class B of D, and for all arguments the corresponding parameters of
  9034. // F1 and F2 have the same type.
  9035. // FIXME: Implement the "all parameters have the same type" check.
  9036. bool Cand1IsInherited =
  9037. isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
  9038. bool Cand2IsInherited =
  9039. isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
  9040. if (Cand1IsInherited != Cand2IsInherited)
  9041. return Cand2IsInherited;
  9042. else if (Cand1IsInherited) {
  9043. assert(Cand2IsInherited);
  9044. auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
  9045. auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
  9046. if (Cand1Class->isDerivedFrom(Cand2Class))
  9047. return true;
  9048. if (Cand2Class->isDerivedFrom(Cand1Class))
  9049. return false;
  9050. // Inherited from sibling base classes: still ambiguous.
  9051. }
  9052. // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
  9053. // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
  9054. // with reversed order of parameters and F1 is not
  9055. //
  9056. // We rank reversed + different operator as worse than just reversed, but
  9057. // that comparison can never happen, because we only consider reversing for
  9058. // the maximally-rewritten operator (== or <=>).
  9059. if (Cand1.RewriteKind != Cand2.RewriteKind)
  9060. return Cand1.RewriteKind < Cand2.RewriteKind;
  9061. // Check C++17 tie-breakers for deduction guides.
  9062. {
  9063. auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
  9064. auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
  9065. if (Guide1 && Guide2) {
  9066. // -- F1 is generated from a deduction-guide and F2 is not
  9067. if (Guide1->isImplicit() != Guide2->isImplicit())
  9068. return Guide2->isImplicit();
  9069. // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
  9070. if (Guide1->isCopyDeductionCandidate())
  9071. return true;
  9072. }
  9073. }
  9074. // Check for enable_if value-based overload resolution.
  9075. if (Cand1.Function && Cand2.Function) {
  9076. Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
  9077. if (Cmp != Comparison::Equal)
  9078. return Cmp == Comparison::Better;
  9079. }
  9080. bool HasPS1 = Cand1.Function != nullptr &&
  9081. functionHasPassObjectSizeParams(Cand1.Function);
  9082. bool HasPS2 = Cand2.Function != nullptr &&
  9083. functionHasPassObjectSizeParams(Cand2.Function);
  9084. if (HasPS1 != HasPS2 && HasPS1)
  9085. return true;
  9086. auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
  9087. if (MV == Comparison::Better)
  9088. return true;
  9089. if (MV == Comparison::Worse)
  9090. return false;
  9091. // If other rules cannot determine which is better, CUDA preference is used
  9092. // to determine which is better.
  9093. if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
  9094. FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
  9095. return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
  9096. S.IdentifyCUDAPreference(Caller, Cand2.Function);
  9097. }
  9098. // General member function overloading is handled above, so this only handles
  9099. // constructors with address spaces.
  9100. // This only handles address spaces since C++ has no other
  9101. // qualifier that can be used with constructors.
  9102. const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
  9103. const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
  9104. if (CD1 && CD2) {
  9105. LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
  9106. LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
  9107. if (AS1 != AS2) {
  9108. if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
  9109. return true;
  9110. if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
  9111. return false;
  9112. }
  9113. }
  9114. return false;
  9115. }
  9116. /// Determine whether two declarations are "equivalent" for the purposes of
  9117. /// name lookup and overload resolution. This applies when the same internal/no
  9118. /// linkage entity is defined by two modules (probably by textually including
  9119. /// the same header). In such a case, we don't consider the declarations to
  9120. /// declare the same entity, but we also don't want lookups with both
  9121. /// declarations visible to be ambiguous in some cases (this happens when using
  9122. /// a modularized libstdc++).
  9123. bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
  9124. const NamedDecl *B) {
  9125. auto *VA = dyn_cast_or_null<ValueDecl>(A);
  9126. auto *VB = dyn_cast_or_null<ValueDecl>(B);
  9127. if (!VA || !VB)
  9128. return false;
  9129. // The declarations must be declaring the same name as an internal linkage
  9130. // entity in different modules.
  9131. if (!VA->getDeclContext()->getRedeclContext()->Equals(
  9132. VB->getDeclContext()->getRedeclContext()) ||
  9133. getOwningModule(VA) == getOwningModule(VB) ||
  9134. VA->isExternallyVisible() || VB->isExternallyVisible())
  9135. return false;
  9136. // Check that the declarations appear to be equivalent.
  9137. //
  9138. // FIXME: Checking the type isn't really enough to resolve the ambiguity.
  9139. // For constants and functions, we should check the initializer or body is
  9140. // the same. For non-constant variables, we shouldn't allow it at all.
  9141. if (Context.hasSameType(VA->getType(), VB->getType()))
  9142. return true;
  9143. // Enum constants within unnamed enumerations will have different types, but
  9144. // may still be similar enough to be interchangeable for our purposes.
  9145. if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
  9146. if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
  9147. // Only handle anonymous enums. If the enumerations were named and
  9148. // equivalent, they would have been merged to the same type.
  9149. auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
  9150. auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
  9151. if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
  9152. !Context.hasSameType(EnumA->getIntegerType(),
  9153. EnumB->getIntegerType()))
  9154. return false;
  9155. // Allow this only if the value is the same for both enumerators.
  9156. return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
  9157. }
  9158. }
  9159. // Nothing else is sufficiently similar.
  9160. return false;
  9161. }
  9162. void Sema::diagnoseEquivalentInternalLinkageDeclarations(
  9163. SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
  9164. assert(D && "Unknown declaration");
  9165. Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
  9166. Module *M = getOwningModule(D);
  9167. Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
  9168. << !M << (M ? M->getFullModuleName() : "");
  9169. for (auto *E : Equiv) {
  9170. Module *M = getOwningModule(E);
  9171. Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
  9172. << !M << (M ? M->getFullModuleName() : "");
  9173. }
  9174. }
  9175. bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
  9176. return FailureKind == ovl_fail_bad_deduction &&
  9177. DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
  9178. static_cast<CNSInfo *>(DeductionFailure.Data)
  9179. ->Satisfaction.ContainsErrors;
  9180. }
  9181. /// Computes the best viable function (C++ 13.3.3)
  9182. /// within an overload candidate set.
  9183. ///
  9184. /// \param Loc The location of the function name (or operator symbol) for
  9185. /// which overload resolution occurs.
  9186. ///
  9187. /// \param Best If overload resolution was successful or found a deleted
  9188. /// function, \p Best points to the candidate function found.
  9189. ///
  9190. /// \returns The result of overload resolution.
  9191. OverloadingResult
  9192. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  9193. iterator &Best) {
  9194. llvm::SmallVector<OverloadCandidate *, 16> Candidates;
  9195. std::transform(begin(), end(), std::back_inserter(Candidates),
  9196. [](OverloadCandidate &Cand) { return &Cand; });
  9197. // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
  9198. // are accepted by both clang and NVCC. However, during a particular
  9199. // compilation mode only one call variant is viable. We need to
  9200. // exclude non-viable overload candidates from consideration based
  9201. // only on their host/device attributes. Specifically, if one
  9202. // candidate call is WrongSide and the other is SameSide, we ignore
  9203. // the WrongSide candidate.
  9204. // We only need to remove wrong-sided candidates here if
  9205. // -fgpu-exclude-wrong-side-overloads is off. When
  9206. // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
  9207. // uniformly in isBetterOverloadCandidate.
  9208. if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
  9209. const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
  9210. bool ContainsSameSideCandidate =
  9211. llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
  9212. // Check viable function only.
  9213. return Cand->Viable && Cand->Function &&
  9214. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  9215. Sema::CFP_SameSide;
  9216. });
  9217. if (ContainsSameSideCandidate) {
  9218. auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
  9219. // Check viable function only to avoid unnecessary data copying/moving.
  9220. return Cand->Viable && Cand->Function &&
  9221. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  9222. Sema::CFP_WrongSide;
  9223. };
  9224. llvm::erase_if(Candidates, IsWrongSideCandidate);
  9225. }
  9226. }
  9227. // Find the best viable function.
  9228. Best = end();
  9229. for (auto *Cand : Candidates) {
  9230. Cand->Best = false;
  9231. if (Cand->Viable) {
  9232. if (Best == end() ||
  9233. isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
  9234. Best = Cand;
  9235. } else if (Cand->NotValidBecauseConstraintExprHasError()) {
  9236. // This candidate has constraint that we were unable to evaluate because
  9237. // it referenced an expression that contained an error. Rather than fall
  9238. // back onto a potentially unintended candidate (made worse by
  9239. // subsuming constraints), treat this as 'no viable candidate'.
  9240. Best = end();
  9241. return OR_No_Viable_Function;
  9242. }
  9243. }
  9244. // If we didn't find any viable functions, abort.
  9245. if (Best == end())
  9246. return OR_No_Viable_Function;
  9247. llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
  9248. llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
  9249. PendingBest.push_back(&*Best);
  9250. Best->Best = true;
  9251. // Make sure that this function is better than every other viable
  9252. // function. If not, we have an ambiguity.
  9253. while (!PendingBest.empty()) {
  9254. auto *Curr = PendingBest.pop_back_val();
  9255. for (auto *Cand : Candidates) {
  9256. if (Cand->Viable && !Cand->Best &&
  9257. !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
  9258. PendingBest.push_back(Cand);
  9259. Cand->Best = true;
  9260. if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
  9261. Curr->Function))
  9262. EquivalentCands.push_back(Cand->Function);
  9263. else
  9264. Best = end();
  9265. }
  9266. }
  9267. }
  9268. // If we found more than one best candidate, this is ambiguous.
  9269. if (Best == end())
  9270. return OR_Ambiguous;
  9271. // Best is the best viable function.
  9272. if (Best->Function && Best->Function->isDeleted())
  9273. return OR_Deleted;
  9274. if (!EquivalentCands.empty())
  9275. S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
  9276. EquivalentCands);
  9277. return OR_Success;
  9278. }
  9279. namespace {
  9280. enum OverloadCandidateKind {
  9281. oc_function,
  9282. oc_method,
  9283. oc_reversed_binary_operator,
  9284. oc_constructor,
  9285. oc_implicit_default_constructor,
  9286. oc_implicit_copy_constructor,
  9287. oc_implicit_move_constructor,
  9288. oc_implicit_copy_assignment,
  9289. oc_implicit_move_assignment,
  9290. oc_implicit_equality_comparison,
  9291. oc_inherited_constructor
  9292. };
  9293. enum OverloadCandidateSelect {
  9294. ocs_non_template,
  9295. ocs_template,
  9296. ocs_described_template,
  9297. };
  9298. static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
  9299. ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
  9300. OverloadCandidateRewriteKind CRK,
  9301. std::string &Description) {
  9302. bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
  9303. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  9304. isTemplate = true;
  9305. Description = S.getTemplateArgumentBindingsText(
  9306. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  9307. }
  9308. OverloadCandidateSelect Select = [&]() {
  9309. if (!Description.empty())
  9310. return ocs_described_template;
  9311. return isTemplate ? ocs_template : ocs_non_template;
  9312. }();
  9313. OverloadCandidateKind Kind = [&]() {
  9314. if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
  9315. return oc_implicit_equality_comparison;
  9316. if (CRK & CRK_Reversed)
  9317. return oc_reversed_binary_operator;
  9318. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  9319. if (!Ctor->isImplicit()) {
  9320. if (isa<ConstructorUsingShadowDecl>(Found))
  9321. return oc_inherited_constructor;
  9322. else
  9323. return oc_constructor;
  9324. }
  9325. if (Ctor->isDefaultConstructor())
  9326. return oc_implicit_default_constructor;
  9327. if (Ctor->isMoveConstructor())
  9328. return oc_implicit_move_constructor;
  9329. assert(Ctor->isCopyConstructor() &&
  9330. "unexpected sort of implicit constructor");
  9331. return oc_implicit_copy_constructor;
  9332. }
  9333. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  9334. // This actually gets spelled 'candidate function' for now, but
  9335. // it doesn't hurt to split it out.
  9336. if (!Meth->isImplicit())
  9337. return oc_method;
  9338. if (Meth->isMoveAssignmentOperator())
  9339. return oc_implicit_move_assignment;
  9340. if (Meth->isCopyAssignmentOperator())
  9341. return oc_implicit_copy_assignment;
  9342. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  9343. return oc_method;
  9344. }
  9345. return oc_function;
  9346. }();
  9347. return std::make_pair(Kind, Select);
  9348. }
  9349. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
  9350. // FIXME: It'd be nice to only emit a note once per using-decl per overload
  9351. // set.
  9352. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
  9353. S.Diag(FoundDecl->getLocation(),
  9354. diag::note_ovl_candidate_inherited_constructor)
  9355. << Shadow->getNominatedBaseClass();
  9356. }
  9357. } // end anonymous namespace
  9358. static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
  9359. const FunctionDecl *FD) {
  9360. for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
  9361. bool AlwaysTrue;
  9362. if (EnableIf->getCond()->isValueDependent() ||
  9363. !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
  9364. return false;
  9365. if (!AlwaysTrue)
  9366. return false;
  9367. }
  9368. return true;
  9369. }
  9370. /// Returns true if we can take the address of the function.
  9371. ///
  9372. /// \param Complain - If true, we'll emit a diagnostic
  9373. /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
  9374. /// we in overload resolution?
  9375. /// \param Loc - The location of the statement we're complaining about. Ignored
  9376. /// if we're not complaining, or if we're in overload resolution.
  9377. static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
  9378. bool Complain,
  9379. bool InOverloadResolution,
  9380. SourceLocation Loc) {
  9381. if (!isFunctionAlwaysEnabled(S.Context, FD)) {
  9382. if (Complain) {
  9383. if (InOverloadResolution)
  9384. S.Diag(FD->getBeginLoc(),
  9385. diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
  9386. else
  9387. S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
  9388. }
  9389. return false;
  9390. }
  9391. if (FD->getTrailingRequiresClause()) {
  9392. ConstraintSatisfaction Satisfaction;
  9393. if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
  9394. return false;
  9395. if (!Satisfaction.IsSatisfied) {
  9396. if (Complain) {
  9397. if (InOverloadResolution) {
  9398. SmallString<128> TemplateArgString;
  9399. if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
  9400. TemplateArgString += " ";
  9401. TemplateArgString += S.getTemplateArgumentBindingsText(
  9402. FunTmpl->getTemplateParameters(),
  9403. *FD->getTemplateSpecializationArgs());
  9404. }
  9405. S.Diag(FD->getBeginLoc(),
  9406. diag::note_ovl_candidate_unsatisfied_constraints)
  9407. << TemplateArgString;
  9408. } else
  9409. S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
  9410. << FD;
  9411. S.DiagnoseUnsatisfiedConstraint(Satisfaction);
  9412. }
  9413. return false;
  9414. }
  9415. }
  9416. auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
  9417. return P->hasAttr<PassObjectSizeAttr>();
  9418. });
  9419. if (I == FD->param_end())
  9420. return true;
  9421. if (Complain) {
  9422. // Add one to ParamNo because it's user-facing
  9423. unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
  9424. if (InOverloadResolution)
  9425. S.Diag(FD->getLocation(),
  9426. diag::note_ovl_candidate_has_pass_object_size_params)
  9427. << ParamNo;
  9428. else
  9429. S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
  9430. << FD << ParamNo;
  9431. }
  9432. return false;
  9433. }
  9434. static bool checkAddressOfCandidateIsAvailable(Sema &S,
  9435. const FunctionDecl *FD) {
  9436. return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
  9437. /*InOverloadResolution=*/true,
  9438. /*Loc=*/SourceLocation());
  9439. }
  9440. bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
  9441. bool Complain,
  9442. SourceLocation Loc) {
  9443. return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
  9444. /*InOverloadResolution=*/false,
  9445. Loc);
  9446. }
  9447. // Don't print candidates other than the one that matches the calling
  9448. // convention of the call operator, since that is guaranteed to exist.
  9449. static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
  9450. const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
  9451. if (!ConvD)
  9452. return false;
  9453. const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
  9454. if (!RD->isLambda())
  9455. return false;
  9456. CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
  9457. CallingConv CallOpCC =
  9458. CallOp->getType()->castAs<FunctionType>()->getCallConv();
  9459. QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
  9460. CallingConv ConvToCC =
  9461. ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
  9462. return ConvToCC != CallOpCC;
  9463. }
  9464. // Notes the location of an overload candidate.
  9465. void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
  9466. OverloadCandidateRewriteKind RewriteKind,
  9467. QualType DestType, bool TakingAddress) {
  9468. if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
  9469. return;
  9470. if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
  9471. !Fn->getAttr<TargetAttr>()->isDefaultVersion())
  9472. return;
  9473. if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
  9474. !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
  9475. return;
  9476. if (shouldSkipNotingLambdaConversionDecl(Fn))
  9477. return;
  9478. std::string FnDesc;
  9479. std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
  9480. ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
  9481. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  9482. << (unsigned)KSPair.first << (unsigned)KSPair.second
  9483. << Fn << FnDesc;
  9484. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  9485. Diag(Fn->getLocation(), PD);
  9486. MaybeEmitInheritedConstructorNote(*this, Found);
  9487. }
  9488. static void
  9489. MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
  9490. // Perhaps the ambiguity was caused by two atomic constraints that are
  9491. // 'identical' but not equivalent:
  9492. //
  9493. // void foo() requires (sizeof(T) > 4) { } // #1
  9494. // void foo() requires (sizeof(T) > 4) && T::value { } // #2
  9495. //
  9496. // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
  9497. // #2 to subsume #1, but these constraint are not considered equivalent
  9498. // according to the subsumption rules because they are not the same
  9499. // source-level construct. This behavior is quite confusing and we should try
  9500. // to help the user figure out what happened.
  9501. SmallVector<const Expr *, 3> FirstAC, SecondAC;
  9502. FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
  9503. for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  9504. if (!I->Function)
  9505. continue;
  9506. SmallVector<const Expr *, 3> AC;
  9507. if (auto *Template = I->Function->getPrimaryTemplate())
  9508. Template->getAssociatedConstraints(AC);
  9509. else
  9510. I->Function->getAssociatedConstraints(AC);
  9511. if (AC.empty())
  9512. continue;
  9513. if (FirstCand == nullptr) {
  9514. FirstCand = I->Function;
  9515. FirstAC = AC;
  9516. } else if (SecondCand == nullptr) {
  9517. SecondCand = I->Function;
  9518. SecondAC = AC;
  9519. } else {
  9520. // We have more than one pair of constrained functions - this check is
  9521. // expensive and we'd rather not try to diagnose it.
  9522. return;
  9523. }
  9524. }
  9525. if (!SecondCand)
  9526. return;
  9527. // The diagnostic can only happen if there are associated constraints on
  9528. // both sides (there needs to be some identical atomic constraint).
  9529. if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
  9530. SecondCand, SecondAC))
  9531. // Just show the user one diagnostic, they'll probably figure it out
  9532. // from here.
  9533. return;
  9534. }
  9535. // Notes the location of all overload candidates designated through
  9536. // OverloadedExpr
  9537. void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
  9538. bool TakingAddress) {
  9539. assert(OverloadedExpr->getType() == Context.OverloadTy);
  9540. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  9541. OverloadExpr *OvlExpr = Ovl.Expression;
  9542. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9543. IEnd = OvlExpr->decls_end();
  9544. I != IEnd; ++I) {
  9545. if (FunctionTemplateDecl *FunTmpl =
  9546. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  9547. NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
  9548. TakingAddress);
  9549. } else if (FunctionDecl *Fun
  9550. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  9551. NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
  9552. }
  9553. }
  9554. }
  9555. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  9556. /// "lead" diagnostic; it will be given two arguments, the source and
  9557. /// target types of the conversion.
  9558. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  9559. Sema &S,
  9560. SourceLocation CaretLoc,
  9561. const PartialDiagnostic &PDiag) const {
  9562. S.Diag(CaretLoc, PDiag)
  9563. << Ambiguous.getFromType() << Ambiguous.getToType();
  9564. unsigned CandsShown = 0;
  9565. AmbiguousConversionSequence::const_iterator I, E;
  9566. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  9567. if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
  9568. break;
  9569. ++CandsShown;
  9570. S.NoteOverloadCandidate(I->first, I->second);
  9571. }
  9572. S.Diags.overloadCandidatesShown(CandsShown);
  9573. if (I != E)
  9574. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  9575. }
  9576. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  9577. unsigned I, bool TakingCandidateAddress) {
  9578. const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  9579. assert(Conv.isBad());
  9580. assert(Cand->Function && "for now, candidate must be a function");
  9581. FunctionDecl *Fn = Cand->Function;
  9582. // There's a conversion slot for the object argument if this is a
  9583. // non-constructor method. Note that 'I' corresponds the
  9584. // conversion-slot index.
  9585. bool isObjectArgument = false;
  9586. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  9587. if (I == 0)
  9588. isObjectArgument = true;
  9589. else
  9590. I--;
  9591. }
  9592. std::string FnDesc;
  9593. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9594. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
  9595. FnDesc);
  9596. Expr *FromExpr = Conv.Bad.FromExpr;
  9597. QualType FromTy = Conv.Bad.getFromType();
  9598. QualType ToTy = Conv.Bad.getToType();
  9599. if (FromTy == S.Context.OverloadTy) {
  9600. assert(FromExpr && "overload set argument came from implicit argument?");
  9601. Expr *E = FromExpr->IgnoreParens();
  9602. if (isa<UnaryOperator>(E))
  9603. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  9604. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  9605. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
  9606. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9607. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
  9608. << Name << I + 1;
  9609. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9610. return;
  9611. }
  9612. // Do some hand-waving analysis to see if the non-viability is due
  9613. // to a qualifier mismatch.
  9614. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  9615. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  9616. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  9617. CToTy = RT->getPointeeType();
  9618. else {
  9619. // TODO: detect and diagnose the full richness of const mismatches.
  9620. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  9621. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
  9622. CFromTy = FromPT->getPointeeType();
  9623. CToTy = ToPT->getPointeeType();
  9624. }
  9625. }
  9626. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  9627. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  9628. Qualifiers FromQs = CFromTy.getQualifiers();
  9629. Qualifiers ToQs = CToTy.getQualifiers();
  9630. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  9631. if (isObjectArgument)
  9632. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
  9633. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9634. << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9635. << FromQs.getAddressSpace() << ToQs.getAddressSpace();
  9636. else
  9637. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
  9638. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9639. << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9640. << FromQs.getAddressSpace() << ToQs.getAddressSpace()
  9641. << ToTy->isReferenceType() << I + 1;
  9642. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9643. return;
  9644. }
  9645. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  9646. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
  9647. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9648. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9649. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  9650. << (unsigned)isObjectArgument << I + 1;
  9651. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9652. return;
  9653. }
  9654. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  9655. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
  9656. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9657. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9658. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  9659. << (unsigned)isObjectArgument << I + 1;
  9660. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9661. return;
  9662. }
  9663. if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
  9664. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
  9665. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9666. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9667. << FromQs.hasUnaligned() << I + 1;
  9668. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9669. return;
  9670. }
  9671. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  9672. assert(CVR && "expected qualifiers mismatch");
  9673. if (isObjectArgument) {
  9674. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
  9675. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9676. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9677. << (CVR - 1);
  9678. } else {
  9679. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
  9680. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9681. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9682. << (CVR - 1) << I + 1;
  9683. }
  9684. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9685. return;
  9686. }
  9687. if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
  9688. Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
  9689. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
  9690. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9691. << (unsigned)isObjectArgument << I + 1
  9692. << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
  9693. << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
  9694. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9695. return;
  9696. }
  9697. // Special diagnostic for failure to convert an initializer list, since
  9698. // telling the user that it has type void is not useful.
  9699. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  9700. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
  9701. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9702. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9703. << ToTy << (unsigned)isObjectArgument << I + 1
  9704. << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
  9705. : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
  9706. ? 2
  9707. : 0);
  9708. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9709. return;
  9710. }
  9711. // Diagnose references or pointers to incomplete types differently,
  9712. // since it's far from impossible that the incompleteness triggered
  9713. // the failure.
  9714. QualType TempFromTy = FromTy.getNonReferenceType();
  9715. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  9716. TempFromTy = PTy->getPointeeType();
  9717. if (TempFromTy->isIncompleteType()) {
  9718. // Emit the generic diagnostic and, optionally, add the hints to it.
  9719. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
  9720. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9721. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9722. << ToTy << (unsigned)isObjectArgument << I + 1
  9723. << (unsigned)(Cand->Fix.Kind);
  9724. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9725. return;
  9726. }
  9727. // Diagnose base -> derived pointer conversions.
  9728. unsigned BaseToDerivedConversion = 0;
  9729. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  9730. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  9731. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  9732. FromPtrTy->getPointeeType()) &&
  9733. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  9734. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  9735. S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
  9736. FromPtrTy->getPointeeType()))
  9737. BaseToDerivedConversion = 1;
  9738. }
  9739. } else if (const ObjCObjectPointerType *FromPtrTy
  9740. = FromTy->getAs<ObjCObjectPointerType>()) {
  9741. if (const ObjCObjectPointerType *ToPtrTy
  9742. = ToTy->getAs<ObjCObjectPointerType>())
  9743. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  9744. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  9745. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  9746. FromPtrTy->getPointeeType()) &&
  9747. FromIface->isSuperClassOf(ToIface))
  9748. BaseToDerivedConversion = 2;
  9749. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  9750. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  9751. !FromTy->isIncompleteType() &&
  9752. !ToRefTy->getPointeeType()->isIncompleteType() &&
  9753. S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
  9754. BaseToDerivedConversion = 3;
  9755. }
  9756. }
  9757. if (BaseToDerivedConversion) {
  9758. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
  9759. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9760. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9761. << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
  9762. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9763. return;
  9764. }
  9765. if (isa<ObjCObjectPointerType>(CFromTy) &&
  9766. isa<PointerType>(CToTy)) {
  9767. Qualifiers FromQs = CFromTy.getQualifiers();
  9768. Qualifiers ToQs = CToTy.getQualifiers();
  9769. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  9770. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
  9771. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9772. << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9773. << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
  9774. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9775. return;
  9776. }
  9777. }
  9778. if (TakingCandidateAddress &&
  9779. !checkAddressOfCandidateIsAvailable(S, Cand->Function))
  9780. return;
  9781. // Emit the generic diagnostic and, optionally, add the hints to it.
  9782. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  9783. FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9784. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9785. << ToTy << (unsigned)isObjectArgument << I + 1
  9786. << (unsigned)(Cand->Fix.Kind);
  9787. // Check that location of Fn is not in system header.
  9788. if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
  9789. // If we can fix the conversion, suggest the FixIts.
  9790. for (const FixItHint &HI : Cand->Fix.Hints)
  9791. FDiag << HI;
  9792. }
  9793. S.Diag(Fn->getLocation(), FDiag);
  9794. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9795. }
  9796. /// Additional arity mismatch diagnosis specific to a function overload
  9797. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  9798. /// over a candidate in any candidate set.
  9799. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  9800. unsigned NumArgs) {
  9801. FunctionDecl *Fn = Cand->Function;
  9802. unsigned MinParams = Fn->getMinRequiredArguments();
  9803. // With invalid overloaded operators, it's possible that we think we
  9804. // have an arity mismatch when in fact it looks like we have the
  9805. // right number of arguments, because only overloaded operators have
  9806. // the weird behavior of overloading member and non-member functions.
  9807. // Just don't report anything.
  9808. if (Fn->isInvalidDecl() &&
  9809. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  9810. return true;
  9811. if (NumArgs < MinParams) {
  9812. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  9813. (Cand->FailureKind == ovl_fail_bad_deduction &&
  9814. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  9815. } else {
  9816. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  9817. (Cand->FailureKind == ovl_fail_bad_deduction &&
  9818. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  9819. }
  9820. return false;
  9821. }
  9822. /// General arity mismatch diagnosis over a candidate in a candidate set.
  9823. static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
  9824. unsigned NumFormalArgs) {
  9825. assert(isa<FunctionDecl>(D) &&
  9826. "The templated declaration should at least be a function"
  9827. " when diagnosing bad template argument deduction due to too many"
  9828. " or too few arguments");
  9829. FunctionDecl *Fn = cast<FunctionDecl>(D);
  9830. // TODO: treat calls to a missing default constructor as a special case
  9831. const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
  9832. unsigned MinParams = Fn->getMinRequiredArguments();
  9833. // at least / at most / exactly
  9834. unsigned mode, modeCount;
  9835. if (NumFormalArgs < MinParams) {
  9836. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  9837. FnTy->isTemplateVariadic())
  9838. mode = 0; // "at least"
  9839. else
  9840. mode = 2; // "exactly"
  9841. modeCount = MinParams;
  9842. } else {
  9843. if (MinParams != FnTy->getNumParams())
  9844. mode = 1; // "at most"
  9845. else
  9846. mode = 2; // "exactly"
  9847. modeCount = FnTy->getNumParams();
  9848. }
  9849. std::string Description;
  9850. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9851. ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
  9852. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  9853. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
  9854. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9855. << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
  9856. else
  9857. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
  9858. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9859. << Description << mode << modeCount << NumFormalArgs;
  9860. MaybeEmitInheritedConstructorNote(S, Found);
  9861. }
  9862. /// Arity mismatch diagnosis specific to a function overload candidate.
  9863. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  9864. unsigned NumFormalArgs) {
  9865. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  9866. DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
  9867. }
  9868. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  9869. if (TemplateDecl *TD = Templated->getDescribedTemplate())
  9870. return TD;
  9871. llvm_unreachable("Unsupported: Getting the described template declaration"
  9872. " for bad deduction diagnosis");
  9873. }
  9874. /// Diagnose a failed template-argument deduction.
  9875. static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
  9876. DeductionFailureInfo &DeductionFailure,
  9877. unsigned NumArgs,
  9878. bool TakingCandidateAddress) {
  9879. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  9880. NamedDecl *ParamD;
  9881. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  9882. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  9883. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  9884. switch (DeductionFailure.Result) {
  9885. case Sema::TDK_Success:
  9886. llvm_unreachable("TDK_success while diagnosing bad deduction");
  9887. case Sema::TDK_Incomplete: {
  9888. assert(ParamD && "no parameter found for incomplete deduction result");
  9889. S.Diag(Templated->getLocation(),
  9890. diag::note_ovl_candidate_incomplete_deduction)
  9891. << ParamD->getDeclName();
  9892. MaybeEmitInheritedConstructorNote(S, Found);
  9893. return;
  9894. }
  9895. case Sema::TDK_IncompletePack: {
  9896. assert(ParamD && "no parameter found for incomplete deduction result");
  9897. S.Diag(Templated->getLocation(),
  9898. diag::note_ovl_candidate_incomplete_deduction_pack)
  9899. << ParamD->getDeclName()
  9900. << (DeductionFailure.getFirstArg()->pack_size() + 1)
  9901. << *DeductionFailure.getFirstArg();
  9902. MaybeEmitInheritedConstructorNote(S, Found);
  9903. return;
  9904. }
  9905. case Sema::TDK_Underqualified: {
  9906. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  9907. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  9908. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  9909. // Param will have been canonicalized, but it should just be a
  9910. // qualified version of ParamD, so move the qualifiers to that.
  9911. QualifierCollector Qs;
  9912. Qs.strip(Param);
  9913. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  9914. assert(S.Context.hasSameType(Param, NonCanonParam));
  9915. // Arg has also been canonicalized, but there's nothing we can do
  9916. // about that. It also doesn't matter as much, because it won't
  9917. // have any template parameters in it (because deduction isn't
  9918. // done on dependent types).
  9919. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  9920. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  9921. << ParamD->getDeclName() << Arg << NonCanonParam;
  9922. MaybeEmitInheritedConstructorNote(S, Found);
  9923. return;
  9924. }
  9925. case Sema::TDK_Inconsistent: {
  9926. assert(ParamD && "no parameter found for inconsistent deduction result");
  9927. int which = 0;
  9928. if (isa<TemplateTypeParmDecl>(ParamD))
  9929. which = 0;
  9930. else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
  9931. // Deduction might have failed because we deduced arguments of two
  9932. // different types for a non-type template parameter.
  9933. // FIXME: Use a different TDK value for this.
  9934. QualType T1 =
  9935. DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
  9936. QualType T2 =
  9937. DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
  9938. if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
  9939. S.Diag(Templated->getLocation(),
  9940. diag::note_ovl_candidate_inconsistent_deduction_types)
  9941. << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
  9942. << *DeductionFailure.getSecondArg() << T2;
  9943. MaybeEmitInheritedConstructorNote(S, Found);
  9944. return;
  9945. }
  9946. which = 1;
  9947. } else {
  9948. which = 2;
  9949. }
  9950. // Tweak the diagnostic if the problem is that we deduced packs of
  9951. // different arities. We'll print the actual packs anyway in case that
  9952. // includes additional useful information.
  9953. if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
  9954. DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
  9955. DeductionFailure.getFirstArg()->pack_size() !=
  9956. DeductionFailure.getSecondArg()->pack_size()) {
  9957. which = 3;
  9958. }
  9959. S.Diag(Templated->getLocation(),
  9960. diag::note_ovl_candidate_inconsistent_deduction)
  9961. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  9962. << *DeductionFailure.getSecondArg();
  9963. MaybeEmitInheritedConstructorNote(S, Found);
  9964. return;
  9965. }
  9966. case Sema::TDK_InvalidExplicitArguments:
  9967. assert(ParamD && "no parameter found for invalid explicit arguments");
  9968. if (ParamD->getDeclName())
  9969. S.Diag(Templated->getLocation(),
  9970. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  9971. << ParamD->getDeclName();
  9972. else {
  9973. int index = 0;
  9974. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  9975. index = TTP->getIndex();
  9976. else if (NonTypeTemplateParmDecl *NTTP
  9977. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  9978. index = NTTP->getIndex();
  9979. else
  9980. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  9981. S.Diag(Templated->getLocation(),
  9982. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  9983. << (index + 1);
  9984. }
  9985. MaybeEmitInheritedConstructorNote(S, Found);
  9986. return;
  9987. case Sema::TDK_ConstraintsNotSatisfied: {
  9988. // Format the template argument list into the argument string.
  9989. SmallString<128> TemplateArgString;
  9990. TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
  9991. TemplateArgString = " ";
  9992. TemplateArgString += S.getTemplateArgumentBindingsText(
  9993. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9994. if (TemplateArgString.size() == 1)
  9995. TemplateArgString.clear();
  9996. S.Diag(Templated->getLocation(),
  9997. diag::note_ovl_candidate_unsatisfied_constraints)
  9998. << TemplateArgString;
  9999. S.DiagnoseUnsatisfiedConstraint(
  10000. static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
  10001. return;
  10002. }
  10003. case Sema::TDK_TooManyArguments:
  10004. case Sema::TDK_TooFewArguments:
  10005. DiagnoseArityMismatch(S, Found, Templated, NumArgs);
  10006. return;
  10007. case Sema::TDK_InstantiationDepth:
  10008. S.Diag(Templated->getLocation(),
  10009. diag::note_ovl_candidate_instantiation_depth);
  10010. MaybeEmitInheritedConstructorNote(S, Found);
  10011. return;
  10012. case Sema::TDK_SubstitutionFailure: {
  10013. // Format the template argument list into the argument string.
  10014. SmallString<128> TemplateArgString;
  10015. if (TemplateArgumentList *Args =
  10016. DeductionFailure.getTemplateArgumentList()) {
  10017. TemplateArgString = " ";
  10018. TemplateArgString += S.getTemplateArgumentBindingsText(
  10019. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  10020. if (TemplateArgString.size() == 1)
  10021. TemplateArgString.clear();
  10022. }
  10023. // If this candidate was disabled by enable_if, say so.
  10024. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  10025. if (PDiag && PDiag->second.getDiagID() ==
  10026. diag::err_typename_nested_not_found_enable_if) {
  10027. // FIXME: Use the source range of the condition, and the fully-qualified
  10028. // name of the enable_if template. These are both present in PDiag.
  10029. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  10030. << "'enable_if'" << TemplateArgString;
  10031. return;
  10032. }
  10033. // We found a specific requirement that disabled the enable_if.
  10034. if (PDiag && PDiag->second.getDiagID() ==
  10035. diag::err_typename_nested_not_found_requirement) {
  10036. S.Diag(Templated->getLocation(),
  10037. diag::note_ovl_candidate_disabled_by_requirement)
  10038. << PDiag->second.getStringArg(0) << TemplateArgString;
  10039. return;
  10040. }
  10041. // Format the SFINAE diagnostic into the argument string.
  10042. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  10043. // formatted message in another diagnostic.
  10044. SmallString<128> SFINAEArgString;
  10045. SourceRange R;
  10046. if (PDiag) {
  10047. SFINAEArgString = ": ";
  10048. R = SourceRange(PDiag->first, PDiag->first);
  10049. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  10050. }
  10051. S.Diag(Templated->getLocation(),
  10052. diag::note_ovl_candidate_substitution_failure)
  10053. << TemplateArgString << SFINAEArgString << R;
  10054. MaybeEmitInheritedConstructorNote(S, Found);
  10055. return;
  10056. }
  10057. case Sema::TDK_DeducedMismatch:
  10058. case Sema::TDK_DeducedMismatchNested: {
  10059. // Format the template argument list into the argument string.
  10060. SmallString<128> TemplateArgString;
  10061. if (TemplateArgumentList *Args =
  10062. DeductionFailure.getTemplateArgumentList()) {
  10063. TemplateArgString = " ";
  10064. TemplateArgString += S.getTemplateArgumentBindingsText(
  10065. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  10066. if (TemplateArgString.size() == 1)
  10067. TemplateArgString.clear();
  10068. }
  10069. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
  10070. << (*DeductionFailure.getCallArgIndex() + 1)
  10071. << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
  10072. << TemplateArgString
  10073. << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
  10074. break;
  10075. }
  10076. case Sema::TDK_NonDeducedMismatch: {
  10077. // FIXME: Provide a source location to indicate what we couldn't match.
  10078. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  10079. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  10080. if (FirstTA.getKind() == TemplateArgument::Template &&
  10081. SecondTA.getKind() == TemplateArgument::Template) {
  10082. TemplateName FirstTN = FirstTA.getAsTemplate();
  10083. TemplateName SecondTN = SecondTA.getAsTemplate();
  10084. if (FirstTN.getKind() == TemplateName::Template &&
  10085. SecondTN.getKind() == TemplateName::Template) {
  10086. if (FirstTN.getAsTemplateDecl()->getName() ==
  10087. SecondTN.getAsTemplateDecl()->getName()) {
  10088. // FIXME: This fixes a bad diagnostic where both templates are named
  10089. // the same. This particular case is a bit difficult since:
  10090. // 1) It is passed as a string to the diagnostic printer.
  10091. // 2) The diagnostic printer only attempts to find a better
  10092. // name for types, not decls.
  10093. // Ideally, this should folded into the diagnostic printer.
  10094. S.Diag(Templated->getLocation(),
  10095. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  10096. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  10097. return;
  10098. }
  10099. }
  10100. }
  10101. if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
  10102. !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
  10103. return;
  10104. // FIXME: For generic lambda parameters, check if the function is a lambda
  10105. // call operator, and if so, emit a prettier and more informative
  10106. // diagnostic that mentions 'auto' and lambda in addition to
  10107. // (or instead of?) the canonical template type parameters.
  10108. S.Diag(Templated->getLocation(),
  10109. diag::note_ovl_candidate_non_deduced_mismatch)
  10110. << FirstTA << SecondTA;
  10111. return;
  10112. }
  10113. // TODO: diagnose these individually, then kill off
  10114. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  10115. case Sema::TDK_MiscellaneousDeductionFailure:
  10116. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  10117. MaybeEmitInheritedConstructorNote(S, Found);
  10118. return;
  10119. case Sema::TDK_CUDATargetMismatch:
  10120. S.Diag(Templated->getLocation(),
  10121. diag::note_cuda_ovl_candidate_target_mismatch);
  10122. return;
  10123. }
  10124. }
  10125. /// Diagnose a failed template-argument deduction, for function calls.
  10126. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  10127. unsigned NumArgs,
  10128. bool TakingCandidateAddress) {
  10129. unsigned TDK = Cand->DeductionFailure.Result;
  10130. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  10131. if (CheckArityMismatch(S, Cand, NumArgs))
  10132. return;
  10133. }
  10134. DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
  10135. Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
  10136. }
  10137. /// CUDA: diagnose an invalid call across targets.
  10138. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  10139. FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
  10140. FunctionDecl *Callee = Cand->Function;
  10141. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  10142. CalleeTarget = S.IdentifyCUDATarget(Callee);
  10143. std::string FnDesc;
  10144. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  10145. ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
  10146. Cand->getRewriteKind(), FnDesc);
  10147. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  10148. << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
  10149. << FnDesc /* Ignored */
  10150. << CalleeTarget << CallerTarget;
  10151. // This could be an implicit constructor for which we could not infer the
  10152. // target due to a collsion. Diagnose that case.
  10153. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  10154. if (Meth != nullptr && Meth->isImplicit()) {
  10155. CXXRecordDecl *ParentClass = Meth->getParent();
  10156. Sema::CXXSpecialMember CSM;
  10157. switch (FnKindPair.first) {
  10158. default:
  10159. return;
  10160. case oc_implicit_default_constructor:
  10161. CSM = Sema::CXXDefaultConstructor;
  10162. break;
  10163. case oc_implicit_copy_constructor:
  10164. CSM = Sema::CXXCopyConstructor;
  10165. break;
  10166. case oc_implicit_move_constructor:
  10167. CSM = Sema::CXXMoveConstructor;
  10168. break;
  10169. case oc_implicit_copy_assignment:
  10170. CSM = Sema::CXXCopyAssignment;
  10171. break;
  10172. case oc_implicit_move_assignment:
  10173. CSM = Sema::CXXMoveAssignment;
  10174. break;
  10175. };
  10176. bool ConstRHS = false;
  10177. if (Meth->getNumParams()) {
  10178. if (const ReferenceType *RT =
  10179. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  10180. ConstRHS = RT->getPointeeType().isConstQualified();
  10181. }
  10182. }
  10183. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  10184. /* ConstRHS */ ConstRHS,
  10185. /* Diagnose */ true);
  10186. }
  10187. }
  10188. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  10189. FunctionDecl *Callee = Cand->Function;
  10190. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  10191. S.Diag(Callee->getLocation(),
  10192. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  10193. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  10194. }
  10195. static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
  10196. ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
  10197. assert(ES.isExplicit() && "not an explicit candidate");
  10198. unsigned Kind;
  10199. switch (Cand->Function->getDeclKind()) {
  10200. case Decl::Kind::CXXConstructor:
  10201. Kind = 0;
  10202. break;
  10203. case Decl::Kind::CXXConversion:
  10204. Kind = 1;
  10205. break;
  10206. case Decl::Kind::CXXDeductionGuide:
  10207. Kind = Cand->Function->isImplicit() ? 0 : 2;
  10208. break;
  10209. default:
  10210. llvm_unreachable("invalid Decl");
  10211. }
  10212. // Note the location of the first (in-class) declaration; a redeclaration
  10213. // (particularly an out-of-class definition) will typically lack the
  10214. // 'explicit' specifier.
  10215. // FIXME: This is probably a good thing to do for all 'candidate' notes.
  10216. FunctionDecl *First = Cand->Function->getFirstDecl();
  10217. if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
  10218. First = Pattern->getFirstDecl();
  10219. S.Diag(First->getLocation(),
  10220. diag::note_ovl_candidate_explicit)
  10221. << Kind << (ES.getExpr() ? 1 : 0)
  10222. << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
  10223. }
  10224. /// Generates a 'note' diagnostic for an overload candidate. We've
  10225. /// already generated a primary error at the call site.
  10226. ///
  10227. /// It really does need to be a single diagnostic with its caret
  10228. /// pointed at the candidate declaration. Yes, this creates some
  10229. /// major challenges of technical writing. Yes, this makes pointing
  10230. /// out problems with specific arguments quite awkward. It's still
  10231. /// better than generating twenty screens of text for every failed
  10232. /// overload.
  10233. ///
  10234. /// It would be great to be able to express per-candidate problems
  10235. /// more richly for those diagnostic clients that cared, but we'd
  10236. /// still have to be just as careful with the default diagnostics.
  10237. /// \param CtorDestAS Addr space of object being constructed (for ctor
  10238. /// candidates only).
  10239. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  10240. unsigned NumArgs,
  10241. bool TakingCandidateAddress,
  10242. LangAS CtorDestAS = LangAS::Default) {
  10243. FunctionDecl *Fn = Cand->Function;
  10244. if (shouldSkipNotingLambdaConversionDecl(Fn))
  10245. return;
  10246. // There is no physical candidate declaration to point to for OpenCL builtins.
  10247. // Except for failed conversions, the notes are identical for each candidate,
  10248. // so do not generate such notes.
  10249. if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
  10250. Cand->FailureKind != ovl_fail_bad_conversion)
  10251. return;
  10252. // Note deleted candidates, but only if they're viable.
  10253. if (Cand->Viable) {
  10254. if (Fn->isDeleted()) {
  10255. std::string FnDesc;
  10256. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  10257. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
  10258. Cand->getRewriteKind(), FnDesc);
  10259. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  10260. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  10261. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  10262. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  10263. return;
  10264. }
  10265. // We don't really have anything else to say about viable candidates.
  10266. S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
  10267. return;
  10268. }
  10269. switch (Cand->FailureKind) {
  10270. case ovl_fail_too_many_arguments:
  10271. case ovl_fail_too_few_arguments:
  10272. return DiagnoseArityMismatch(S, Cand, NumArgs);
  10273. case ovl_fail_bad_deduction:
  10274. return DiagnoseBadDeduction(S, Cand, NumArgs,
  10275. TakingCandidateAddress);
  10276. case ovl_fail_illegal_constructor: {
  10277. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  10278. << (Fn->getPrimaryTemplate() ? 1 : 0);
  10279. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  10280. return;
  10281. }
  10282. case ovl_fail_object_addrspace_mismatch: {
  10283. Qualifiers QualsForPrinting;
  10284. QualsForPrinting.setAddressSpace(CtorDestAS);
  10285. S.Diag(Fn->getLocation(),
  10286. diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
  10287. << QualsForPrinting;
  10288. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  10289. return;
  10290. }
  10291. case ovl_fail_trivial_conversion:
  10292. case ovl_fail_bad_final_conversion:
  10293. case ovl_fail_final_conversion_not_exact:
  10294. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
  10295. case ovl_fail_bad_conversion: {
  10296. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  10297. for (unsigned N = Cand->Conversions.size(); I != N; ++I)
  10298. if (Cand->Conversions[I].isBad())
  10299. return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
  10300. // FIXME: this currently happens when we're called from SemaInit
  10301. // when user-conversion overload fails. Figure out how to handle
  10302. // those conditions and diagnose them well.
  10303. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
  10304. }
  10305. case ovl_fail_bad_target:
  10306. return DiagnoseBadTarget(S, Cand);
  10307. case ovl_fail_enable_if:
  10308. return DiagnoseFailedEnableIfAttr(S, Cand);
  10309. case ovl_fail_explicit:
  10310. return DiagnoseFailedExplicitSpec(S, Cand);
  10311. case ovl_fail_inhctor_slice:
  10312. // It's generally not interesting to note copy/move constructors here.
  10313. if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
  10314. return;
  10315. S.Diag(Fn->getLocation(),
  10316. diag::note_ovl_candidate_inherited_constructor_slice)
  10317. << (Fn->getPrimaryTemplate() ? 1 : 0)
  10318. << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
  10319. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  10320. return;
  10321. case ovl_fail_addr_not_available: {
  10322. bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
  10323. (void)Available;
  10324. assert(!Available);
  10325. break;
  10326. }
  10327. case ovl_non_default_multiversion_function:
  10328. // Do nothing, these should simply be ignored.
  10329. break;
  10330. case ovl_fail_constraints_not_satisfied: {
  10331. std::string FnDesc;
  10332. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  10333. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
  10334. Cand->getRewriteKind(), FnDesc);
  10335. S.Diag(Fn->getLocation(),
  10336. diag::note_ovl_candidate_constraints_not_satisfied)
  10337. << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
  10338. << FnDesc /* Ignored */;
  10339. ConstraintSatisfaction Satisfaction;
  10340. if (S.CheckFunctionConstraints(Fn, Satisfaction))
  10341. break;
  10342. S.DiagnoseUnsatisfiedConstraint(Satisfaction);
  10343. }
  10344. }
  10345. }
  10346. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  10347. if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
  10348. return;
  10349. // Desugar the type of the surrogate down to a function type,
  10350. // retaining as many typedefs as possible while still showing
  10351. // the function type (and, therefore, its parameter types).
  10352. QualType FnType = Cand->Surrogate->getConversionType();
  10353. bool isLValueReference = false;
  10354. bool isRValueReference = false;
  10355. bool isPointer = false;
  10356. if (const LValueReferenceType *FnTypeRef =
  10357. FnType->getAs<LValueReferenceType>()) {
  10358. FnType = FnTypeRef->getPointeeType();
  10359. isLValueReference = true;
  10360. } else if (const RValueReferenceType *FnTypeRef =
  10361. FnType->getAs<RValueReferenceType>()) {
  10362. FnType = FnTypeRef->getPointeeType();
  10363. isRValueReference = true;
  10364. }
  10365. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  10366. FnType = FnTypePtr->getPointeeType();
  10367. isPointer = true;
  10368. }
  10369. // Desugar down to a function type.
  10370. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  10371. // Reconstruct the pointer/reference as appropriate.
  10372. if (isPointer) FnType = S.Context.getPointerType(FnType);
  10373. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  10374. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  10375. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  10376. << FnType;
  10377. }
  10378. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  10379. SourceLocation OpLoc,
  10380. OverloadCandidate *Cand) {
  10381. assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
  10382. std::string TypeStr("operator");
  10383. TypeStr += Opc;
  10384. TypeStr += "(";
  10385. TypeStr += Cand->BuiltinParamTypes[0].getAsString();
  10386. if (Cand->Conversions.size() == 1) {
  10387. TypeStr += ")";
  10388. S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
  10389. } else {
  10390. TypeStr += ", ";
  10391. TypeStr += Cand->BuiltinParamTypes[1].getAsString();
  10392. TypeStr += ")";
  10393. S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
  10394. }
  10395. }
  10396. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  10397. OverloadCandidate *Cand) {
  10398. for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
  10399. if (ICS.isBad()) break; // all meaningless after first invalid
  10400. if (!ICS.isAmbiguous()) continue;
  10401. ICS.DiagnoseAmbiguousConversion(
  10402. S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
  10403. }
  10404. }
  10405. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  10406. if (Cand->Function)
  10407. return Cand->Function->getLocation();
  10408. if (Cand->IsSurrogate)
  10409. return Cand->Surrogate->getLocation();
  10410. return SourceLocation();
  10411. }
  10412. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  10413. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  10414. case Sema::TDK_Success:
  10415. case Sema::TDK_NonDependentConversionFailure:
  10416. case Sema::TDK_AlreadyDiagnosed:
  10417. llvm_unreachable("non-deduction failure while diagnosing bad deduction");
  10418. case Sema::TDK_Invalid:
  10419. case Sema::TDK_Incomplete:
  10420. case Sema::TDK_IncompletePack:
  10421. return 1;
  10422. case Sema::TDK_Underqualified:
  10423. case Sema::TDK_Inconsistent:
  10424. return 2;
  10425. case Sema::TDK_SubstitutionFailure:
  10426. case Sema::TDK_DeducedMismatch:
  10427. case Sema::TDK_ConstraintsNotSatisfied:
  10428. case Sema::TDK_DeducedMismatchNested:
  10429. case Sema::TDK_NonDeducedMismatch:
  10430. case Sema::TDK_MiscellaneousDeductionFailure:
  10431. case Sema::TDK_CUDATargetMismatch:
  10432. return 3;
  10433. case Sema::TDK_InstantiationDepth:
  10434. return 4;
  10435. case Sema::TDK_InvalidExplicitArguments:
  10436. return 5;
  10437. case Sema::TDK_TooManyArguments:
  10438. case Sema::TDK_TooFewArguments:
  10439. return 6;
  10440. }
  10441. llvm_unreachable("Unhandled deduction result");
  10442. }
  10443. namespace {
  10444. struct CompareOverloadCandidatesForDisplay {
  10445. Sema &S;
  10446. SourceLocation Loc;
  10447. size_t NumArgs;
  10448. OverloadCandidateSet::CandidateSetKind CSK;
  10449. CompareOverloadCandidatesForDisplay(
  10450. Sema &S, SourceLocation Loc, size_t NArgs,
  10451. OverloadCandidateSet::CandidateSetKind CSK)
  10452. : S(S), NumArgs(NArgs), CSK(CSK) {}
  10453. OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
  10454. // If there are too many or too few arguments, that's the high-order bit we
  10455. // want to sort by, even if the immediate failure kind was something else.
  10456. if (C->FailureKind == ovl_fail_too_many_arguments ||
  10457. C->FailureKind == ovl_fail_too_few_arguments)
  10458. return static_cast<OverloadFailureKind>(C->FailureKind);
  10459. if (C->Function) {
  10460. if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
  10461. return ovl_fail_too_many_arguments;
  10462. if (NumArgs < C->Function->getMinRequiredArguments())
  10463. return ovl_fail_too_few_arguments;
  10464. }
  10465. return static_cast<OverloadFailureKind>(C->FailureKind);
  10466. }
  10467. bool operator()(const OverloadCandidate *L,
  10468. const OverloadCandidate *R) {
  10469. // Fast-path this check.
  10470. if (L == R) return false;
  10471. // Order first by viability.
  10472. if (L->Viable) {
  10473. if (!R->Viable) return true;
  10474. // TODO: introduce a tri-valued comparison for overload
  10475. // candidates. Would be more worthwhile if we had a sort
  10476. // that could exploit it.
  10477. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
  10478. return true;
  10479. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
  10480. return false;
  10481. } else if (R->Viable)
  10482. return false;
  10483. assert(L->Viable == R->Viable);
  10484. // Criteria by which we can sort non-viable candidates:
  10485. if (!L->Viable) {
  10486. OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
  10487. OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
  10488. // 1. Arity mismatches come after other candidates.
  10489. if (LFailureKind == ovl_fail_too_many_arguments ||
  10490. LFailureKind == ovl_fail_too_few_arguments) {
  10491. if (RFailureKind == ovl_fail_too_many_arguments ||
  10492. RFailureKind == ovl_fail_too_few_arguments) {
  10493. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  10494. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  10495. if (LDist == RDist) {
  10496. if (LFailureKind == RFailureKind)
  10497. // Sort non-surrogates before surrogates.
  10498. return !L->IsSurrogate && R->IsSurrogate;
  10499. // Sort candidates requiring fewer parameters than there were
  10500. // arguments given after candidates requiring more parameters
  10501. // than there were arguments given.
  10502. return LFailureKind == ovl_fail_too_many_arguments;
  10503. }
  10504. return LDist < RDist;
  10505. }
  10506. return false;
  10507. }
  10508. if (RFailureKind == ovl_fail_too_many_arguments ||
  10509. RFailureKind == ovl_fail_too_few_arguments)
  10510. return true;
  10511. // 2. Bad conversions come first and are ordered by the number
  10512. // of bad conversions and quality of good conversions.
  10513. if (LFailureKind == ovl_fail_bad_conversion) {
  10514. if (RFailureKind != ovl_fail_bad_conversion)
  10515. return true;
  10516. // The conversion that can be fixed with a smaller number of changes,
  10517. // comes first.
  10518. unsigned numLFixes = L->Fix.NumConversionsFixed;
  10519. unsigned numRFixes = R->Fix.NumConversionsFixed;
  10520. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  10521. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  10522. if (numLFixes != numRFixes) {
  10523. return numLFixes < numRFixes;
  10524. }
  10525. // If there's any ordering between the defined conversions...
  10526. // FIXME: this might not be transitive.
  10527. assert(L->Conversions.size() == R->Conversions.size());
  10528. int leftBetter = 0;
  10529. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  10530. for (unsigned E = L->Conversions.size(); I != E; ++I) {
  10531. switch (CompareImplicitConversionSequences(S, Loc,
  10532. L->Conversions[I],
  10533. R->Conversions[I])) {
  10534. case ImplicitConversionSequence::Better:
  10535. leftBetter++;
  10536. break;
  10537. case ImplicitConversionSequence::Worse:
  10538. leftBetter--;
  10539. break;
  10540. case ImplicitConversionSequence::Indistinguishable:
  10541. break;
  10542. }
  10543. }
  10544. if (leftBetter > 0) return true;
  10545. if (leftBetter < 0) return false;
  10546. } else if (RFailureKind == ovl_fail_bad_conversion)
  10547. return false;
  10548. if (LFailureKind == ovl_fail_bad_deduction) {
  10549. if (RFailureKind != ovl_fail_bad_deduction)
  10550. return true;
  10551. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  10552. return RankDeductionFailure(L->DeductionFailure)
  10553. < RankDeductionFailure(R->DeductionFailure);
  10554. } else if (RFailureKind == ovl_fail_bad_deduction)
  10555. return false;
  10556. // TODO: others?
  10557. }
  10558. // Sort everything else by location.
  10559. SourceLocation LLoc = GetLocationForCandidate(L);
  10560. SourceLocation RLoc = GetLocationForCandidate(R);
  10561. // Put candidates without locations (e.g. builtins) at the end.
  10562. if (LLoc.isInvalid()) return false;
  10563. if (RLoc.isInvalid()) return true;
  10564. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  10565. }
  10566. };
  10567. }
  10568. /// CompleteNonViableCandidate - Normally, overload resolution only
  10569. /// computes up to the first bad conversion. Produces the FixIt set if
  10570. /// possible.
  10571. static void
  10572. CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  10573. ArrayRef<Expr *> Args,
  10574. OverloadCandidateSet::CandidateSetKind CSK) {
  10575. assert(!Cand->Viable);
  10576. // Don't do anything on failures other than bad conversion.
  10577. if (Cand->FailureKind != ovl_fail_bad_conversion)
  10578. return;
  10579. // We only want the FixIts if all the arguments can be corrected.
  10580. bool Unfixable = false;
  10581. // Use a implicit copy initialization to check conversion fixes.
  10582. Cand->Fix.setConversionChecker(TryCopyInitialization);
  10583. // Attempt to fix the bad conversion.
  10584. unsigned ConvCount = Cand->Conversions.size();
  10585. for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
  10586. ++ConvIdx) {
  10587. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  10588. if (Cand->Conversions[ConvIdx].isInitialized() &&
  10589. Cand->Conversions[ConvIdx].isBad()) {
  10590. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  10591. break;
  10592. }
  10593. }
  10594. // FIXME: this should probably be preserved from the overload
  10595. // operation somehow.
  10596. bool SuppressUserConversions = false;
  10597. unsigned ConvIdx = 0;
  10598. unsigned ArgIdx = 0;
  10599. ArrayRef<QualType> ParamTypes;
  10600. bool Reversed = Cand->isReversed();
  10601. if (Cand->IsSurrogate) {
  10602. QualType ConvType
  10603. = Cand->Surrogate->getConversionType().getNonReferenceType();
  10604. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  10605. ConvType = ConvPtrType->getPointeeType();
  10606. ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
  10607. // Conversion 0 is 'this', which doesn't have a corresponding parameter.
  10608. ConvIdx = 1;
  10609. } else if (Cand->Function) {
  10610. ParamTypes =
  10611. Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
  10612. if (isa<CXXMethodDecl>(Cand->Function) &&
  10613. !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
  10614. // Conversion 0 is 'this', which doesn't have a corresponding parameter.
  10615. ConvIdx = 1;
  10616. if (CSK == OverloadCandidateSet::CSK_Operator &&
  10617. Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
  10618. Cand->Function->getDeclName().getCXXOverloadedOperator() !=
  10619. OO_Subscript)
  10620. // Argument 0 is 'this', which doesn't have a corresponding parameter.
  10621. ArgIdx = 1;
  10622. }
  10623. } else {
  10624. // Builtin operator.
  10625. assert(ConvCount <= 3);
  10626. ParamTypes = Cand->BuiltinParamTypes;
  10627. }
  10628. // Fill in the rest of the conversions.
  10629. for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
  10630. ConvIdx != ConvCount;
  10631. ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
  10632. assert(ArgIdx < Args.size() && "no argument for this arg conversion");
  10633. if (Cand->Conversions[ConvIdx].isInitialized()) {
  10634. // We've already checked this conversion.
  10635. } else if (ParamIdx < ParamTypes.size()) {
  10636. if (ParamTypes[ParamIdx]->isDependentType())
  10637. Cand->Conversions[ConvIdx].setAsIdentityConversion(
  10638. Args[ArgIdx]->getType());
  10639. else {
  10640. Cand->Conversions[ConvIdx] =
  10641. TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
  10642. SuppressUserConversions,
  10643. /*InOverloadResolution=*/true,
  10644. /*AllowObjCWritebackConversion=*/
  10645. S.getLangOpts().ObjCAutoRefCount);
  10646. // Store the FixIt in the candidate if it exists.
  10647. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  10648. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  10649. }
  10650. } else
  10651. Cand->Conversions[ConvIdx].setEllipsis();
  10652. }
  10653. }
  10654. SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
  10655. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  10656. SourceLocation OpLoc,
  10657. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  10658. // Sort the candidates by viability and position. Sorting directly would
  10659. // be prohibitive, so we make a set of pointers and sort those.
  10660. SmallVector<OverloadCandidate*, 32> Cands;
  10661. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  10662. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  10663. if (!Filter(*Cand))
  10664. continue;
  10665. switch (OCD) {
  10666. case OCD_AllCandidates:
  10667. if (!Cand->Viable) {
  10668. if (!Cand->Function && !Cand->IsSurrogate) {
  10669. // This a non-viable builtin candidate. We do not, in general,
  10670. // want to list every possible builtin candidate.
  10671. continue;
  10672. }
  10673. CompleteNonViableCandidate(S, Cand, Args, Kind);
  10674. }
  10675. break;
  10676. case OCD_ViableCandidates:
  10677. if (!Cand->Viable)
  10678. continue;
  10679. break;
  10680. case OCD_AmbiguousCandidates:
  10681. if (!Cand->Best)
  10682. continue;
  10683. break;
  10684. }
  10685. Cands.push_back(Cand);
  10686. }
  10687. llvm::stable_sort(
  10688. Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
  10689. return Cands;
  10690. }
  10691. bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
  10692. SourceLocation OpLoc) {
  10693. bool DeferHint = false;
  10694. if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
  10695. // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
  10696. // host device candidates.
  10697. auto WrongSidedCands =
  10698. CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
  10699. return (Cand.Viable == false &&
  10700. Cand.FailureKind == ovl_fail_bad_target) ||
  10701. (Cand.Function &&
  10702. Cand.Function->template hasAttr<CUDAHostAttr>() &&
  10703. Cand.Function->template hasAttr<CUDADeviceAttr>());
  10704. });
  10705. DeferHint = !WrongSidedCands.empty();
  10706. }
  10707. return DeferHint;
  10708. }
  10709. /// When overload resolution fails, prints diagnostic messages containing the
  10710. /// candidates in the candidate set.
  10711. void OverloadCandidateSet::NoteCandidates(
  10712. PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
  10713. ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
  10714. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  10715. auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
  10716. S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
  10717. NoteCandidates(S, Args, Cands, Opc, OpLoc);
  10718. if (OCD == OCD_AmbiguousCandidates)
  10719. MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
  10720. }
  10721. void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
  10722. ArrayRef<OverloadCandidate *> Cands,
  10723. StringRef Opc, SourceLocation OpLoc) {
  10724. bool ReportedAmbiguousConversions = false;
  10725. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  10726. unsigned CandsShown = 0;
  10727. auto I = Cands.begin(), E = Cands.end();
  10728. for (; I != E; ++I) {
  10729. OverloadCandidate *Cand = *I;
  10730. if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
  10731. ShowOverloads == Ovl_Best) {
  10732. break;
  10733. }
  10734. ++CandsShown;
  10735. if (Cand->Function)
  10736. NoteFunctionCandidate(S, Cand, Args.size(),
  10737. /*TakingCandidateAddress=*/false, DestAS);
  10738. else if (Cand->IsSurrogate)
  10739. NoteSurrogateCandidate(S, Cand);
  10740. else {
  10741. assert(Cand->Viable &&
  10742. "Non-viable built-in candidates are not added to Cands.");
  10743. // Generally we only see ambiguities including viable builtin
  10744. // operators if overload resolution got screwed up by an
  10745. // ambiguous user-defined conversion.
  10746. //
  10747. // FIXME: It's quite possible for different conversions to see
  10748. // different ambiguities, though.
  10749. if (!ReportedAmbiguousConversions) {
  10750. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  10751. ReportedAmbiguousConversions = true;
  10752. }
  10753. // If this is a viable builtin, print it.
  10754. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  10755. }
  10756. }
  10757. // Inform S.Diags that we've shown an overload set with N elements. This may
  10758. // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
  10759. S.Diags.overloadCandidatesShown(CandsShown);
  10760. if (I != E)
  10761. S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
  10762. shouldDeferDiags(S, Args, OpLoc))
  10763. << int(E - I);
  10764. }
  10765. static SourceLocation
  10766. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  10767. return Cand->Specialization ? Cand->Specialization->getLocation()
  10768. : SourceLocation();
  10769. }
  10770. namespace {
  10771. struct CompareTemplateSpecCandidatesForDisplay {
  10772. Sema &S;
  10773. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  10774. bool operator()(const TemplateSpecCandidate *L,
  10775. const TemplateSpecCandidate *R) {
  10776. // Fast-path this check.
  10777. if (L == R)
  10778. return false;
  10779. // Assuming that both candidates are not matches...
  10780. // Sort by the ranking of deduction failures.
  10781. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  10782. return RankDeductionFailure(L->DeductionFailure) <
  10783. RankDeductionFailure(R->DeductionFailure);
  10784. // Sort everything else by location.
  10785. SourceLocation LLoc = GetLocationForCandidate(L);
  10786. SourceLocation RLoc = GetLocationForCandidate(R);
  10787. // Put candidates without locations (e.g. builtins) at the end.
  10788. if (LLoc.isInvalid())
  10789. return false;
  10790. if (RLoc.isInvalid())
  10791. return true;
  10792. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  10793. }
  10794. };
  10795. }
  10796. /// Diagnose a template argument deduction failure.
  10797. /// We are treating these failures as overload failures due to bad
  10798. /// deductions.
  10799. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
  10800. bool ForTakingAddress) {
  10801. DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
  10802. DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
  10803. }
  10804. void TemplateSpecCandidateSet::destroyCandidates() {
  10805. for (iterator i = begin(), e = end(); i != e; ++i) {
  10806. i->DeductionFailure.Destroy();
  10807. }
  10808. }
  10809. void TemplateSpecCandidateSet::clear() {
  10810. destroyCandidates();
  10811. Candidates.clear();
  10812. }
  10813. /// NoteCandidates - When no template specialization match is found, prints
  10814. /// diagnostic messages containing the non-matching specializations that form
  10815. /// the candidate set.
  10816. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  10817. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  10818. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  10819. // Sort the candidates by position (assuming no candidate is a match).
  10820. // Sorting directly would be prohibitive, so we make a set of pointers
  10821. // and sort those.
  10822. SmallVector<TemplateSpecCandidate *, 32> Cands;
  10823. Cands.reserve(size());
  10824. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  10825. if (Cand->Specialization)
  10826. Cands.push_back(Cand);
  10827. // Otherwise, this is a non-matching builtin candidate. We do not,
  10828. // in general, want to list every possible builtin candidate.
  10829. }
  10830. llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
  10831. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  10832. // for generalization purposes (?).
  10833. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  10834. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  10835. unsigned CandsShown = 0;
  10836. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  10837. TemplateSpecCandidate *Cand = *I;
  10838. // Set an arbitrary limit on the number of candidates we'll spam
  10839. // the user with. FIXME: This limit should depend on details of the
  10840. // candidate list.
  10841. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  10842. break;
  10843. ++CandsShown;
  10844. assert(Cand->Specialization &&
  10845. "Non-matching built-in candidates are not added to Cands.");
  10846. Cand->NoteDeductionFailure(S, ForTakingAddress);
  10847. }
  10848. if (I != E)
  10849. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  10850. }
  10851. // [PossiblyAFunctionType] --> [Return]
  10852. // NonFunctionType --> NonFunctionType
  10853. // R (A) --> R(A)
  10854. // R (*)(A) --> R (A)
  10855. // R (&)(A) --> R (A)
  10856. // R (S::*)(A) --> R (A)
  10857. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  10858. QualType Ret = PossiblyAFunctionType;
  10859. if (const PointerType *ToTypePtr =
  10860. PossiblyAFunctionType->getAs<PointerType>())
  10861. Ret = ToTypePtr->getPointeeType();
  10862. else if (const ReferenceType *ToTypeRef =
  10863. PossiblyAFunctionType->getAs<ReferenceType>())
  10864. Ret = ToTypeRef->getPointeeType();
  10865. else if (const MemberPointerType *MemTypePtr =
  10866. PossiblyAFunctionType->getAs<MemberPointerType>())
  10867. Ret = MemTypePtr->getPointeeType();
  10868. Ret =
  10869. Context.getCanonicalType(Ret).getUnqualifiedType();
  10870. return Ret;
  10871. }
  10872. static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
  10873. bool Complain = true) {
  10874. if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  10875. S.DeduceReturnType(FD, Loc, Complain))
  10876. return true;
  10877. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  10878. if (S.getLangOpts().CPlusPlus17 &&
  10879. isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  10880. !S.ResolveExceptionSpec(Loc, FPT))
  10881. return true;
  10882. return false;
  10883. }
  10884. namespace {
  10885. // A helper class to help with address of function resolution
  10886. // - allows us to avoid passing around all those ugly parameters
  10887. class AddressOfFunctionResolver {
  10888. Sema& S;
  10889. Expr* SourceExpr;
  10890. const QualType& TargetType;
  10891. QualType TargetFunctionType; // Extracted function type from target type
  10892. bool Complain;
  10893. //DeclAccessPair& ResultFunctionAccessPair;
  10894. ASTContext& Context;
  10895. bool TargetTypeIsNonStaticMemberFunction;
  10896. bool FoundNonTemplateFunction;
  10897. bool StaticMemberFunctionFromBoundPointer;
  10898. bool HasComplained;
  10899. OverloadExpr::FindResult OvlExprInfo;
  10900. OverloadExpr *OvlExpr;
  10901. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  10902. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  10903. TemplateSpecCandidateSet FailedCandidates;
  10904. public:
  10905. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  10906. const QualType &TargetType, bool Complain)
  10907. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  10908. Complain(Complain), Context(S.getASTContext()),
  10909. TargetTypeIsNonStaticMemberFunction(
  10910. !!TargetType->getAs<MemberPointerType>()),
  10911. FoundNonTemplateFunction(false),
  10912. StaticMemberFunctionFromBoundPointer(false),
  10913. HasComplained(false),
  10914. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  10915. OvlExpr(OvlExprInfo.Expression),
  10916. FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
  10917. ExtractUnqualifiedFunctionTypeFromTargetType();
  10918. if (TargetFunctionType->isFunctionType()) {
  10919. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  10920. if (!UME->isImplicitAccess() &&
  10921. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  10922. StaticMemberFunctionFromBoundPointer = true;
  10923. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  10924. DeclAccessPair dap;
  10925. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  10926. OvlExpr, false, &dap)) {
  10927. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  10928. if (!Method->isStatic()) {
  10929. // If the target type is a non-function type and the function found
  10930. // is a non-static member function, pretend as if that was the
  10931. // target, it's the only possible type to end up with.
  10932. TargetTypeIsNonStaticMemberFunction = true;
  10933. // And skip adding the function if its not in the proper form.
  10934. // We'll diagnose this due to an empty set of functions.
  10935. if (!OvlExprInfo.HasFormOfMemberPointer)
  10936. return;
  10937. }
  10938. Matches.push_back(std::make_pair(dap, Fn));
  10939. }
  10940. return;
  10941. }
  10942. if (OvlExpr->hasExplicitTemplateArgs())
  10943. OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
  10944. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  10945. // C++ [over.over]p4:
  10946. // If more than one function is selected, [...]
  10947. if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
  10948. if (FoundNonTemplateFunction)
  10949. EliminateAllTemplateMatches();
  10950. else
  10951. EliminateAllExceptMostSpecializedTemplate();
  10952. }
  10953. }
  10954. if (S.getLangOpts().CUDA && Matches.size() > 1)
  10955. EliminateSuboptimalCudaMatches();
  10956. }
  10957. bool hasComplained() const { return HasComplained; }
  10958. private:
  10959. bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
  10960. QualType Discard;
  10961. return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
  10962. S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
  10963. }
  10964. /// \return true if A is considered a better overload candidate for the
  10965. /// desired type than B.
  10966. bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
  10967. // If A doesn't have exactly the correct type, we don't want to classify it
  10968. // as "better" than anything else. This way, the user is required to
  10969. // disambiguate for us if there are multiple candidates and no exact match.
  10970. return candidateHasExactlyCorrectType(A) &&
  10971. (!candidateHasExactlyCorrectType(B) ||
  10972. compareEnableIfAttrs(S, A, B) == Comparison::Better);
  10973. }
  10974. /// \return true if we were able to eliminate all but one overload candidate,
  10975. /// false otherwise.
  10976. bool eliminiateSuboptimalOverloadCandidates() {
  10977. // Same algorithm as overload resolution -- one pass to pick the "best",
  10978. // another pass to be sure that nothing is better than the best.
  10979. auto Best = Matches.begin();
  10980. for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
  10981. if (isBetterCandidate(I->second, Best->second))
  10982. Best = I;
  10983. const FunctionDecl *BestFn = Best->second;
  10984. auto IsBestOrInferiorToBest = [this, BestFn](
  10985. const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
  10986. return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
  10987. };
  10988. // Note: We explicitly leave Matches unmodified if there isn't a clear best
  10989. // option, so we can potentially give the user a better error
  10990. if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
  10991. return false;
  10992. Matches[0] = *Best;
  10993. Matches.resize(1);
  10994. return true;
  10995. }
  10996. bool isTargetTypeAFunction() const {
  10997. return TargetFunctionType->isFunctionType();
  10998. }
  10999. // [ToType] [Return]
  11000. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  11001. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  11002. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  11003. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  11004. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  11005. }
  11006. // return true if any matching specializations were found
  11007. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  11008. const DeclAccessPair& CurAccessFunPair) {
  11009. if (CXXMethodDecl *Method
  11010. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  11011. // Skip non-static function templates when converting to pointer, and
  11012. // static when converting to member pointer.
  11013. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  11014. return false;
  11015. }
  11016. else if (TargetTypeIsNonStaticMemberFunction)
  11017. return false;
  11018. // C++ [over.over]p2:
  11019. // If the name is a function template, template argument deduction is
  11020. // done (14.8.2.2), and if the argument deduction succeeds, the
  11021. // resulting template argument list is used to generate a single
  11022. // function template specialization, which is added to the set of
  11023. // overloaded functions considered.
  11024. FunctionDecl *Specialization = nullptr;
  11025. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  11026. if (Sema::TemplateDeductionResult Result
  11027. = S.DeduceTemplateArguments(FunctionTemplate,
  11028. &OvlExplicitTemplateArgs,
  11029. TargetFunctionType, Specialization,
  11030. Info, /*IsAddressOfFunction*/true)) {
  11031. // Make a note of the failed deduction for diagnostics.
  11032. FailedCandidates.addCandidate()
  11033. .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
  11034. MakeDeductionFailureInfo(Context, Result, Info));
  11035. return false;
  11036. }
  11037. // Template argument deduction ensures that we have an exact match or
  11038. // compatible pointer-to-function arguments that would be adjusted by ICS.
  11039. // This function template specicalization works.
  11040. assert(S.isSameOrCompatibleFunctionType(
  11041. Context.getCanonicalType(Specialization->getType()),
  11042. Context.getCanonicalType(TargetFunctionType)));
  11043. if (!S.checkAddressOfFunctionIsAvailable(Specialization))
  11044. return false;
  11045. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  11046. return true;
  11047. }
  11048. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  11049. const DeclAccessPair& CurAccessFunPair) {
  11050. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  11051. // Skip non-static functions when converting to pointer, and static
  11052. // when converting to member pointer.
  11053. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  11054. return false;
  11055. }
  11056. else if (TargetTypeIsNonStaticMemberFunction)
  11057. return false;
  11058. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  11059. if (S.getLangOpts().CUDA)
  11060. if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
  11061. if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
  11062. return false;
  11063. if (FunDecl->isMultiVersion()) {
  11064. const auto *TA = FunDecl->getAttr<TargetAttr>();
  11065. if (TA && !TA->isDefaultVersion())
  11066. return false;
  11067. const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
  11068. if (TVA && !TVA->isDefaultVersion())
  11069. return false;
  11070. }
  11071. // If any candidate has a placeholder return type, trigger its deduction
  11072. // now.
  11073. if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
  11074. Complain)) {
  11075. HasComplained |= Complain;
  11076. return false;
  11077. }
  11078. if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
  11079. return false;
  11080. // If we're in C, we need to support types that aren't exactly identical.
  11081. if (!S.getLangOpts().CPlusPlus ||
  11082. candidateHasExactlyCorrectType(FunDecl)) {
  11083. Matches.push_back(std::make_pair(
  11084. CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  11085. FoundNonTemplateFunction = true;
  11086. return true;
  11087. }
  11088. }
  11089. return false;
  11090. }
  11091. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  11092. bool Ret = false;
  11093. // If the overload expression doesn't have the form of a pointer to
  11094. // member, don't try to convert it to a pointer-to-member type.
  11095. if (IsInvalidFormOfPointerToMemberFunction())
  11096. return false;
  11097. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  11098. E = OvlExpr->decls_end();
  11099. I != E; ++I) {
  11100. // Look through any using declarations to find the underlying function.
  11101. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  11102. // C++ [over.over]p3:
  11103. // Non-member functions and static member functions match
  11104. // targets of type "pointer-to-function" or "reference-to-function."
  11105. // Nonstatic member functions match targets of
  11106. // type "pointer-to-member-function."
  11107. // Note that according to DR 247, the containing class does not matter.
  11108. if (FunctionTemplateDecl *FunctionTemplate
  11109. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  11110. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  11111. Ret = true;
  11112. }
  11113. // If we have explicit template arguments supplied, skip non-templates.
  11114. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  11115. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  11116. Ret = true;
  11117. }
  11118. assert(Ret || Matches.empty());
  11119. return Ret;
  11120. }
  11121. void EliminateAllExceptMostSpecializedTemplate() {
  11122. // [...] and any given function template specialization F1 is
  11123. // eliminated if the set contains a second function template
  11124. // specialization whose function template is more specialized
  11125. // than the function template of F1 according to the partial
  11126. // ordering rules of 14.5.5.2.
  11127. // The algorithm specified above is quadratic. We instead use a
  11128. // two-pass algorithm (similar to the one used to identify the
  11129. // best viable function in an overload set) that identifies the
  11130. // best function template (if it exists).
  11131. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  11132. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  11133. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  11134. // TODO: It looks like FailedCandidates does not serve much purpose
  11135. // here, since the no_viable diagnostic has index 0.
  11136. UnresolvedSetIterator Result = S.getMostSpecialized(
  11137. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  11138. SourceExpr->getBeginLoc(), S.PDiag(),
  11139. S.PDiag(diag::err_addr_ovl_ambiguous)
  11140. << Matches[0].second->getDeclName(),
  11141. S.PDiag(diag::note_ovl_candidate)
  11142. << (unsigned)oc_function << (unsigned)ocs_described_template,
  11143. Complain, TargetFunctionType);
  11144. if (Result != MatchesCopy.end()) {
  11145. // Make it the first and only element
  11146. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  11147. Matches[0].second = cast<FunctionDecl>(*Result);
  11148. Matches.resize(1);
  11149. } else
  11150. HasComplained |= Complain;
  11151. }
  11152. void EliminateAllTemplateMatches() {
  11153. // [...] any function template specializations in the set are
  11154. // eliminated if the set also contains a non-template function, [...]
  11155. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  11156. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  11157. ++I;
  11158. else {
  11159. Matches[I] = Matches[--N];
  11160. Matches.resize(N);
  11161. }
  11162. }
  11163. }
  11164. void EliminateSuboptimalCudaMatches() {
  11165. S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
  11166. Matches);
  11167. }
  11168. public:
  11169. void ComplainNoMatchesFound() const {
  11170. assert(Matches.empty());
  11171. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
  11172. << OvlExpr->getName() << TargetFunctionType
  11173. << OvlExpr->getSourceRange();
  11174. if (FailedCandidates.empty())
  11175. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  11176. /*TakingAddress=*/true);
  11177. else {
  11178. // We have some deduction failure messages. Use them to diagnose
  11179. // the function templates, and diagnose the non-template candidates
  11180. // normally.
  11181. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  11182. IEnd = OvlExpr->decls_end();
  11183. I != IEnd; ++I)
  11184. if (FunctionDecl *Fun =
  11185. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  11186. if (!functionHasPassObjectSizeParams(Fun))
  11187. S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
  11188. /*TakingAddress=*/true);
  11189. FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
  11190. }
  11191. }
  11192. bool IsInvalidFormOfPointerToMemberFunction() const {
  11193. return TargetTypeIsNonStaticMemberFunction &&
  11194. !OvlExprInfo.HasFormOfMemberPointer;
  11195. }
  11196. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  11197. // TODO: Should we condition this on whether any functions might
  11198. // have matched, or is it more appropriate to do that in callers?
  11199. // TODO: a fixit wouldn't hurt.
  11200. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  11201. << TargetType << OvlExpr->getSourceRange();
  11202. }
  11203. bool IsStaticMemberFunctionFromBoundPointer() const {
  11204. return StaticMemberFunctionFromBoundPointer;
  11205. }
  11206. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  11207. S.Diag(OvlExpr->getBeginLoc(),
  11208. diag::err_invalid_form_pointer_member_function)
  11209. << OvlExpr->getSourceRange();
  11210. }
  11211. void ComplainOfInvalidConversion() const {
  11212. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
  11213. << OvlExpr->getName() << TargetType;
  11214. }
  11215. void ComplainMultipleMatchesFound() const {
  11216. assert(Matches.size() > 1);
  11217. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
  11218. << OvlExpr->getName() << OvlExpr->getSourceRange();
  11219. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  11220. /*TakingAddress=*/true);
  11221. }
  11222. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  11223. int getNumMatches() const { return Matches.size(); }
  11224. FunctionDecl* getMatchingFunctionDecl() const {
  11225. if (Matches.size() != 1) return nullptr;
  11226. return Matches[0].second;
  11227. }
  11228. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  11229. if (Matches.size() != 1) return nullptr;
  11230. return &Matches[0].first;
  11231. }
  11232. };
  11233. }
  11234. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  11235. /// an overloaded function (C++ [over.over]), where @p From is an
  11236. /// expression with overloaded function type and @p ToType is the type
  11237. /// we're trying to resolve to. For example:
  11238. ///
  11239. /// @code
  11240. /// int f(double);
  11241. /// int f(int);
  11242. ///
  11243. /// int (*pfd)(double) = f; // selects f(double)
  11244. /// @endcode
  11245. ///
  11246. /// This routine returns the resulting FunctionDecl if it could be
  11247. /// resolved, and NULL otherwise. When @p Complain is true, this
  11248. /// routine will emit diagnostics if there is an error.
  11249. FunctionDecl *
  11250. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  11251. QualType TargetType,
  11252. bool Complain,
  11253. DeclAccessPair &FoundResult,
  11254. bool *pHadMultipleCandidates) {
  11255. assert(AddressOfExpr->getType() == Context.OverloadTy);
  11256. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  11257. Complain);
  11258. int NumMatches = Resolver.getNumMatches();
  11259. FunctionDecl *Fn = nullptr;
  11260. bool ShouldComplain = Complain && !Resolver.hasComplained();
  11261. if (NumMatches == 0 && ShouldComplain) {
  11262. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  11263. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  11264. else
  11265. Resolver.ComplainNoMatchesFound();
  11266. }
  11267. else if (NumMatches > 1 && ShouldComplain)
  11268. Resolver.ComplainMultipleMatchesFound();
  11269. else if (NumMatches == 1) {
  11270. Fn = Resolver.getMatchingFunctionDecl();
  11271. assert(Fn);
  11272. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  11273. ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
  11274. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  11275. if (Complain) {
  11276. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  11277. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  11278. else
  11279. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  11280. }
  11281. }
  11282. if (pHadMultipleCandidates)
  11283. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  11284. return Fn;
  11285. }
  11286. /// Given an expression that refers to an overloaded function, try to
  11287. /// resolve that function to a single function that can have its address taken.
  11288. /// This will modify `Pair` iff it returns non-null.
  11289. ///
  11290. /// This routine can only succeed if from all of the candidates in the overload
  11291. /// set for SrcExpr that can have their addresses taken, there is one candidate
  11292. /// that is more constrained than the rest.
  11293. FunctionDecl *
  11294. Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
  11295. OverloadExpr::FindResult R = OverloadExpr::find(E);
  11296. OverloadExpr *Ovl = R.Expression;
  11297. bool IsResultAmbiguous = false;
  11298. FunctionDecl *Result = nullptr;
  11299. DeclAccessPair DAP;
  11300. SmallVector<FunctionDecl *, 2> AmbiguousDecls;
  11301. auto CheckMoreConstrained = [&](FunctionDecl *FD1,
  11302. FunctionDecl *FD2) -> std::optional<bool> {
  11303. if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
  11304. FD1 = MF;
  11305. if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
  11306. FD2 = MF;
  11307. SmallVector<const Expr *, 1> AC1, AC2;
  11308. FD1->getAssociatedConstraints(AC1);
  11309. FD2->getAssociatedConstraints(AC2);
  11310. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  11311. if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
  11312. return std::nullopt;
  11313. if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
  11314. return std::nullopt;
  11315. if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
  11316. return std::nullopt;
  11317. return AtLeastAsConstrained1;
  11318. };
  11319. // Don't use the AddressOfResolver because we're specifically looking for
  11320. // cases where we have one overload candidate that lacks
  11321. // enable_if/pass_object_size/...
  11322. for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
  11323. auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
  11324. if (!FD)
  11325. return nullptr;
  11326. if (!checkAddressOfFunctionIsAvailable(FD))
  11327. continue;
  11328. // We have more than one result - see if it is more constrained than the
  11329. // previous one.
  11330. if (Result) {
  11331. std::optional<bool> MoreConstrainedThanPrevious =
  11332. CheckMoreConstrained(FD, Result);
  11333. if (!MoreConstrainedThanPrevious) {
  11334. IsResultAmbiguous = true;
  11335. AmbiguousDecls.push_back(FD);
  11336. continue;
  11337. }
  11338. if (!*MoreConstrainedThanPrevious)
  11339. continue;
  11340. // FD is more constrained - replace Result with it.
  11341. }
  11342. IsResultAmbiguous = false;
  11343. DAP = I.getPair();
  11344. Result = FD;
  11345. }
  11346. if (IsResultAmbiguous)
  11347. return nullptr;
  11348. if (Result) {
  11349. SmallVector<const Expr *, 1> ResultAC;
  11350. // We skipped over some ambiguous declarations which might be ambiguous with
  11351. // the selected result.
  11352. for (FunctionDecl *Skipped : AmbiguousDecls)
  11353. if (!CheckMoreConstrained(Skipped, Result))
  11354. return nullptr;
  11355. Pair = DAP;
  11356. }
  11357. return Result;
  11358. }
  11359. /// Given an overloaded function, tries to turn it into a non-overloaded
  11360. /// function reference using resolveAddressOfSingleOverloadCandidate. This
  11361. /// will perform access checks, diagnose the use of the resultant decl, and, if
  11362. /// requested, potentially perform a function-to-pointer decay.
  11363. ///
  11364. /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
  11365. /// Otherwise, returns true. This may emit diagnostics and return true.
  11366. bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
  11367. ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
  11368. Expr *E = SrcExpr.get();
  11369. assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
  11370. DeclAccessPair DAP;
  11371. FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
  11372. if (!Found || Found->isCPUDispatchMultiVersion() ||
  11373. Found->isCPUSpecificMultiVersion())
  11374. return false;
  11375. // Emitting multiple diagnostics for a function that is both inaccessible and
  11376. // unavailable is consistent with our behavior elsewhere. So, always check
  11377. // for both.
  11378. DiagnoseUseOfDecl(Found, E->getExprLoc());
  11379. CheckAddressOfMemberAccess(E, DAP);
  11380. Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
  11381. if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
  11382. SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
  11383. else
  11384. SrcExpr = Fixed;
  11385. return true;
  11386. }
  11387. /// Given an expression that refers to an overloaded function, try to
  11388. /// resolve that overloaded function expression down to a single function.
  11389. ///
  11390. /// This routine can only resolve template-ids that refer to a single function
  11391. /// template, where that template-id refers to a single template whose template
  11392. /// arguments are either provided by the template-id or have defaults,
  11393. /// as described in C++0x [temp.arg.explicit]p3.
  11394. ///
  11395. /// If no template-ids are found, no diagnostics are emitted and NULL is
  11396. /// returned.
  11397. FunctionDecl *
  11398. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  11399. bool Complain,
  11400. DeclAccessPair *FoundResult) {
  11401. // C++ [over.over]p1:
  11402. // [...] [Note: any redundant set of parentheses surrounding the
  11403. // overloaded function name is ignored (5.1). ]
  11404. // C++ [over.over]p1:
  11405. // [...] The overloaded function name can be preceded by the &
  11406. // operator.
  11407. // If we didn't actually find any template-ids, we're done.
  11408. if (!ovl->hasExplicitTemplateArgs())
  11409. return nullptr;
  11410. TemplateArgumentListInfo ExplicitTemplateArgs;
  11411. ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
  11412. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  11413. // Look through all of the overloaded functions, searching for one
  11414. // whose type matches exactly.
  11415. FunctionDecl *Matched = nullptr;
  11416. for (UnresolvedSetIterator I = ovl->decls_begin(),
  11417. E = ovl->decls_end(); I != E; ++I) {
  11418. // C++0x [temp.arg.explicit]p3:
  11419. // [...] In contexts where deduction is done and fails, or in contexts
  11420. // where deduction is not done, if a template argument list is
  11421. // specified and it, along with any default template arguments,
  11422. // identifies a single function template specialization, then the
  11423. // template-id is an lvalue for the function template specialization.
  11424. FunctionTemplateDecl *FunctionTemplate
  11425. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  11426. // C++ [over.over]p2:
  11427. // If the name is a function template, template argument deduction is
  11428. // done (14.8.2.2), and if the argument deduction succeeds, the
  11429. // resulting template argument list is used to generate a single
  11430. // function template specialization, which is added to the set of
  11431. // overloaded functions considered.
  11432. FunctionDecl *Specialization = nullptr;
  11433. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  11434. if (TemplateDeductionResult Result
  11435. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  11436. Specialization, Info,
  11437. /*IsAddressOfFunction*/true)) {
  11438. // Make a note of the failed deduction for diagnostics.
  11439. // TODO: Actually use the failed-deduction info?
  11440. FailedCandidates.addCandidate()
  11441. .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
  11442. MakeDeductionFailureInfo(Context, Result, Info));
  11443. continue;
  11444. }
  11445. assert(Specialization && "no specialization and no error?");
  11446. // Multiple matches; we can't resolve to a single declaration.
  11447. if (Matched) {
  11448. if (Complain) {
  11449. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  11450. << ovl->getName();
  11451. NoteAllOverloadCandidates(ovl);
  11452. }
  11453. return nullptr;
  11454. }
  11455. Matched = Specialization;
  11456. if (FoundResult) *FoundResult = I.getPair();
  11457. }
  11458. if (Matched &&
  11459. completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
  11460. return nullptr;
  11461. return Matched;
  11462. }
  11463. // Resolve and fix an overloaded expression that can be resolved
  11464. // because it identifies a single function template specialization.
  11465. //
  11466. // Last three arguments should only be supplied if Complain = true
  11467. //
  11468. // Return true if it was logically possible to so resolve the
  11469. // expression, regardless of whether or not it succeeded. Always
  11470. // returns true if 'complain' is set.
  11471. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  11472. ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
  11473. SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
  11474. unsigned DiagIDForComplaining) {
  11475. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  11476. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  11477. DeclAccessPair found;
  11478. ExprResult SingleFunctionExpression;
  11479. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  11480. ovl.Expression, /*complain*/ false, &found)) {
  11481. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
  11482. SrcExpr = ExprError();
  11483. return true;
  11484. }
  11485. // It is only correct to resolve to an instance method if we're
  11486. // resolving a form that's permitted to be a pointer to member.
  11487. // Otherwise we'll end up making a bound member expression, which
  11488. // is illegal in all the contexts we resolve like this.
  11489. if (!ovl.HasFormOfMemberPointer &&
  11490. isa<CXXMethodDecl>(fn) &&
  11491. cast<CXXMethodDecl>(fn)->isInstance()) {
  11492. if (!complain) return false;
  11493. Diag(ovl.Expression->getExprLoc(),
  11494. diag::err_bound_member_function)
  11495. << 0 << ovl.Expression->getSourceRange();
  11496. // TODO: I believe we only end up here if there's a mix of
  11497. // static and non-static candidates (otherwise the expression
  11498. // would have 'bound member' type, not 'overload' type).
  11499. // Ideally we would note which candidate was chosen and why
  11500. // the static candidates were rejected.
  11501. SrcExpr = ExprError();
  11502. return true;
  11503. }
  11504. // Fix the expression to refer to 'fn'.
  11505. SingleFunctionExpression =
  11506. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  11507. // If desired, do function-to-pointer decay.
  11508. if (doFunctionPointerConversion) {
  11509. SingleFunctionExpression =
  11510. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  11511. if (SingleFunctionExpression.isInvalid()) {
  11512. SrcExpr = ExprError();
  11513. return true;
  11514. }
  11515. }
  11516. }
  11517. if (!SingleFunctionExpression.isUsable()) {
  11518. if (complain) {
  11519. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  11520. << ovl.Expression->getName()
  11521. << DestTypeForComplaining
  11522. << OpRangeForComplaining
  11523. << ovl.Expression->getQualifierLoc().getSourceRange();
  11524. NoteAllOverloadCandidates(SrcExpr.get());
  11525. SrcExpr = ExprError();
  11526. return true;
  11527. }
  11528. return false;
  11529. }
  11530. SrcExpr = SingleFunctionExpression;
  11531. return true;
  11532. }
  11533. /// Add a single candidate to the overload set.
  11534. static void AddOverloadedCallCandidate(Sema &S,
  11535. DeclAccessPair FoundDecl,
  11536. TemplateArgumentListInfo *ExplicitTemplateArgs,
  11537. ArrayRef<Expr *> Args,
  11538. OverloadCandidateSet &CandidateSet,
  11539. bool PartialOverloading,
  11540. bool KnownValid) {
  11541. NamedDecl *Callee = FoundDecl.getDecl();
  11542. if (isa<UsingShadowDecl>(Callee))
  11543. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  11544. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  11545. if (ExplicitTemplateArgs) {
  11546. assert(!KnownValid && "Explicit template arguments?");
  11547. return;
  11548. }
  11549. // Prevent ill-formed function decls to be added as overload candidates.
  11550. if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
  11551. return;
  11552. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  11553. /*SuppressUserConversions=*/false,
  11554. PartialOverloading);
  11555. return;
  11556. }
  11557. if (FunctionTemplateDecl *FuncTemplate
  11558. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  11559. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  11560. ExplicitTemplateArgs, Args, CandidateSet,
  11561. /*SuppressUserConversions=*/false,
  11562. PartialOverloading);
  11563. return;
  11564. }
  11565. assert(!KnownValid && "unhandled case in overloaded call candidate");
  11566. }
  11567. /// Add the overload candidates named by callee and/or found by argument
  11568. /// dependent lookup to the given overload set.
  11569. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  11570. ArrayRef<Expr *> Args,
  11571. OverloadCandidateSet &CandidateSet,
  11572. bool PartialOverloading) {
  11573. #ifndef NDEBUG
  11574. // Verify that ArgumentDependentLookup is consistent with the rules
  11575. // in C++0x [basic.lookup.argdep]p3:
  11576. //
  11577. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  11578. // and let Y be the lookup set produced by argument dependent
  11579. // lookup (defined as follows). If X contains
  11580. //
  11581. // -- a declaration of a class member, or
  11582. //
  11583. // -- a block-scope function declaration that is not a
  11584. // using-declaration, or
  11585. //
  11586. // -- a declaration that is neither a function or a function
  11587. // template
  11588. //
  11589. // then Y is empty.
  11590. if (ULE->requiresADL()) {
  11591. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  11592. E = ULE->decls_end(); I != E; ++I) {
  11593. assert(!(*I)->getDeclContext()->isRecord());
  11594. assert(isa<UsingShadowDecl>(*I) ||
  11595. !(*I)->getDeclContext()->isFunctionOrMethod());
  11596. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  11597. }
  11598. }
  11599. #endif
  11600. // It would be nice to avoid this copy.
  11601. TemplateArgumentListInfo TABuffer;
  11602. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  11603. if (ULE->hasExplicitTemplateArgs()) {
  11604. ULE->copyTemplateArgumentsInto(TABuffer);
  11605. ExplicitTemplateArgs = &TABuffer;
  11606. }
  11607. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  11608. E = ULE->decls_end(); I != E; ++I)
  11609. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  11610. CandidateSet, PartialOverloading,
  11611. /*KnownValid*/ true);
  11612. if (ULE->requiresADL())
  11613. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  11614. Args, ExplicitTemplateArgs,
  11615. CandidateSet, PartialOverloading);
  11616. }
  11617. /// Add the call candidates from the given set of lookup results to the given
  11618. /// overload set. Non-function lookup results are ignored.
  11619. void Sema::AddOverloadedCallCandidates(
  11620. LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
  11621. ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
  11622. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  11623. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  11624. CandidateSet, false, /*KnownValid*/ false);
  11625. }
  11626. /// Determine whether a declaration with the specified name could be moved into
  11627. /// a different namespace.
  11628. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  11629. switch (Name.getCXXOverloadedOperator()) {
  11630. case OO_New: case OO_Array_New:
  11631. case OO_Delete: case OO_Array_Delete:
  11632. return false;
  11633. default:
  11634. return true;
  11635. }
  11636. }
  11637. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  11638. /// template, where the non-dependent name was declared after the template
  11639. /// was defined. This is common in code written for a compilers which do not
  11640. /// correctly implement two-stage name lookup.
  11641. ///
  11642. /// Returns true if a viable candidate was found and a diagnostic was issued.
  11643. static bool DiagnoseTwoPhaseLookup(
  11644. Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
  11645. LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
  11646. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  11647. CXXRecordDecl **FoundInClass = nullptr) {
  11648. if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
  11649. return false;
  11650. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  11651. if (DC->isTransparentContext())
  11652. continue;
  11653. SemaRef.LookupQualifiedName(R, DC);
  11654. if (!R.empty()) {
  11655. R.suppressDiagnostics();
  11656. OverloadCandidateSet Candidates(FnLoc, CSK);
  11657. SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
  11658. Candidates);
  11659. OverloadCandidateSet::iterator Best;
  11660. OverloadingResult OR =
  11661. Candidates.BestViableFunction(SemaRef, FnLoc, Best);
  11662. if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
  11663. // We either found non-function declarations or a best viable function
  11664. // at class scope. A class-scope lookup result disables ADL. Don't
  11665. // look past this, but let the caller know that we found something that
  11666. // either is, or might be, usable in this class.
  11667. if (FoundInClass) {
  11668. *FoundInClass = RD;
  11669. if (OR == OR_Success) {
  11670. R.clear();
  11671. R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
  11672. R.resolveKind();
  11673. }
  11674. }
  11675. return false;
  11676. }
  11677. if (OR != OR_Success) {
  11678. // There wasn't a unique best function or function template.
  11679. return false;
  11680. }
  11681. // Find the namespaces where ADL would have looked, and suggest
  11682. // declaring the function there instead.
  11683. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  11684. Sema::AssociatedClassSet AssociatedClasses;
  11685. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  11686. AssociatedNamespaces,
  11687. AssociatedClasses);
  11688. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  11689. if (canBeDeclaredInNamespace(R.getLookupName())) {
  11690. DeclContext *Std = SemaRef.getStdNamespace();
  11691. for (Sema::AssociatedNamespaceSet::iterator
  11692. it = AssociatedNamespaces.begin(),
  11693. end = AssociatedNamespaces.end(); it != end; ++it) {
  11694. // Never suggest declaring a function within namespace 'std'.
  11695. if (Std && Std->Encloses(*it))
  11696. continue;
  11697. // Never suggest declaring a function within a namespace with a
  11698. // reserved name, like __gnu_cxx.
  11699. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  11700. if (NS &&
  11701. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  11702. continue;
  11703. SuggestedNamespaces.insert(*it);
  11704. }
  11705. }
  11706. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  11707. << R.getLookupName();
  11708. if (SuggestedNamespaces.empty()) {
  11709. SemaRef.Diag(Best->Function->getLocation(),
  11710. diag::note_not_found_by_two_phase_lookup)
  11711. << R.getLookupName() << 0;
  11712. } else if (SuggestedNamespaces.size() == 1) {
  11713. SemaRef.Diag(Best->Function->getLocation(),
  11714. diag::note_not_found_by_two_phase_lookup)
  11715. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  11716. } else {
  11717. // FIXME: It would be useful to list the associated namespaces here,
  11718. // but the diagnostics infrastructure doesn't provide a way to produce
  11719. // a localized representation of a list of items.
  11720. SemaRef.Diag(Best->Function->getLocation(),
  11721. diag::note_not_found_by_two_phase_lookup)
  11722. << R.getLookupName() << 2;
  11723. }
  11724. // Try to recover by calling this function.
  11725. return true;
  11726. }
  11727. R.clear();
  11728. }
  11729. return false;
  11730. }
  11731. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  11732. /// template, where the non-dependent operator was declared after the template
  11733. /// was defined.
  11734. ///
  11735. /// Returns true if a viable candidate was found and a diagnostic was issued.
  11736. static bool
  11737. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  11738. SourceLocation OpLoc,
  11739. ArrayRef<Expr *> Args) {
  11740. DeclarationName OpName =
  11741. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  11742. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  11743. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  11744. OverloadCandidateSet::CSK_Operator,
  11745. /*ExplicitTemplateArgs=*/nullptr, Args);
  11746. }
  11747. namespace {
  11748. class BuildRecoveryCallExprRAII {
  11749. Sema &SemaRef;
  11750. Sema::SatisfactionStackResetRAII SatStack;
  11751. public:
  11752. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
  11753. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  11754. SemaRef.IsBuildingRecoveryCallExpr = true;
  11755. }
  11756. ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
  11757. };
  11758. }
  11759. /// Attempts to recover from a call where no functions were found.
  11760. ///
  11761. /// This function will do one of three things:
  11762. /// * Diagnose, recover, and return a recovery expression.
  11763. /// * Diagnose, fail to recover, and return ExprError().
  11764. /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
  11765. /// expected to diagnose as appropriate.
  11766. static ExprResult
  11767. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  11768. UnresolvedLookupExpr *ULE,
  11769. SourceLocation LParenLoc,
  11770. MutableArrayRef<Expr *> Args,
  11771. SourceLocation RParenLoc,
  11772. bool EmptyLookup, bool AllowTypoCorrection) {
  11773. // Do not try to recover if it is already building a recovery call.
  11774. // This stops infinite loops for template instantiations like
  11775. //
  11776. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  11777. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  11778. if (SemaRef.IsBuildingRecoveryCallExpr)
  11779. return ExprResult();
  11780. BuildRecoveryCallExprRAII RCE(SemaRef);
  11781. CXXScopeSpec SS;
  11782. SS.Adopt(ULE->getQualifierLoc());
  11783. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  11784. TemplateArgumentListInfo TABuffer;
  11785. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  11786. if (ULE->hasExplicitTemplateArgs()) {
  11787. ULE->copyTemplateArgumentsInto(TABuffer);
  11788. ExplicitTemplateArgs = &TABuffer;
  11789. }
  11790. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  11791. Sema::LookupOrdinaryName);
  11792. CXXRecordDecl *FoundInClass = nullptr;
  11793. if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
  11794. OverloadCandidateSet::CSK_Normal,
  11795. ExplicitTemplateArgs, Args, &FoundInClass)) {
  11796. // OK, diagnosed a two-phase lookup issue.
  11797. } else if (EmptyLookup) {
  11798. // Try to recover from an empty lookup with typo correction.
  11799. R.clear();
  11800. NoTypoCorrectionCCC NoTypoValidator{};
  11801. FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
  11802. ExplicitTemplateArgs != nullptr,
  11803. dyn_cast<MemberExpr>(Fn));
  11804. CorrectionCandidateCallback &Validator =
  11805. AllowTypoCorrection
  11806. ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
  11807. : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
  11808. if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
  11809. Args))
  11810. return ExprError();
  11811. } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
  11812. // We found a usable declaration of the name in a dependent base of some
  11813. // enclosing class.
  11814. // FIXME: We should also explain why the candidates found by name lookup
  11815. // were not viable.
  11816. if (SemaRef.DiagnoseDependentMemberLookup(R))
  11817. return ExprError();
  11818. } else {
  11819. // We had viable candidates and couldn't recover; let the caller diagnose
  11820. // this.
  11821. return ExprResult();
  11822. }
  11823. // If we get here, we should have issued a diagnostic and formed a recovery
  11824. // lookup result.
  11825. assert(!R.empty() && "lookup results empty despite recovery");
  11826. // If recovery created an ambiguity, just bail out.
  11827. if (R.isAmbiguous()) {
  11828. R.suppressDiagnostics();
  11829. return ExprError();
  11830. }
  11831. // Build an implicit member call if appropriate. Just drop the
  11832. // casts and such from the call, we don't really care.
  11833. ExprResult NewFn = ExprError();
  11834. if ((*R.begin())->isCXXClassMember())
  11835. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
  11836. ExplicitTemplateArgs, S);
  11837. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  11838. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  11839. ExplicitTemplateArgs);
  11840. else
  11841. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  11842. if (NewFn.isInvalid())
  11843. return ExprError();
  11844. // This shouldn't cause an infinite loop because we're giving it
  11845. // an expression with viable lookup results, which should never
  11846. // end up here.
  11847. return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  11848. MultiExprArg(Args.data(), Args.size()),
  11849. RParenLoc);
  11850. }
  11851. /// Constructs and populates an OverloadedCandidateSet from
  11852. /// the given function.
  11853. /// \returns true when an the ExprResult output parameter has been set.
  11854. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  11855. UnresolvedLookupExpr *ULE,
  11856. MultiExprArg Args,
  11857. SourceLocation RParenLoc,
  11858. OverloadCandidateSet *CandidateSet,
  11859. ExprResult *Result) {
  11860. #ifndef NDEBUG
  11861. if (ULE->requiresADL()) {
  11862. // To do ADL, we must have found an unqualified name.
  11863. assert(!ULE->getQualifier() && "qualified name with ADL");
  11864. // We don't perform ADL for implicit declarations of builtins.
  11865. // Verify that this was correctly set up.
  11866. FunctionDecl *F;
  11867. if (ULE->decls_begin() != ULE->decls_end() &&
  11868. ULE->decls_begin() + 1 == ULE->decls_end() &&
  11869. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  11870. F->getBuiltinID() && F->isImplicit())
  11871. llvm_unreachable("performing ADL for builtin");
  11872. // We don't perform ADL in C.
  11873. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  11874. }
  11875. #endif
  11876. UnbridgedCastsSet UnbridgedCasts;
  11877. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  11878. *Result = ExprError();
  11879. return true;
  11880. }
  11881. // Add the functions denoted by the callee to the set of candidate
  11882. // functions, including those from argument-dependent lookup.
  11883. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  11884. if (getLangOpts().MSVCCompat &&
  11885. CurContext->isDependentContext() && !isSFINAEContext() &&
  11886. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  11887. OverloadCandidateSet::iterator Best;
  11888. if (CandidateSet->empty() ||
  11889. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
  11890. OR_No_Viable_Function) {
  11891. // In Microsoft mode, if we are inside a template class member function
  11892. // then create a type dependent CallExpr. The goal is to postpone name
  11893. // lookup to instantiation time to be able to search into type dependent
  11894. // base classes.
  11895. CallExpr *CE =
  11896. CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
  11897. RParenLoc, CurFPFeatureOverrides());
  11898. CE->markDependentForPostponedNameLookup();
  11899. *Result = CE;
  11900. return true;
  11901. }
  11902. }
  11903. if (CandidateSet->empty())
  11904. return false;
  11905. UnbridgedCasts.restore();
  11906. return false;
  11907. }
  11908. // Guess at what the return type for an unresolvable overload should be.
  11909. static QualType chooseRecoveryType(OverloadCandidateSet &CS,
  11910. OverloadCandidateSet::iterator *Best) {
  11911. std::optional<QualType> Result;
  11912. // Adjust Type after seeing a candidate.
  11913. auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
  11914. if (!Candidate.Function)
  11915. return;
  11916. if (Candidate.Function->isInvalidDecl())
  11917. return;
  11918. QualType T = Candidate.Function->getReturnType();
  11919. if (T.isNull())
  11920. return;
  11921. if (!Result)
  11922. Result = T;
  11923. else if (Result != T)
  11924. Result = QualType();
  11925. };
  11926. // Look for an unambiguous type from a progressively larger subset.
  11927. // e.g. if types disagree, but all *viable* overloads return int, choose int.
  11928. //
  11929. // First, consider only the best candidate.
  11930. if (Best && *Best != CS.end())
  11931. ConsiderCandidate(**Best);
  11932. // Next, consider only viable candidates.
  11933. if (!Result)
  11934. for (const auto &C : CS)
  11935. if (C.Viable)
  11936. ConsiderCandidate(C);
  11937. // Finally, consider all candidates.
  11938. if (!Result)
  11939. for (const auto &C : CS)
  11940. ConsiderCandidate(C);
  11941. if (!Result)
  11942. return QualType();
  11943. auto Value = *Result;
  11944. if (Value.isNull() || Value->isUndeducedType())
  11945. return QualType();
  11946. return Value;
  11947. }
  11948. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  11949. /// the completed call expression. If overload resolution fails, emits
  11950. /// diagnostics and returns ExprError()
  11951. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  11952. UnresolvedLookupExpr *ULE,
  11953. SourceLocation LParenLoc,
  11954. MultiExprArg Args,
  11955. SourceLocation RParenLoc,
  11956. Expr *ExecConfig,
  11957. OverloadCandidateSet *CandidateSet,
  11958. OverloadCandidateSet::iterator *Best,
  11959. OverloadingResult OverloadResult,
  11960. bool AllowTypoCorrection) {
  11961. switch (OverloadResult) {
  11962. case OR_Success: {
  11963. FunctionDecl *FDecl = (*Best)->Function;
  11964. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  11965. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  11966. return ExprError();
  11967. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  11968. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  11969. ExecConfig, /*IsExecConfig=*/false,
  11970. (*Best)->IsADLCandidate);
  11971. }
  11972. case OR_No_Viable_Function: {
  11973. // Try to recover by looking for viable functions which the user might
  11974. // have meant to call.
  11975. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  11976. Args, RParenLoc,
  11977. CandidateSet->empty(),
  11978. AllowTypoCorrection);
  11979. if (Recovery.isInvalid() || Recovery.isUsable())
  11980. return Recovery;
  11981. // If the user passes in a function that we can't take the address of, we
  11982. // generally end up emitting really bad error messages. Here, we attempt to
  11983. // emit better ones.
  11984. for (const Expr *Arg : Args) {
  11985. if (!Arg->getType()->isFunctionType())
  11986. continue;
  11987. if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
  11988. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  11989. if (FD &&
  11990. !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  11991. Arg->getExprLoc()))
  11992. return ExprError();
  11993. }
  11994. }
  11995. CandidateSet->NoteCandidates(
  11996. PartialDiagnosticAt(
  11997. Fn->getBeginLoc(),
  11998. SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
  11999. << ULE->getName() << Fn->getSourceRange()),
  12000. SemaRef, OCD_AllCandidates, Args);
  12001. break;
  12002. }
  12003. case OR_Ambiguous:
  12004. CandidateSet->NoteCandidates(
  12005. PartialDiagnosticAt(Fn->getBeginLoc(),
  12006. SemaRef.PDiag(diag::err_ovl_ambiguous_call)
  12007. << ULE->getName() << Fn->getSourceRange()),
  12008. SemaRef, OCD_AmbiguousCandidates, Args);
  12009. break;
  12010. case OR_Deleted: {
  12011. CandidateSet->NoteCandidates(
  12012. PartialDiagnosticAt(Fn->getBeginLoc(),
  12013. SemaRef.PDiag(diag::err_ovl_deleted_call)
  12014. << ULE->getName() << Fn->getSourceRange()),
  12015. SemaRef, OCD_AllCandidates, Args);
  12016. // We emitted an error for the unavailable/deleted function call but keep
  12017. // the call in the AST.
  12018. FunctionDecl *FDecl = (*Best)->Function;
  12019. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  12020. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  12021. ExecConfig, /*IsExecConfig=*/false,
  12022. (*Best)->IsADLCandidate);
  12023. }
  12024. }
  12025. // Overload resolution failed, try to recover.
  12026. SmallVector<Expr *, 8> SubExprs = {Fn};
  12027. SubExprs.append(Args.begin(), Args.end());
  12028. return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
  12029. chooseRecoveryType(*CandidateSet, Best));
  12030. }
  12031. static void markUnaddressableCandidatesUnviable(Sema &S,
  12032. OverloadCandidateSet &CS) {
  12033. for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
  12034. if (I->Viable &&
  12035. !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
  12036. I->Viable = false;
  12037. I->FailureKind = ovl_fail_addr_not_available;
  12038. }
  12039. }
  12040. }
  12041. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  12042. /// (which eventually refers to the declaration Func) and the call
  12043. /// arguments Args/NumArgs, attempt to resolve the function call down
  12044. /// to a specific function. If overload resolution succeeds, returns
  12045. /// the call expression produced by overload resolution.
  12046. /// Otherwise, emits diagnostics and returns ExprError.
  12047. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  12048. UnresolvedLookupExpr *ULE,
  12049. SourceLocation LParenLoc,
  12050. MultiExprArg Args,
  12051. SourceLocation RParenLoc,
  12052. Expr *ExecConfig,
  12053. bool AllowTypoCorrection,
  12054. bool CalleesAddressIsTaken) {
  12055. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  12056. OverloadCandidateSet::CSK_Normal);
  12057. ExprResult result;
  12058. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  12059. &result))
  12060. return result;
  12061. // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
  12062. // functions that aren't addressible are considered unviable.
  12063. if (CalleesAddressIsTaken)
  12064. markUnaddressableCandidatesUnviable(*this, CandidateSet);
  12065. OverloadCandidateSet::iterator Best;
  12066. OverloadingResult OverloadResult =
  12067. CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
  12068. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
  12069. ExecConfig, &CandidateSet, &Best,
  12070. OverloadResult, AllowTypoCorrection);
  12071. }
  12072. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  12073. return Functions.size() > 1 ||
  12074. (Functions.size() == 1 &&
  12075. isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
  12076. }
  12077. ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
  12078. NestedNameSpecifierLoc NNSLoc,
  12079. DeclarationNameInfo DNI,
  12080. const UnresolvedSetImpl &Fns,
  12081. bool PerformADL) {
  12082. return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
  12083. PerformADL, IsOverloaded(Fns),
  12084. Fns.begin(), Fns.end());
  12085. }
  12086. /// Create a unary operation that may resolve to an overloaded
  12087. /// operator.
  12088. ///
  12089. /// \param OpLoc The location of the operator itself (e.g., '*').
  12090. ///
  12091. /// \param Opc The UnaryOperatorKind that describes this operator.
  12092. ///
  12093. /// \param Fns The set of non-member functions that will be
  12094. /// considered by overload resolution. The caller needs to build this
  12095. /// set based on the context using, e.g.,
  12096. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  12097. /// set should not contain any member functions; those will be added
  12098. /// by CreateOverloadedUnaryOp().
  12099. ///
  12100. /// \param Input The input argument.
  12101. ExprResult
  12102. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
  12103. const UnresolvedSetImpl &Fns,
  12104. Expr *Input, bool PerformADL) {
  12105. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  12106. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  12107. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  12108. // TODO: provide better source location info.
  12109. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  12110. if (checkPlaceholderForOverload(*this, Input))
  12111. return ExprError();
  12112. Expr *Args[2] = { Input, nullptr };
  12113. unsigned NumArgs = 1;
  12114. // For post-increment and post-decrement, add the implicit '0' as
  12115. // the second argument, so that we know this is a post-increment or
  12116. // post-decrement.
  12117. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  12118. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  12119. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  12120. SourceLocation());
  12121. NumArgs = 2;
  12122. }
  12123. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  12124. if (Input->isTypeDependent()) {
  12125. if (Fns.empty())
  12126. return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
  12127. VK_PRValue, OK_Ordinary, OpLoc, false,
  12128. CurFPFeatureOverrides());
  12129. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  12130. ExprResult Fn = CreateUnresolvedLookupExpr(
  12131. NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
  12132. if (Fn.isInvalid())
  12133. return ExprError();
  12134. return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
  12135. Context.DependentTy, VK_PRValue, OpLoc,
  12136. CurFPFeatureOverrides());
  12137. }
  12138. // Build an empty overload set.
  12139. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  12140. // Add the candidates from the given function set.
  12141. AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
  12142. // Add operator candidates that are member functions.
  12143. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  12144. // Add candidates from ADL.
  12145. if (PerformADL) {
  12146. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  12147. /*ExplicitTemplateArgs*/nullptr,
  12148. CandidateSet);
  12149. }
  12150. // Add builtin operator candidates.
  12151. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  12152. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12153. // Perform overload resolution.
  12154. OverloadCandidateSet::iterator Best;
  12155. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  12156. case OR_Success: {
  12157. // We found a built-in operator or an overloaded operator.
  12158. FunctionDecl *FnDecl = Best->Function;
  12159. if (FnDecl) {
  12160. Expr *Base = nullptr;
  12161. // We matched an overloaded operator. Build a call to that
  12162. // operator.
  12163. // Convert the arguments.
  12164. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  12165. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  12166. ExprResult InputRes =
  12167. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  12168. Best->FoundDecl, Method);
  12169. if (InputRes.isInvalid())
  12170. return ExprError();
  12171. Base = Input = InputRes.get();
  12172. } else {
  12173. // Convert the arguments.
  12174. ExprResult InputInit
  12175. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  12176. Context,
  12177. FnDecl->getParamDecl(0)),
  12178. SourceLocation(),
  12179. Input);
  12180. if (InputInit.isInvalid())
  12181. return ExprError();
  12182. Input = InputInit.get();
  12183. }
  12184. // Build the actual expression node.
  12185. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  12186. Base, HadMultipleCandidates,
  12187. OpLoc);
  12188. if (FnExpr.isInvalid())
  12189. return ExprError();
  12190. // Determine the result type.
  12191. QualType ResultTy = FnDecl->getReturnType();
  12192. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12193. ResultTy = ResultTy.getNonLValueExprType(Context);
  12194. Args[0] = Input;
  12195. CallExpr *TheCall = CXXOperatorCallExpr::Create(
  12196. Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
  12197. CurFPFeatureOverrides(), Best->IsADLCandidate);
  12198. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  12199. return ExprError();
  12200. if (CheckFunctionCall(FnDecl, TheCall,
  12201. FnDecl->getType()->castAs<FunctionProtoType>()))
  12202. return ExprError();
  12203. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
  12204. } else {
  12205. // We matched a built-in operator. Convert the arguments, then
  12206. // break out so that we will build the appropriate built-in
  12207. // operator node.
  12208. ExprResult InputRes = PerformImplicitConversion(
  12209. Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
  12210. CCK_ForBuiltinOverloadedOp);
  12211. if (InputRes.isInvalid())
  12212. return ExprError();
  12213. Input = InputRes.get();
  12214. break;
  12215. }
  12216. }
  12217. case OR_No_Viable_Function:
  12218. // This is an erroneous use of an operator which can be overloaded by
  12219. // a non-member function. Check for non-member operators which were
  12220. // defined too late to be candidates.
  12221. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  12222. // FIXME: Recover by calling the found function.
  12223. return ExprError();
  12224. // No viable function; fall through to handling this as a
  12225. // built-in operator, which will produce an error message for us.
  12226. break;
  12227. case OR_Ambiguous:
  12228. CandidateSet.NoteCandidates(
  12229. PartialDiagnosticAt(OpLoc,
  12230. PDiag(diag::err_ovl_ambiguous_oper_unary)
  12231. << UnaryOperator::getOpcodeStr(Opc)
  12232. << Input->getType() << Input->getSourceRange()),
  12233. *this, OCD_AmbiguousCandidates, ArgsArray,
  12234. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  12235. return ExprError();
  12236. case OR_Deleted:
  12237. CandidateSet.NoteCandidates(
  12238. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  12239. << UnaryOperator::getOpcodeStr(Opc)
  12240. << Input->getSourceRange()),
  12241. *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
  12242. OpLoc);
  12243. return ExprError();
  12244. }
  12245. // Either we found no viable overloaded operator or we matched a
  12246. // built-in operator. In either case, fall through to trying to
  12247. // build a built-in operation.
  12248. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12249. }
  12250. /// Perform lookup for an overloaded binary operator.
  12251. void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
  12252. OverloadedOperatorKind Op,
  12253. const UnresolvedSetImpl &Fns,
  12254. ArrayRef<Expr *> Args, bool PerformADL) {
  12255. SourceLocation OpLoc = CandidateSet.getLocation();
  12256. OverloadedOperatorKind ExtraOp =
  12257. CandidateSet.getRewriteInfo().AllowRewrittenCandidates
  12258. ? getRewrittenOverloadedOperator(Op)
  12259. : OO_None;
  12260. // Add the candidates from the given function set. This also adds the
  12261. // rewritten candidates using these functions if necessary.
  12262. AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
  12263. // Add operator candidates that are member functions.
  12264. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  12265. if (CandidateSet.getRewriteInfo().allowsReversed(Op))
  12266. AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
  12267. OverloadCandidateParamOrder::Reversed);
  12268. // In C++20, also add any rewritten member candidates.
  12269. if (ExtraOp) {
  12270. AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
  12271. if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
  12272. AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
  12273. CandidateSet,
  12274. OverloadCandidateParamOrder::Reversed);
  12275. }
  12276. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  12277. // performed for an assignment operator (nor for operator[] nor operator->,
  12278. // which don't get here).
  12279. if (Op != OO_Equal && PerformADL) {
  12280. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  12281. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  12282. /*ExplicitTemplateArgs*/ nullptr,
  12283. CandidateSet);
  12284. if (ExtraOp) {
  12285. DeclarationName ExtraOpName =
  12286. Context.DeclarationNames.getCXXOperatorName(ExtraOp);
  12287. AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
  12288. /*ExplicitTemplateArgs*/ nullptr,
  12289. CandidateSet);
  12290. }
  12291. }
  12292. // Add builtin operator candidates.
  12293. //
  12294. // FIXME: We don't add any rewritten candidates here. This is strictly
  12295. // incorrect; a builtin candidate could be hidden by a non-viable candidate,
  12296. // resulting in our selecting a rewritten builtin candidate. For example:
  12297. //
  12298. // enum class E { e };
  12299. // bool operator!=(E, E) requires false;
  12300. // bool k = E::e != E::e;
  12301. //
  12302. // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
  12303. // it seems unreasonable to consider rewritten builtin candidates. A core
  12304. // issue has been filed proposing to removed this requirement.
  12305. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  12306. }
  12307. /// Create a binary operation that may resolve to an overloaded
  12308. /// operator.
  12309. ///
  12310. /// \param OpLoc The location of the operator itself (e.g., '+').
  12311. ///
  12312. /// \param Opc The BinaryOperatorKind that describes this operator.
  12313. ///
  12314. /// \param Fns The set of non-member functions that will be
  12315. /// considered by overload resolution. The caller needs to build this
  12316. /// set based on the context using, e.g.,
  12317. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  12318. /// set should not contain any member functions; those will be added
  12319. /// by CreateOverloadedBinOp().
  12320. ///
  12321. /// \param LHS Left-hand argument.
  12322. /// \param RHS Right-hand argument.
  12323. /// \param PerformADL Whether to consider operator candidates found by ADL.
  12324. /// \param AllowRewrittenCandidates Whether to consider candidates found by
  12325. /// C++20 operator rewrites.
  12326. /// \param DefaultedFn If we are synthesizing a defaulted operator function,
  12327. /// the function in question. Such a function is never a candidate in
  12328. /// our overload resolution. This also enables synthesizing a three-way
  12329. /// comparison from < and == as described in C++20 [class.spaceship]p1.
  12330. ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  12331. BinaryOperatorKind Opc,
  12332. const UnresolvedSetImpl &Fns, Expr *LHS,
  12333. Expr *RHS, bool PerformADL,
  12334. bool AllowRewrittenCandidates,
  12335. FunctionDecl *DefaultedFn) {
  12336. Expr *Args[2] = { LHS, RHS };
  12337. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  12338. if (!getLangOpts().CPlusPlus20)
  12339. AllowRewrittenCandidates = false;
  12340. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  12341. // If either side is type-dependent, create an appropriate dependent
  12342. // expression.
  12343. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  12344. if (Fns.empty()) {
  12345. // If there are no functions to store, just build a dependent
  12346. // BinaryOperator or CompoundAssignment.
  12347. if (BinaryOperator::isCompoundAssignmentOp(Opc))
  12348. return CompoundAssignOperator::Create(
  12349. Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
  12350. OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
  12351. Context.DependentTy);
  12352. return BinaryOperator::Create(
  12353. Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
  12354. OK_Ordinary, OpLoc, CurFPFeatureOverrides());
  12355. }
  12356. // FIXME: save results of ADL from here?
  12357. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  12358. // TODO: provide better source location info in DNLoc component.
  12359. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  12360. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  12361. ExprResult Fn = CreateUnresolvedLookupExpr(
  12362. NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
  12363. if (Fn.isInvalid())
  12364. return ExprError();
  12365. return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
  12366. Context.DependentTy, VK_PRValue, OpLoc,
  12367. CurFPFeatureOverrides());
  12368. }
  12369. // Always do placeholder-like conversions on the RHS.
  12370. if (checkPlaceholderForOverload(*this, Args[1]))
  12371. return ExprError();
  12372. // Do placeholder-like conversion on the LHS; note that we should
  12373. // not get here with a PseudoObject LHS.
  12374. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  12375. if (checkPlaceholderForOverload(*this, Args[0]))
  12376. return ExprError();
  12377. // If this is the assignment operator, we only perform overload resolution
  12378. // if the left-hand side is a class or enumeration type. This is actually
  12379. // a hack. The standard requires that we do overload resolution between the
  12380. // various built-in candidates, but as DR507 points out, this can lead to
  12381. // problems. So we do it this way, which pretty much follows what GCC does.
  12382. // Note that we go the traditional code path for compound assignment forms.
  12383. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  12384. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  12385. // If this is the .* operator, which is not overloadable, just
  12386. // create a built-in binary operator.
  12387. if (Opc == BO_PtrMemD)
  12388. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  12389. // Build the overload set.
  12390. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
  12391. OverloadCandidateSet::OperatorRewriteInfo(
  12392. Op, OpLoc, AllowRewrittenCandidates));
  12393. if (DefaultedFn)
  12394. CandidateSet.exclude(DefaultedFn);
  12395. LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
  12396. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12397. // Perform overload resolution.
  12398. OverloadCandidateSet::iterator Best;
  12399. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  12400. case OR_Success: {
  12401. // We found a built-in operator or an overloaded operator.
  12402. FunctionDecl *FnDecl = Best->Function;
  12403. bool IsReversed = Best->isReversed();
  12404. if (IsReversed)
  12405. std::swap(Args[0], Args[1]);
  12406. if (FnDecl) {
  12407. Expr *Base = nullptr;
  12408. // We matched an overloaded operator. Build a call to that
  12409. // operator.
  12410. OverloadedOperatorKind ChosenOp =
  12411. FnDecl->getDeclName().getCXXOverloadedOperator();
  12412. // C++2a [over.match.oper]p9:
  12413. // If a rewritten operator== candidate is selected by overload
  12414. // resolution for an operator@, its return type shall be cv bool
  12415. if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
  12416. !FnDecl->getReturnType()->isBooleanType()) {
  12417. bool IsExtension =
  12418. FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
  12419. Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
  12420. : diag::err_ovl_rewrite_equalequal_not_bool)
  12421. << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
  12422. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  12423. Diag(FnDecl->getLocation(), diag::note_declared_at);
  12424. if (!IsExtension)
  12425. return ExprError();
  12426. }
  12427. if (AllowRewrittenCandidates && !IsReversed &&
  12428. CandidateSet.getRewriteInfo().isReversible()) {
  12429. // We could have reversed this operator, but didn't. Check if some
  12430. // reversed form was a viable candidate, and if so, if it had a
  12431. // better conversion for either parameter. If so, this call is
  12432. // formally ambiguous, and allowing it is an extension.
  12433. llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
  12434. for (OverloadCandidate &Cand : CandidateSet) {
  12435. if (Cand.Viable && Cand.Function && Cand.isReversed() &&
  12436. haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
  12437. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  12438. if (CompareImplicitConversionSequences(
  12439. *this, OpLoc, Cand.Conversions[ArgIdx],
  12440. Best->Conversions[ArgIdx]) ==
  12441. ImplicitConversionSequence::Better) {
  12442. AmbiguousWith.push_back(Cand.Function);
  12443. break;
  12444. }
  12445. }
  12446. }
  12447. }
  12448. if (!AmbiguousWith.empty()) {
  12449. bool AmbiguousWithSelf =
  12450. AmbiguousWith.size() == 1 &&
  12451. declaresSameEntity(AmbiguousWith.front(), FnDecl);
  12452. Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
  12453. << BinaryOperator::getOpcodeStr(Opc)
  12454. << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
  12455. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  12456. if (AmbiguousWithSelf) {
  12457. Diag(FnDecl->getLocation(),
  12458. diag::note_ovl_ambiguous_oper_binary_reversed_self);
  12459. // Mark member== const or provide matching != to disallow reversed
  12460. // args. Eg.
  12461. // struct S { bool operator==(const S&); };
  12462. // S()==S();
  12463. if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
  12464. if (Op == OverloadedOperatorKind::OO_EqualEqual &&
  12465. !MD->isConst() &&
  12466. Context.hasSameUnqualifiedType(
  12467. MD->getThisObjectType(),
  12468. MD->getParamDecl(0)->getType().getNonReferenceType()) &&
  12469. Context.hasSameUnqualifiedType(MD->getThisObjectType(),
  12470. Args[0]->getType()) &&
  12471. Context.hasSameUnqualifiedType(MD->getThisObjectType(),
  12472. Args[1]->getType()))
  12473. Diag(FnDecl->getLocation(),
  12474. diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
  12475. } else {
  12476. Diag(FnDecl->getLocation(),
  12477. diag::note_ovl_ambiguous_oper_binary_selected_candidate);
  12478. for (auto *F : AmbiguousWith)
  12479. Diag(F->getLocation(),
  12480. diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
  12481. }
  12482. }
  12483. }
  12484. // Convert the arguments.
  12485. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  12486. // Best->Access is only meaningful for class members.
  12487. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  12488. ExprResult Arg1 =
  12489. PerformCopyInitialization(
  12490. InitializedEntity::InitializeParameter(Context,
  12491. FnDecl->getParamDecl(0)),
  12492. SourceLocation(), Args[1]);
  12493. if (Arg1.isInvalid())
  12494. return ExprError();
  12495. ExprResult Arg0 =
  12496. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  12497. Best->FoundDecl, Method);
  12498. if (Arg0.isInvalid())
  12499. return ExprError();
  12500. Base = Args[0] = Arg0.getAs<Expr>();
  12501. Args[1] = RHS = Arg1.getAs<Expr>();
  12502. } else {
  12503. // Convert the arguments.
  12504. ExprResult Arg0 = PerformCopyInitialization(
  12505. InitializedEntity::InitializeParameter(Context,
  12506. FnDecl->getParamDecl(0)),
  12507. SourceLocation(), Args[0]);
  12508. if (Arg0.isInvalid())
  12509. return ExprError();
  12510. ExprResult Arg1 =
  12511. PerformCopyInitialization(
  12512. InitializedEntity::InitializeParameter(Context,
  12513. FnDecl->getParamDecl(1)),
  12514. SourceLocation(), Args[1]);
  12515. if (Arg1.isInvalid())
  12516. return ExprError();
  12517. Args[0] = LHS = Arg0.getAs<Expr>();
  12518. Args[1] = RHS = Arg1.getAs<Expr>();
  12519. }
  12520. // Build the actual expression node.
  12521. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  12522. Best->FoundDecl, Base,
  12523. HadMultipleCandidates, OpLoc);
  12524. if (FnExpr.isInvalid())
  12525. return ExprError();
  12526. // Determine the result type.
  12527. QualType ResultTy = FnDecl->getReturnType();
  12528. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12529. ResultTy = ResultTy.getNonLValueExprType(Context);
  12530. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  12531. Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
  12532. CurFPFeatureOverrides(), Best->IsADLCandidate);
  12533. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  12534. FnDecl))
  12535. return ExprError();
  12536. ArrayRef<const Expr *> ArgsArray(Args, 2);
  12537. const Expr *ImplicitThis = nullptr;
  12538. // Cut off the implicit 'this'.
  12539. if (isa<CXXMethodDecl>(FnDecl)) {
  12540. ImplicitThis = ArgsArray[0];
  12541. ArgsArray = ArgsArray.slice(1);
  12542. }
  12543. // Check for a self move.
  12544. if (Op == OO_Equal)
  12545. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  12546. if (ImplicitThis) {
  12547. QualType ThisType = Context.getPointerType(ImplicitThis->getType());
  12548. QualType ThisTypeFromDecl = Context.getPointerType(
  12549. cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
  12550. CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
  12551. ThisTypeFromDecl);
  12552. }
  12553. checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
  12554. isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
  12555. VariadicDoesNotApply);
  12556. ExprResult R = MaybeBindToTemporary(TheCall);
  12557. if (R.isInvalid())
  12558. return ExprError();
  12559. R = CheckForImmediateInvocation(R, FnDecl);
  12560. if (R.isInvalid())
  12561. return ExprError();
  12562. // For a rewritten candidate, we've already reversed the arguments
  12563. // if needed. Perform the rest of the rewrite now.
  12564. if ((Best->RewriteKind & CRK_DifferentOperator) ||
  12565. (Op == OO_Spaceship && IsReversed)) {
  12566. if (Op == OO_ExclaimEqual) {
  12567. assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
  12568. R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
  12569. } else {
  12570. assert(ChosenOp == OO_Spaceship && "unexpected operator name");
  12571. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  12572. Expr *ZeroLiteral =
  12573. IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
  12574. Sema::CodeSynthesisContext Ctx;
  12575. Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
  12576. Ctx.Entity = FnDecl;
  12577. pushCodeSynthesisContext(Ctx);
  12578. R = CreateOverloadedBinOp(
  12579. OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
  12580. IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
  12581. /*AllowRewrittenCandidates=*/false);
  12582. popCodeSynthesisContext();
  12583. }
  12584. if (R.isInvalid())
  12585. return ExprError();
  12586. } else {
  12587. assert(ChosenOp == Op && "unexpected operator name");
  12588. }
  12589. // Make a note in the AST if we did any rewriting.
  12590. if (Best->RewriteKind != CRK_None)
  12591. R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
  12592. return R;
  12593. } else {
  12594. // We matched a built-in operator. Convert the arguments, then
  12595. // break out so that we will build the appropriate built-in
  12596. // operator node.
  12597. ExprResult ArgsRes0 = PerformImplicitConversion(
  12598. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  12599. AA_Passing, CCK_ForBuiltinOverloadedOp);
  12600. if (ArgsRes0.isInvalid())
  12601. return ExprError();
  12602. Args[0] = ArgsRes0.get();
  12603. ExprResult ArgsRes1 = PerformImplicitConversion(
  12604. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  12605. AA_Passing, CCK_ForBuiltinOverloadedOp);
  12606. if (ArgsRes1.isInvalid())
  12607. return ExprError();
  12608. Args[1] = ArgsRes1.get();
  12609. break;
  12610. }
  12611. }
  12612. case OR_No_Viable_Function: {
  12613. // C++ [over.match.oper]p9:
  12614. // If the operator is the operator , [...] and there are no
  12615. // viable functions, then the operator is assumed to be the
  12616. // built-in operator and interpreted according to clause 5.
  12617. if (Opc == BO_Comma)
  12618. break;
  12619. // When defaulting an 'operator<=>', we can try to synthesize a three-way
  12620. // compare result using '==' and '<'.
  12621. if (DefaultedFn && Opc == BO_Cmp) {
  12622. ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
  12623. Args[1], DefaultedFn);
  12624. if (E.isInvalid() || E.isUsable())
  12625. return E;
  12626. }
  12627. // For class as left operand for assignment or compound assignment
  12628. // operator do not fall through to handling in built-in, but report that
  12629. // no overloaded assignment operator found
  12630. ExprResult Result = ExprError();
  12631. StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
  12632. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
  12633. Args, OpLoc);
  12634. DeferDiagsRAII DDR(*this,
  12635. CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
  12636. if (Args[0]->getType()->isRecordType() &&
  12637. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  12638. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  12639. << BinaryOperator::getOpcodeStr(Opc)
  12640. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  12641. if (Args[0]->getType()->isIncompleteType()) {
  12642. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  12643. << Args[0]->getType()
  12644. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  12645. }
  12646. } else {
  12647. // This is an erroneous use of an operator which can be overloaded by
  12648. // a non-member function. Check for non-member operators which were
  12649. // defined too late to be candidates.
  12650. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  12651. // FIXME: Recover by calling the found function.
  12652. return ExprError();
  12653. // No viable function; try to create a built-in operation, which will
  12654. // produce an error. Then, show the non-viable candidates.
  12655. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  12656. }
  12657. assert(Result.isInvalid() &&
  12658. "C++ binary operator overloading is missing candidates!");
  12659. CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
  12660. return Result;
  12661. }
  12662. case OR_Ambiguous:
  12663. CandidateSet.NoteCandidates(
  12664. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  12665. << BinaryOperator::getOpcodeStr(Opc)
  12666. << Args[0]->getType()
  12667. << Args[1]->getType()
  12668. << Args[0]->getSourceRange()
  12669. << Args[1]->getSourceRange()),
  12670. *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  12671. OpLoc);
  12672. return ExprError();
  12673. case OR_Deleted:
  12674. if (isImplicitlyDeleted(Best->Function)) {
  12675. FunctionDecl *DeletedFD = Best->Function;
  12676. DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
  12677. if (DFK.isSpecialMember()) {
  12678. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  12679. << Args[0]->getType() << DFK.asSpecialMember();
  12680. } else {
  12681. assert(DFK.isComparison());
  12682. Diag(OpLoc, diag::err_ovl_deleted_comparison)
  12683. << Args[0]->getType() << DeletedFD;
  12684. }
  12685. // The user probably meant to call this special member. Just
  12686. // explain why it's deleted.
  12687. NoteDeletedFunction(DeletedFD);
  12688. return ExprError();
  12689. }
  12690. CandidateSet.NoteCandidates(
  12691. PartialDiagnosticAt(
  12692. OpLoc, PDiag(diag::err_ovl_deleted_oper)
  12693. << getOperatorSpelling(Best->Function->getDeclName()
  12694. .getCXXOverloadedOperator())
  12695. << Args[0]->getSourceRange()
  12696. << Args[1]->getSourceRange()),
  12697. *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  12698. OpLoc);
  12699. return ExprError();
  12700. }
  12701. // We matched a built-in operator; build it.
  12702. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  12703. }
  12704. ExprResult Sema::BuildSynthesizedThreeWayComparison(
  12705. SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
  12706. FunctionDecl *DefaultedFn) {
  12707. const ComparisonCategoryInfo *Info =
  12708. Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
  12709. // If we're not producing a known comparison category type, we can't
  12710. // synthesize a three-way comparison. Let the caller diagnose this.
  12711. if (!Info)
  12712. return ExprResult((Expr*)nullptr);
  12713. // If we ever want to perform this synthesis more generally, we will need to
  12714. // apply the temporary materialization conversion to the operands.
  12715. assert(LHS->isGLValue() && RHS->isGLValue() &&
  12716. "cannot use prvalue expressions more than once");
  12717. Expr *OrigLHS = LHS;
  12718. Expr *OrigRHS = RHS;
  12719. // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
  12720. // each of them multiple times below.
  12721. LHS = new (Context)
  12722. OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
  12723. LHS->getObjectKind(), LHS);
  12724. RHS = new (Context)
  12725. OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
  12726. RHS->getObjectKind(), RHS);
  12727. ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
  12728. DefaultedFn);
  12729. if (Eq.isInvalid())
  12730. return ExprError();
  12731. ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
  12732. true, DefaultedFn);
  12733. if (Less.isInvalid())
  12734. return ExprError();
  12735. ExprResult Greater;
  12736. if (Info->isPartial()) {
  12737. Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
  12738. DefaultedFn);
  12739. if (Greater.isInvalid())
  12740. return ExprError();
  12741. }
  12742. // Form the list of comparisons we're going to perform.
  12743. struct Comparison {
  12744. ExprResult Cmp;
  12745. ComparisonCategoryResult Result;
  12746. } Comparisons[4] =
  12747. { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
  12748. : ComparisonCategoryResult::Equivalent},
  12749. {Less, ComparisonCategoryResult::Less},
  12750. {Greater, ComparisonCategoryResult::Greater},
  12751. {ExprResult(), ComparisonCategoryResult::Unordered},
  12752. };
  12753. int I = Info->isPartial() ? 3 : 2;
  12754. // Combine the comparisons with suitable conditional expressions.
  12755. ExprResult Result;
  12756. for (; I >= 0; --I) {
  12757. // Build a reference to the comparison category constant.
  12758. auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
  12759. // FIXME: Missing a constant for a comparison category. Diagnose this?
  12760. if (!VI)
  12761. return ExprResult((Expr*)nullptr);
  12762. ExprResult ThisResult =
  12763. BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
  12764. if (ThisResult.isInvalid())
  12765. return ExprError();
  12766. // Build a conditional unless this is the final case.
  12767. if (Result.get()) {
  12768. Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
  12769. ThisResult.get(), Result.get());
  12770. if (Result.isInvalid())
  12771. return ExprError();
  12772. } else {
  12773. Result = ThisResult;
  12774. }
  12775. }
  12776. // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
  12777. // bind the OpaqueValueExprs before they're (repeatedly) used.
  12778. Expr *SyntacticForm = BinaryOperator::Create(
  12779. Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
  12780. Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
  12781. CurFPFeatureOverrides());
  12782. Expr *SemanticForm[] = {LHS, RHS, Result.get()};
  12783. return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
  12784. }
  12785. static bool PrepareArgumentsForCallToObjectOfClassType(
  12786. Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
  12787. MultiExprArg Args, SourceLocation LParenLoc) {
  12788. const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
  12789. unsigned NumParams = Proto->getNumParams();
  12790. unsigned NumArgsSlots =
  12791. MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
  12792. // Build the full argument list for the method call (the implicit object
  12793. // parameter is placed at the beginning of the list).
  12794. MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
  12795. bool IsError = false;
  12796. // Initialize the implicit object parameter.
  12797. // Check the argument types.
  12798. for (unsigned i = 0; i != NumParams; i++) {
  12799. Expr *Arg;
  12800. if (i < Args.size()) {
  12801. Arg = Args[i];
  12802. ExprResult InputInit =
  12803. S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  12804. S.Context, Method->getParamDecl(i)),
  12805. SourceLocation(), Arg);
  12806. IsError |= InputInit.isInvalid();
  12807. Arg = InputInit.getAs<Expr>();
  12808. } else {
  12809. ExprResult DefArg =
  12810. S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  12811. if (DefArg.isInvalid()) {
  12812. IsError = true;
  12813. break;
  12814. }
  12815. Arg = DefArg.getAs<Expr>();
  12816. }
  12817. MethodArgs.push_back(Arg);
  12818. }
  12819. return IsError;
  12820. }
  12821. ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  12822. SourceLocation RLoc,
  12823. Expr *Base,
  12824. MultiExprArg ArgExpr) {
  12825. SmallVector<Expr *, 2> Args;
  12826. Args.push_back(Base);
  12827. for (auto *e : ArgExpr) {
  12828. Args.push_back(e);
  12829. }
  12830. DeclarationName OpName =
  12831. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  12832. SourceRange Range = ArgExpr.empty()
  12833. ? SourceRange{}
  12834. : SourceRange(ArgExpr.front()->getBeginLoc(),
  12835. ArgExpr.back()->getEndLoc());
  12836. // If either side is type-dependent, create an appropriate dependent
  12837. // expression.
  12838. if (Expr::hasAnyTypeDependentArguments(Args)) {
  12839. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  12840. // CHECKME: no 'operator' keyword?
  12841. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  12842. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  12843. ExprResult Fn = CreateUnresolvedLookupExpr(
  12844. NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
  12845. if (Fn.isInvalid())
  12846. return ExprError();
  12847. // Can't add any actual overloads yet
  12848. return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
  12849. Context.DependentTy, VK_PRValue, RLoc,
  12850. CurFPFeatureOverrides());
  12851. }
  12852. // Handle placeholders
  12853. UnbridgedCastsSet UnbridgedCasts;
  12854. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  12855. return ExprError();
  12856. }
  12857. // Build an empty overload set.
  12858. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  12859. // Subscript can only be overloaded as a member function.
  12860. // Add operator candidates that are member functions.
  12861. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  12862. // Add builtin operator candidates.
  12863. if (Args.size() == 2)
  12864. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  12865. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12866. // Perform overload resolution.
  12867. OverloadCandidateSet::iterator Best;
  12868. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  12869. case OR_Success: {
  12870. // We found a built-in operator or an overloaded operator.
  12871. FunctionDecl *FnDecl = Best->Function;
  12872. if (FnDecl) {
  12873. // We matched an overloaded operator. Build a call to that
  12874. // operator.
  12875. CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
  12876. // Convert the arguments.
  12877. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  12878. SmallVector<Expr *, 2> MethodArgs;
  12879. // Handle 'this' parameter if the selected function is not static.
  12880. if (Method->isInstance()) {
  12881. ExprResult Arg0 = PerformObjectArgumentInitialization(
  12882. Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
  12883. if (Arg0.isInvalid())
  12884. return ExprError();
  12885. MethodArgs.push_back(Arg0.get());
  12886. }
  12887. bool IsError = PrepareArgumentsForCallToObjectOfClassType(
  12888. *this, MethodArgs, Method, ArgExpr, LLoc);
  12889. if (IsError)
  12890. return ExprError();
  12891. // Build the actual expression node.
  12892. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  12893. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  12894. ExprResult FnExpr = CreateFunctionRefExpr(
  12895. *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
  12896. OpLocInfo.getLoc(), OpLocInfo.getInfo());
  12897. if (FnExpr.isInvalid())
  12898. return ExprError();
  12899. // Determine the result type
  12900. QualType ResultTy = FnDecl->getReturnType();
  12901. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12902. ResultTy = ResultTy.getNonLValueExprType(Context);
  12903. CallExpr *TheCall;
  12904. if (Method->isInstance())
  12905. TheCall = CXXOperatorCallExpr::Create(
  12906. Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK,
  12907. RLoc, CurFPFeatureOverrides());
  12908. else
  12909. TheCall =
  12910. CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK,
  12911. RLoc, CurFPFeatureOverrides());
  12912. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  12913. return ExprError();
  12914. if (CheckFunctionCall(Method, TheCall,
  12915. Method->getType()->castAs<FunctionProtoType>()))
  12916. return ExprError();
  12917. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
  12918. FnDecl);
  12919. } else {
  12920. // We matched a built-in operator. Convert the arguments, then
  12921. // break out so that we will build the appropriate built-in
  12922. // operator node.
  12923. ExprResult ArgsRes0 = PerformImplicitConversion(
  12924. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  12925. AA_Passing, CCK_ForBuiltinOverloadedOp);
  12926. if (ArgsRes0.isInvalid())
  12927. return ExprError();
  12928. Args[0] = ArgsRes0.get();
  12929. ExprResult ArgsRes1 = PerformImplicitConversion(
  12930. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  12931. AA_Passing, CCK_ForBuiltinOverloadedOp);
  12932. if (ArgsRes1.isInvalid())
  12933. return ExprError();
  12934. Args[1] = ArgsRes1.get();
  12935. break;
  12936. }
  12937. }
  12938. case OR_No_Viable_Function: {
  12939. PartialDiagnostic PD =
  12940. CandidateSet.empty()
  12941. ? (PDiag(diag::err_ovl_no_oper)
  12942. << Args[0]->getType() << /*subscript*/ 0
  12943. << Args[0]->getSourceRange() << Range)
  12944. : (PDiag(diag::err_ovl_no_viable_subscript)
  12945. << Args[0]->getType() << Args[0]->getSourceRange() << Range);
  12946. CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
  12947. OCD_AllCandidates, ArgExpr, "[]", LLoc);
  12948. return ExprError();
  12949. }
  12950. case OR_Ambiguous:
  12951. if (Args.size() == 2) {
  12952. CandidateSet.NoteCandidates(
  12953. PartialDiagnosticAt(
  12954. LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  12955. << "[]" << Args[0]->getType() << Args[1]->getType()
  12956. << Args[0]->getSourceRange() << Range),
  12957. *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
  12958. } else {
  12959. CandidateSet.NoteCandidates(
  12960. PartialDiagnosticAt(LLoc,
  12961. PDiag(diag::err_ovl_ambiguous_subscript_call)
  12962. << Args[0]->getType()
  12963. << Args[0]->getSourceRange() << Range),
  12964. *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
  12965. }
  12966. return ExprError();
  12967. case OR_Deleted:
  12968. CandidateSet.NoteCandidates(
  12969. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
  12970. << "[]" << Args[0]->getSourceRange()
  12971. << Range),
  12972. *this, OCD_AllCandidates, Args, "[]", LLoc);
  12973. return ExprError();
  12974. }
  12975. // We matched a built-in operator; build it.
  12976. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  12977. }
  12978. /// BuildCallToMemberFunction - Build a call to a member
  12979. /// function. MemExpr is the expression that refers to the member
  12980. /// function (and includes the object parameter), Args/NumArgs are the
  12981. /// arguments to the function call (not including the object
  12982. /// parameter). The caller needs to validate that the member
  12983. /// expression refers to a non-static member function or an overloaded
  12984. /// member function.
  12985. ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  12986. SourceLocation LParenLoc,
  12987. MultiExprArg Args,
  12988. SourceLocation RParenLoc,
  12989. Expr *ExecConfig, bool IsExecConfig,
  12990. bool AllowRecovery) {
  12991. assert(MemExprE->getType() == Context.BoundMemberTy ||
  12992. MemExprE->getType() == Context.OverloadTy);
  12993. // Dig out the member expression. This holds both the object
  12994. // argument and the member function we're referring to.
  12995. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  12996. // Determine whether this is a call to a pointer-to-member function.
  12997. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  12998. assert(op->getType() == Context.BoundMemberTy);
  12999. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  13000. QualType fnType =
  13001. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  13002. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  13003. QualType resultType = proto->getCallResultType(Context);
  13004. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  13005. // Check that the object type isn't more qualified than the
  13006. // member function we're calling.
  13007. Qualifiers funcQuals = proto->getMethodQuals();
  13008. QualType objectType = op->getLHS()->getType();
  13009. if (op->getOpcode() == BO_PtrMemI)
  13010. objectType = objectType->castAs<PointerType>()->getPointeeType();
  13011. Qualifiers objectQuals = objectType.getQualifiers();
  13012. Qualifiers difference = objectQuals - funcQuals;
  13013. difference.removeObjCGCAttr();
  13014. difference.removeAddressSpace();
  13015. if (difference) {
  13016. std::string qualsString = difference.getAsString();
  13017. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  13018. << fnType.getUnqualifiedType()
  13019. << qualsString
  13020. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  13021. }
  13022. CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
  13023. Context, MemExprE, Args, resultType, valueKind, RParenLoc,
  13024. CurFPFeatureOverrides(), proto->getNumParams());
  13025. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
  13026. call, nullptr))
  13027. return ExprError();
  13028. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  13029. return ExprError();
  13030. if (CheckOtherCall(call, proto))
  13031. return ExprError();
  13032. return MaybeBindToTemporary(call);
  13033. }
  13034. // We only try to build a recovery expr at this level if we can preserve
  13035. // the return type, otherwise we return ExprError() and let the caller
  13036. // recover.
  13037. auto BuildRecoveryExpr = [&](QualType Type) {
  13038. if (!AllowRecovery)
  13039. return ExprError();
  13040. std::vector<Expr *> SubExprs = {MemExprE};
  13041. llvm::append_range(SubExprs, Args);
  13042. return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
  13043. Type);
  13044. };
  13045. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  13046. return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
  13047. RParenLoc, CurFPFeatureOverrides());
  13048. UnbridgedCastsSet UnbridgedCasts;
  13049. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  13050. return ExprError();
  13051. MemberExpr *MemExpr;
  13052. CXXMethodDecl *Method = nullptr;
  13053. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  13054. NestedNameSpecifier *Qualifier = nullptr;
  13055. if (isa<MemberExpr>(NakedMemExpr)) {
  13056. MemExpr = cast<MemberExpr>(NakedMemExpr);
  13057. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  13058. FoundDecl = MemExpr->getFoundDecl();
  13059. Qualifier = MemExpr->getQualifier();
  13060. UnbridgedCasts.restore();
  13061. } else {
  13062. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  13063. Qualifier = UnresExpr->getQualifier();
  13064. QualType ObjectType = UnresExpr->getBaseType();
  13065. Expr::Classification ObjectClassification
  13066. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  13067. : UnresExpr->getBase()->Classify(Context);
  13068. // Add overload candidates
  13069. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  13070. OverloadCandidateSet::CSK_Normal);
  13071. // FIXME: avoid copy.
  13072. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  13073. if (UnresExpr->hasExplicitTemplateArgs()) {
  13074. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  13075. TemplateArgs = &TemplateArgsBuffer;
  13076. }
  13077. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  13078. E = UnresExpr->decls_end(); I != E; ++I) {
  13079. NamedDecl *Func = *I;
  13080. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  13081. if (isa<UsingShadowDecl>(Func))
  13082. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  13083. // Microsoft supports direct constructor calls.
  13084. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  13085. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
  13086. CandidateSet,
  13087. /*SuppressUserConversions*/ false);
  13088. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  13089. // If explicit template arguments were provided, we can't call a
  13090. // non-template member function.
  13091. if (TemplateArgs)
  13092. continue;
  13093. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  13094. ObjectClassification, Args, CandidateSet,
  13095. /*SuppressUserConversions=*/false);
  13096. } else {
  13097. AddMethodTemplateCandidate(
  13098. cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
  13099. TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
  13100. /*SuppressUserConversions=*/false);
  13101. }
  13102. }
  13103. DeclarationName DeclName = UnresExpr->getMemberName();
  13104. UnbridgedCasts.restore();
  13105. OverloadCandidateSet::iterator Best;
  13106. bool Succeeded = false;
  13107. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
  13108. Best)) {
  13109. case OR_Success:
  13110. Method = cast<CXXMethodDecl>(Best->Function);
  13111. FoundDecl = Best->FoundDecl;
  13112. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  13113. if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  13114. break;
  13115. // If FoundDecl is different from Method (such as if one is a template
  13116. // and the other a specialization), make sure DiagnoseUseOfDecl is
  13117. // called on both.
  13118. // FIXME: This would be more comprehensively addressed by modifying
  13119. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  13120. // being used.
  13121. if (Method != FoundDecl.getDecl() &&
  13122. DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
  13123. break;
  13124. Succeeded = true;
  13125. break;
  13126. case OR_No_Viable_Function:
  13127. CandidateSet.NoteCandidates(
  13128. PartialDiagnosticAt(
  13129. UnresExpr->getMemberLoc(),
  13130. PDiag(diag::err_ovl_no_viable_member_function_in_call)
  13131. << DeclName << MemExprE->getSourceRange()),
  13132. *this, OCD_AllCandidates, Args);
  13133. break;
  13134. case OR_Ambiguous:
  13135. CandidateSet.NoteCandidates(
  13136. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  13137. PDiag(diag::err_ovl_ambiguous_member_call)
  13138. << DeclName << MemExprE->getSourceRange()),
  13139. *this, OCD_AmbiguousCandidates, Args);
  13140. break;
  13141. case OR_Deleted:
  13142. CandidateSet.NoteCandidates(
  13143. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  13144. PDiag(diag::err_ovl_deleted_member_call)
  13145. << DeclName << MemExprE->getSourceRange()),
  13146. *this, OCD_AllCandidates, Args);
  13147. break;
  13148. }
  13149. // Overload resolution fails, try to recover.
  13150. if (!Succeeded)
  13151. return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
  13152. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  13153. // If overload resolution picked a static member, build a
  13154. // non-member call based on that function.
  13155. if (Method->isStatic()) {
  13156. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
  13157. ExecConfig, IsExecConfig);
  13158. }
  13159. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  13160. }
  13161. QualType ResultType = Method->getReturnType();
  13162. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  13163. ResultType = ResultType.getNonLValueExprType(Context);
  13164. assert(Method && "Member call to something that isn't a method?");
  13165. const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
  13166. CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
  13167. Context, MemExprE, Args, ResultType, VK, RParenLoc,
  13168. CurFPFeatureOverrides(), Proto->getNumParams());
  13169. // Check for a valid return type.
  13170. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  13171. TheCall, Method))
  13172. return BuildRecoveryExpr(ResultType);
  13173. // Convert the object argument (for a non-static member function call).
  13174. // We only need to do this if there was actually an overload; otherwise
  13175. // it was done at lookup.
  13176. if (!Method->isStatic()) {
  13177. ExprResult ObjectArg =
  13178. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  13179. FoundDecl, Method);
  13180. if (ObjectArg.isInvalid())
  13181. return ExprError();
  13182. MemExpr->setBase(ObjectArg.get());
  13183. }
  13184. // Convert the rest of the arguments
  13185. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  13186. RParenLoc))
  13187. return BuildRecoveryExpr(ResultType);
  13188. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  13189. if (CheckFunctionCall(Method, TheCall, Proto))
  13190. return ExprError();
  13191. // In the case the method to call was not selected by the overloading
  13192. // resolution process, we still need to handle the enable_if attribute. Do
  13193. // that here, so it will not hide previous -- and more relevant -- errors.
  13194. if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
  13195. if (const EnableIfAttr *Attr =
  13196. CheckEnableIf(Method, LParenLoc, Args, true)) {
  13197. Diag(MemE->getMemberLoc(),
  13198. diag::err_ovl_no_viable_member_function_in_call)
  13199. << Method << Method->getSourceRange();
  13200. Diag(Method->getLocation(),
  13201. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  13202. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  13203. return ExprError();
  13204. }
  13205. }
  13206. if ((isa<CXXConstructorDecl>(CurContext) ||
  13207. isa<CXXDestructorDecl>(CurContext)) &&
  13208. TheCall->getMethodDecl()->isPure()) {
  13209. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  13210. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
  13211. MemExpr->performsVirtualDispatch(getLangOpts())) {
  13212. Diag(MemExpr->getBeginLoc(),
  13213. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  13214. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  13215. << MD->getParent();
  13216. Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
  13217. if (getLangOpts().AppleKext)
  13218. Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
  13219. << MD->getParent() << MD->getDeclName();
  13220. }
  13221. }
  13222. if (CXXDestructorDecl *DD =
  13223. dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
  13224. // a->A::f() doesn't go through the vtable, except in AppleKext mode.
  13225. bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
  13226. CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
  13227. CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
  13228. MemExpr->getMemberLoc());
  13229. }
  13230. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
  13231. TheCall->getMethodDecl());
  13232. }
  13233. /// BuildCallToObjectOfClassType - Build a call to an object of class
  13234. /// type (C++ [over.call.object]), which can end up invoking an
  13235. /// overloaded function call operator (@c operator()) or performing a
  13236. /// user-defined conversion on the object argument.
  13237. ExprResult
  13238. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  13239. SourceLocation LParenLoc,
  13240. MultiExprArg Args,
  13241. SourceLocation RParenLoc) {
  13242. if (checkPlaceholderForOverload(*this, Obj))
  13243. return ExprError();
  13244. ExprResult Object = Obj;
  13245. UnbridgedCastsSet UnbridgedCasts;
  13246. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  13247. return ExprError();
  13248. assert(Object.get()->getType()->isRecordType() &&
  13249. "Requires object type argument");
  13250. // C++ [over.call.object]p1:
  13251. // If the primary-expression E in the function call syntax
  13252. // evaluates to a class object of type "cv T", then the set of
  13253. // candidate functions includes at least the function call
  13254. // operators of T. The function call operators of T are obtained by
  13255. // ordinary lookup of the name operator() in the context of
  13256. // (E).operator().
  13257. OverloadCandidateSet CandidateSet(LParenLoc,
  13258. OverloadCandidateSet::CSK_Operator);
  13259. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  13260. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  13261. diag::err_incomplete_object_call, Object.get()))
  13262. return true;
  13263. const auto *Record = Object.get()->getType()->castAs<RecordType>();
  13264. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  13265. LookupQualifiedName(R, Record->getDecl());
  13266. R.suppressDiagnostics();
  13267. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  13268. Oper != OperEnd; ++Oper) {
  13269. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  13270. Object.get()->Classify(Context), Args, CandidateSet,
  13271. /*SuppressUserConversion=*/false);
  13272. }
  13273. // C++ [over.call.object]p2:
  13274. // In addition, for each (non-explicit in C++0x) conversion function
  13275. // declared in T of the form
  13276. //
  13277. // operator conversion-type-id () cv-qualifier;
  13278. //
  13279. // where cv-qualifier is the same cv-qualification as, or a
  13280. // greater cv-qualification than, cv, and where conversion-type-id
  13281. // denotes the type "pointer to function of (P1,...,Pn) returning
  13282. // R", or the type "reference to pointer to function of
  13283. // (P1,...,Pn) returning R", or the type "reference to function
  13284. // of (P1,...,Pn) returning R", a surrogate call function [...]
  13285. // is also considered as a candidate function. Similarly,
  13286. // surrogate call functions are added to the set of candidate
  13287. // functions for each conversion function declared in an
  13288. // accessible base class provided the function is not hidden
  13289. // within T by another intervening declaration.
  13290. const auto &Conversions =
  13291. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  13292. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  13293. NamedDecl *D = *I;
  13294. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  13295. if (isa<UsingShadowDecl>(D))
  13296. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  13297. // Skip over templated conversion functions; they aren't
  13298. // surrogates.
  13299. if (isa<FunctionTemplateDecl>(D))
  13300. continue;
  13301. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  13302. if (!Conv->isExplicit()) {
  13303. // Strip the reference type (if any) and then the pointer type (if
  13304. // any) to get down to what might be a function type.
  13305. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  13306. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  13307. ConvType = ConvPtrType->getPointeeType();
  13308. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  13309. {
  13310. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  13311. Object.get(), Args, CandidateSet);
  13312. }
  13313. }
  13314. }
  13315. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  13316. // Perform overload resolution.
  13317. OverloadCandidateSet::iterator Best;
  13318. switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
  13319. Best)) {
  13320. case OR_Success:
  13321. // Overload resolution succeeded; we'll build the appropriate call
  13322. // below.
  13323. break;
  13324. case OR_No_Viable_Function: {
  13325. PartialDiagnostic PD =
  13326. CandidateSet.empty()
  13327. ? (PDiag(diag::err_ovl_no_oper)
  13328. << Object.get()->getType() << /*call*/ 1
  13329. << Object.get()->getSourceRange())
  13330. : (PDiag(diag::err_ovl_no_viable_object_call)
  13331. << Object.get()->getType() << Object.get()->getSourceRange());
  13332. CandidateSet.NoteCandidates(
  13333. PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
  13334. OCD_AllCandidates, Args);
  13335. break;
  13336. }
  13337. case OR_Ambiguous:
  13338. CandidateSet.NoteCandidates(
  13339. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  13340. PDiag(diag::err_ovl_ambiguous_object_call)
  13341. << Object.get()->getType()
  13342. << Object.get()->getSourceRange()),
  13343. *this, OCD_AmbiguousCandidates, Args);
  13344. break;
  13345. case OR_Deleted:
  13346. CandidateSet.NoteCandidates(
  13347. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  13348. PDiag(diag::err_ovl_deleted_object_call)
  13349. << Object.get()->getType()
  13350. << Object.get()->getSourceRange()),
  13351. *this, OCD_AllCandidates, Args);
  13352. break;
  13353. }
  13354. if (Best == CandidateSet.end())
  13355. return true;
  13356. UnbridgedCasts.restore();
  13357. if (Best->Function == nullptr) {
  13358. // Since there is no function declaration, this is one of the
  13359. // surrogate candidates. Dig out the conversion function.
  13360. CXXConversionDecl *Conv
  13361. = cast<CXXConversionDecl>(
  13362. Best->Conversions[0].UserDefined.ConversionFunction);
  13363. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  13364. Best->FoundDecl);
  13365. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  13366. return ExprError();
  13367. assert(Conv == Best->FoundDecl.getDecl() &&
  13368. "Found Decl & conversion-to-functionptr should be same, right?!");
  13369. // We selected one of the surrogate functions that converts the
  13370. // object parameter to a function pointer. Perform the conversion
  13371. // on the object argument, then let BuildCallExpr finish the job.
  13372. // Create an implicit member expr to refer to the conversion operator.
  13373. // and then call it.
  13374. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  13375. Conv, HadMultipleCandidates);
  13376. if (Call.isInvalid())
  13377. return ExprError();
  13378. // Record usage of conversion in an implicit cast.
  13379. Call = ImplicitCastExpr::Create(
  13380. Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
  13381. nullptr, VK_PRValue, CurFPFeatureOverrides());
  13382. return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  13383. }
  13384. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  13385. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  13386. // that calls this method, using Object for the implicit object
  13387. // parameter and passing along the remaining arguments.
  13388. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  13389. // An error diagnostic has already been printed when parsing the declaration.
  13390. if (Method->isInvalidDecl())
  13391. return ExprError();
  13392. const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
  13393. unsigned NumParams = Proto->getNumParams();
  13394. DeclarationNameInfo OpLocInfo(
  13395. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  13396. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  13397. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  13398. Obj, HadMultipleCandidates,
  13399. OpLocInfo.getLoc(),
  13400. OpLocInfo.getInfo());
  13401. if (NewFn.isInvalid())
  13402. return true;
  13403. SmallVector<Expr *, 8> MethodArgs;
  13404. MethodArgs.reserve(NumParams + 1);
  13405. bool IsError = false;
  13406. // Initialize the implicit object parameter if needed.
  13407. // Since C++2b, this could also be a call to a static call operator
  13408. // which we emit as a regular CallExpr.
  13409. if (Method->isInstance()) {
  13410. ExprResult ObjRes = PerformObjectArgumentInitialization(
  13411. Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
  13412. if (ObjRes.isInvalid())
  13413. IsError = true;
  13414. else
  13415. Object = ObjRes;
  13416. MethodArgs.push_back(Object.get());
  13417. }
  13418. IsError |= PrepareArgumentsForCallToObjectOfClassType(
  13419. *this, MethodArgs, Method, Args, LParenLoc);
  13420. // If this is a variadic call, handle args passed through "...".
  13421. if (Proto->isVariadic()) {
  13422. // Promote the arguments (C99 6.5.2.2p7).
  13423. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  13424. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  13425. nullptr);
  13426. IsError |= Arg.isInvalid();
  13427. MethodArgs.push_back(Arg.get());
  13428. }
  13429. }
  13430. if (IsError)
  13431. return true;
  13432. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  13433. // Once we've built TheCall, all of the expressions are properly owned.
  13434. QualType ResultTy = Method->getReturnType();
  13435. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  13436. ResultTy = ResultTy.getNonLValueExprType(Context);
  13437. CallExpr *TheCall;
  13438. if (Method->isInstance())
  13439. TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(),
  13440. MethodArgs, ResultTy, VK, RParenLoc,
  13441. CurFPFeatureOverrides());
  13442. else
  13443. TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK,
  13444. RParenLoc, CurFPFeatureOverrides());
  13445. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  13446. return true;
  13447. if (CheckFunctionCall(Method, TheCall, Proto))
  13448. return true;
  13449. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
  13450. }
  13451. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  13452. /// (if one exists), where @c Base is an expression of class type and
  13453. /// @c Member is the name of the member we're trying to find.
  13454. ExprResult
  13455. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  13456. bool *NoArrowOperatorFound) {
  13457. assert(Base->getType()->isRecordType() &&
  13458. "left-hand side must have class type");
  13459. if (checkPlaceholderForOverload(*this, Base))
  13460. return ExprError();
  13461. SourceLocation Loc = Base->getExprLoc();
  13462. // C++ [over.ref]p1:
  13463. //
  13464. // [...] An expression x->m is interpreted as (x.operator->())->m
  13465. // for a class object x of type T if T::operator->() exists and if
  13466. // the operator is selected as the best match function by the
  13467. // overload resolution mechanism (13.3).
  13468. DeclarationName OpName =
  13469. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  13470. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  13471. if (RequireCompleteType(Loc, Base->getType(),
  13472. diag::err_typecheck_incomplete_tag, Base))
  13473. return ExprError();
  13474. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  13475. LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
  13476. R.suppressDiagnostics();
  13477. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  13478. Oper != OperEnd; ++Oper) {
  13479. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  13480. std::nullopt, CandidateSet,
  13481. /*SuppressUserConversion=*/false);
  13482. }
  13483. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  13484. // Perform overload resolution.
  13485. OverloadCandidateSet::iterator Best;
  13486. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  13487. case OR_Success:
  13488. // Overload resolution succeeded; we'll build the call below.
  13489. break;
  13490. case OR_No_Viable_Function: {
  13491. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
  13492. if (CandidateSet.empty()) {
  13493. QualType BaseType = Base->getType();
  13494. if (NoArrowOperatorFound) {
  13495. // Report this specific error to the caller instead of emitting a
  13496. // diagnostic, as requested.
  13497. *NoArrowOperatorFound = true;
  13498. return ExprError();
  13499. }
  13500. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  13501. << BaseType << Base->getSourceRange();
  13502. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  13503. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  13504. << FixItHint::CreateReplacement(OpLoc, ".");
  13505. }
  13506. } else
  13507. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  13508. << "operator->" << Base->getSourceRange();
  13509. CandidateSet.NoteCandidates(*this, Base, Cands);
  13510. return ExprError();
  13511. }
  13512. case OR_Ambiguous:
  13513. CandidateSet.NoteCandidates(
  13514. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
  13515. << "->" << Base->getType()
  13516. << Base->getSourceRange()),
  13517. *this, OCD_AmbiguousCandidates, Base);
  13518. return ExprError();
  13519. case OR_Deleted:
  13520. CandidateSet.NoteCandidates(
  13521. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  13522. << "->" << Base->getSourceRange()),
  13523. *this, OCD_AllCandidates, Base);
  13524. return ExprError();
  13525. }
  13526. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  13527. // Convert the object parameter.
  13528. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  13529. ExprResult BaseResult =
  13530. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  13531. Best->FoundDecl, Method);
  13532. if (BaseResult.isInvalid())
  13533. return ExprError();
  13534. Base = BaseResult.get();
  13535. // Build the operator call.
  13536. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  13537. Base, HadMultipleCandidates, OpLoc);
  13538. if (FnExpr.isInvalid())
  13539. return ExprError();
  13540. QualType ResultTy = Method->getReturnType();
  13541. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  13542. ResultTy = ResultTy.getNonLValueExprType(Context);
  13543. CXXOperatorCallExpr *TheCall =
  13544. CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
  13545. ResultTy, VK, OpLoc, CurFPFeatureOverrides());
  13546. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  13547. return ExprError();
  13548. if (CheckFunctionCall(Method, TheCall,
  13549. Method->getType()->castAs<FunctionProtoType>()))
  13550. return ExprError();
  13551. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
  13552. }
  13553. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  13554. /// a literal operator described by the provided lookup results.
  13555. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  13556. DeclarationNameInfo &SuffixInfo,
  13557. ArrayRef<Expr*> Args,
  13558. SourceLocation LitEndLoc,
  13559. TemplateArgumentListInfo *TemplateArgs) {
  13560. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  13561. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  13562. OverloadCandidateSet::CSK_Normal);
  13563. AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
  13564. TemplateArgs);
  13565. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  13566. // Perform overload resolution. This will usually be trivial, but might need
  13567. // to perform substitutions for a literal operator template.
  13568. OverloadCandidateSet::iterator Best;
  13569. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  13570. case OR_Success:
  13571. case OR_Deleted:
  13572. break;
  13573. case OR_No_Viable_Function:
  13574. CandidateSet.NoteCandidates(
  13575. PartialDiagnosticAt(UDSuffixLoc,
  13576. PDiag(diag::err_ovl_no_viable_function_in_call)
  13577. << R.getLookupName()),
  13578. *this, OCD_AllCandidates, Args);
  13579. return ExprError();
  13580. case OR_Ambiguous:
  13581. CandidateSet.NoteCandidates(
  13582. PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
  13583. << R.getLookupName()),
  13584. *this, OCD_AmbiguousCandidates, Args);
  13585. return ExprError();
  13586. }
  13587. FunctionDecl *FD = Best->Function;
  13588. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  13589. nullptr, HadMultipleCandidates,
  13590. SuffixInfo.getLoc(),
  13591. SuffixInfo.getInfo());
  13592. if (Fn.isInvalid())
  13593. return true;
  13594. // Check the argument types. This should almost always be a no-op, except
  13595. // that array-to-pointer decay is applied to string literals.
  13596. Expr *ConvArgs[2];
  13597. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  13598. ExprResult InputInit = PerformCopyInitialization(
  13599. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  13600. SourceLocation(), Args[ArgIdx]);
  13601. if (InputInit.isInvalid())
  13602. return true;
  13603. ConvArgs[ArgIdx] = InputInit.get();
  13604. }
  13605. QualType ResultTy = FD->getReturnType();
  13606. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  13607. ResultTy = ResultTy.getNonLValueExprType(Context);
  13608. UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
  13609. Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
  13610. LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
  13611. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  13612. return ExprError();
  13613. if (CheckFunctionCall(FD, UDL, nullptr))
  13614. return ExprError();
  13615. return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
  13616. }
  13617. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  13618. /// given LookupResult is non-empty, it is assumed to describe a member which
  13619. /// will be invoked. Otherwise, the function will be found via argument
  13620. /// dependent lookup.
  13621. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  13622. /// otherwise CallExpr is set to ExprError() and some non-success value
  13623. /// is returned.
  13624. Sema::ForRangeStatus
  13625. Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
  13626. SourceLocation RangeLoc,
  13627. const DeclarationNameInfo &NameInfo,
  13628. LookupResult &MemberLookup,
  13629. OverloadCandidateSet *CandidateSet,
  13630. Expr *Range, ExprResult *CallExpr) {
  13631. Scope *S = nullptr;
  13632. CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
  13633. if (!MemberLookup.empty()) {
  13634. ExprResult MemberRef =
  13635. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  13636. /*IsPtr=*/false, CXXScopeSpec(),
  13637. /*TemplateKWLoc=*/SourceLocation(),
  13638. /*FirstQualifierInScope=*/nullptr,
  13639. MemberLookup,
  13640. /*TemplateArgs=*/nullptr, S);
  13641. if (MemberRef.isInvalid()) {
  13642. *CallExpr = ExprError();
  13643. return FRS_DiagnosticIssued;
  13644. }
  13645. *CallExpr =
  13646. BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
  13647. if (CallExpr->isInvalid()) {
  13648. *CallExpr = ExprError();
  13649. return FRS_DiagnosticIssued;
  13650. }
  13651. } else {
  13652. ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
  13653. NestedNameSpecifierLoc(),
  13654. NameInfo, UnresolvedSet<0>());
  13655. if (FnR.isInvalid())
  13656. return FRS_DiagnosticIssued;
  13657. UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
  13658. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  13659. CandidateSet, CallExpr);
  13660. if (CandidateSet->empty() || CandidateSetError) {
  13661. *CallExpr = ExprError();
  13662. return FRS_NoViableFunction;
  13663. }
  13664. OverloadCandidateSet::iterator Best;
  13665. OverloadingResult OverloadResult =
  13666. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
  13667. if (OverloadResult == OR_No_Viable_Function) {
  13668. *CallExpr = ExprError();
  13669. return FRS_NoViableFunction;
  13670. }
  13671. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  13672. Loc, nullptr, CandidateSet, &Best,
  13673. OverloadResult,
  13674. /*AllowTypoCorrection=*/false);
  13675. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  13676. *CallExpr = ExprError();
  13677. return FRS_DiagnosticIssued;
  13678. }
  13679. }
  13680. return FRS_Success;
  13681. }
  13682. /// FixOverloadedFunctionReference - E is an expression that refers to
  13683. /// a C++ overloaded function (possibly with some parentheses and
  13684. /// perhaps a '&' around it). We have resolved the overloaded function
  13685. /// to the function declaration Fn, so patch up the expression E to
  13686. /// refer (possibly indirectly) to Fn. Returns the new expr.
  13687. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  13688. FunctionDecl *Fn) {
  13689. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  13690. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  13691. Found, Fn);
  13692. if (SubExpr == PE->getSubExpr())
  13693. return PE;
  13694. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  13695. }
  13696. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  13697. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  13698. Found, Fn);
  13699. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  13700. SubExpr->getType()) &&
  13701. "Implicit cast type cannot be determined from overload");
  13702. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  13703. if (SubExpr == ICE->getSubExpr())
  13704. return ICE;
  13705. return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
  13706. SubExpr, nullptr, ICE->getValueKind(),
  13707. CurFPFeatureOverrides());
  13708. }
  13709. if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  13710. if (!GSE->isResultDependent()) {
  13711. Expr *SubExpr =
  13712. FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
  13713. if (SubExpr == GSE->getResultExpr())
  13714. return GSE;
  13715. // Replace the resulting type information before rebuilding the generic
  13716. // selection expression.
  13717. ArrayRef<Expr *> A = GSE->getAssocExprs();
  13718. SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
  13719. unsigned ResultIdx = GSE->getResultIndex();
  13720. AssocExprs[ResultIdx] = SubExpr;
  13721. return GenericSelectionExpr::Create(
  13722. Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
  13723. GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
  13724. GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
  13725. ResultIdx);
  13726. }
  13727. // Rather than fall through to the unreachable, return the original generic
  13728. // selection expression.
  13729. return GSE;
  13730. }
  13731. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  13732. assert(UnOp->getOpcode() == UO_AddrOf &&
  13733. "Can only take the address of an overloaded function");
  13734. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  13735. if (Method->isStatic()) {
  13736. // Do nothing: static member functions aren't any different
  13737. // from non-member functions.
  13738. } else {
  13739. // Fix the subexpression, which really has to be an
  13740. // UnresolvedLookupExpr holding an overloaded member function
  13741. // or template.
  13742. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  13743. Found, Fn);
  13744. if (SubExpr == UnOp->getSubExpr())
  13745. return UnOp;
  13746. assert(isa<DeclRefExpr>(SubExpr)
  13747. && "fixed to something other than a decl ref");
  13748. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  13749. && "fixed to a member ref with no nested name qualifier");
  13750. // We have taken the address of a pointer to member
  13751. // function. Perform the computation here so that we get the
  13752. // appropriate pointer to member type.
  13753. QualType ClassType
  13754. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  13755. QualType MemPtrType
  13756. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  13757. // Under the MS ABI, lock down the inheritance model now.
  13758. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  13759. (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
  13760. return UnaryOperator::Create(
  13761. Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
  13762. UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
  13763. }
  13764. }
  13765. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  13766. Found, Fn);
  13767. if (SubExpr == UnOp->getSubExpr())
  13768. return UnOp;
  13769. // FIXME: This can't currently fail, but in principle it could.
  13770. return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
  13771. .get();
  13772. }
  13773. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  13774. // FIXME: avoid copy.
  13775. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  13776. if (ULE->hasExplicitTemplateArgs()) {
  13777. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  13778. TemplateArgs = &TemplateArgsBuffer;
  13779. }
  13780. QualType Type = Fn->getType();
  13781. ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
  13782. // FIXME: Duplicated from BuildDeclarationNameExpr.
  13783. if (unsigned BID = Fn->getBuiltinID()) {
  13784. if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
  13785. Type = Context.BuiltinFnTy;
  13786. ValueKind = VK_PRValue;
  13787. }
  13788. }
  13789. DeclRefExpr *DRE = BuildDeclRefExpr(
  13790. Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
  13791. Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
  13792. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  13793. return DRE;
  13794. }
  13795. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  13796. // FIXME: avoid copy.
  13797. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  13798. if (MemExpr->hasExplicitTemplateArgs()) {
  13799. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  13800. TemplateArgs = &TemplateArgsBuffer;
  13801. }
  13802. Expr *Base;
  13803. // If we're filling in a static method where we used to have an
  13804. // implicit member access, rewrite to a simple decl ref.
  13805. if (MemExpr->isImplicitAccess()) {
  13806. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  13807. DeclRefExpr *DRE = BuildDeclRefExpr(
  13808. Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
  13809. MemExpr->getQualifierLoc(), Found.getDecl(),
  13810. MemExpr->getTemplateKeywordLoc(), TemplateArgs);
  13811. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  13812. return DRE;
  13813. } else {
  13814. SourceLocation Loc = MemExpr->getMemberLoc();
  13815. if (MemExpr->getQualifier())
  13816. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  13817. Base =
  13818. BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
  13819. }
  13820. } else
  13821. Base = MemExpr->getBase();
  13822. ExprValueKind valueKind;
  13823. QualType type;
  13824. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  13825. valueKind = VK_LValue;
  13826. type = Fn->getType();
  13827. } else {
  13828. valueKind = VK_PRValue;
  13829. type = Context.BoundMemberTy;
  13830. }
  13831. return BuildMemberExpr(
  13832. Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  13833. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  13834. /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
  13835. type, valueKind, OK_Ordinary, TemplateArgs);
  13836. }
  13837. llvm_unreachable("Invalid reference to overloaded function");
  13838. }
  13839. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  13840. DeclAccessPair Found,
  13841. FunctionDecl *Fn) {
  13842. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  13843. }
  13844. bool clang::shouldEnforceArgLimit(bool PartialOverloading,
  13845. FunctionDecl *Function) {
  13846. if (!PartialOverloading || !Function)
  13847. return true;
  13848. if (Function->isVariadic())
  13849. return false;
  13850. if (const auto *Proto =
  13851. dyn_cast<FunctionProtoType>(Function->getFunctionType()))
  13852. if (Proto->isTemplateVariadic())
  13853. return false;
  13854. if (auto *Pattern = Function->getTemplateInstantiationPattern())
  13855. if (const auto *Proto =
  13856. dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
  13857. if (Proto->isTemplateVariadic())
  13858. return false;
  13859. return true;
  13860. }