SemaOverload.cpp 570 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280
  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/Sema/Overload.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/CXXInheritance.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/ExprObjC.h"
  19. #include "clang/AST/TypeOrdering.h"
  20. #include "clang/Basic/Diagnostic.h"
  21. #include "clang/Basic/DiagnosticOptions.h"
  22. #include "clang/Basic/PartialDiagnostic.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Sema/Initialization.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/SemaInternal.h"
  27. #include "clang/Sema/Template.h"
  28. #include "clang/Sema/TemplateDeduction.h"
  29. #include "llvm/ADT/DenseSet.h"
  30. #include "llvm/ADT/Optional.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include "llvm/ADT/SmallPtrSet.h"
  33. #include "llvm/ADT/SmallString.h"
  34. #include <algorithm>
  35. #include <cstdlib>
  36. using namespace clang;
  37. using namespace sema;
  38. static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
  39. return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
  40. return P->hasAttr<PassObjectSizeAttr>();
  41. });
  42. }
  43. /// A convenience routine for creating a decayed reference to a function.
  44. static ExprResult
  45. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
  46. const Expr *Base, bool HadMultipleCandidates,
  47. SourceLocation Loc = SourceLocation(),
  48. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  49. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  50. return ExprError();
  51. // If FoundDecl is different from Fn (such as if one is a template
  52. // and the other a specialization), make sure DiagnoseUseOfDecl is
  53. // called on both.
  54. // FIXME: This would be more comprehensively addressed by modifying
  55. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  56. // being used.
  57. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  58. return ExprError();
  59. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  60. S.ResolveExceptionSpec(Loc, FPT);
  61. DeclRefExpr *DRE = new (S.Context)
  62. DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
  63. if (HadMultipleCandidates)
  64. DRE->setHadMultipleCandidates(true);
  65. S.MarkDeclRefReferenced(DRE, Base);
  66. return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
  67. CK_FunctionToPointerDecay);
  68. }
  69. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  70. bool InOverloadResolution,
  71. StandardConversionSequence &SCS,
  72. bool CStyle,
  73. bool AllowObjCWritebackConversion);
  74. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  75. QualType &ToType,
  76. bool InOverloadResolution,
  77. StandardConversionSequence &SCS,
  78. bool CStyle);
  79. static OverloadingResult
  80. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  81. UserDefinedConversionSequence& User,
  82. OverloadCandidateSet& Conversions,
  83. bool AllowExplicit,
  84. bool AllowObjCConversionOnExplicit);
  85. static ImplicitConversionSequence::CompareKind
  86. CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
  87. const StandardConversionSequence& SCS1,
  88. const StandardConversionSequence& SCS2);
  89. static ImplicitConversionSequence::CompareKind
  90. CompareQualificationConversions(Sema &S,
  91. const StandardConversionSequence& SCS1,
  92. const StandardConversionSequence& SCS2);
  93. static ImplicitConversionSequence::CompareKind
  94. CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
  95. const StandardConversionSequence& SCS1,
  96. const StandardConversionSequence& SCS2);
  97. /// GetConversionRank - Retrieve the implicit conversion rank
  98. /// corresponding to the given implicit conversion kind.
  99. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  100. static const ImplicitConversionRank
  101. Rank[(int)ICK_Num_Conversion_Kinds] = {
  102. ICR_Exact_Match,
  103. ICR_Exact_Match,
  104. ICR_Exact_Match,
  105. ICR_Exact_Match,
  106. ICR_Exact_Match,
  107. ICR_Exact_Match,
  108. ICR_Promotion,
  109. ICR_Promotion,
  110. ICR_Promotion,
  111. ICR_Conversion,
  112. ICR_Conversion,
  113. ICR_Conversion,
  114. ICR_Conversion,
  115. ICR_Conversion,
  116. ICR_Conversion,
  117. ICR_Conversion,
  118. ICR_Conversion,
  119. ICR_Conversion,
  120. ICR_Conversion,
  121. ICR_OCL_Scalar_Widening,
  122. ICR_Complex_Real_Conversion,
  123. ICR_Conversion,
  124. ICR_Conversion,
  125. ICR_Writeback_Conversion,
  126. ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
  127. // it was omitted by the patch that added
  128. // ICK_Zero_Event_Conversion
  129. ICR_C_Conversion,
  130. ICR_C_Conversion_Extension
  131. };
  132. return Rank[(int)Kind];
  133. }
  134. /// GetImplicitConversionName - Return the name of this kind of
  135. /// implicit conversion.
  136. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  137. static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
  138. "No conversion",
  139. "Lvalue-to-rvalue",
  140. "Array-to-pointer",
  141. "Function-to-pointer",
  142. "Function pointer conversion",
  143. "Qualification",
  144. "Integral promotion",
  145. "Floating point promotion",
  146. "Complex promotion",
  147. "Integral conversion",
  148. "Floating conversion",
  149. "Complex conversion",
  150. "Floating-integral conversion",
  151. "Pointer conversion",
  152. "Pointer-to-member conversion",
  153. "Boolean conversion",
  154. "Compatible-types conversion",
  155. "Derived-to-base conversion",
  156. "Vector conversion",
  157. "Vector splat",
  158. "Complex-real conversion",
  159. "Block Pointer conversion",
  160. "Transparent Union Conversion",
  161. "Writeback conversion",
  162. "OpenCL Zero Event Conversion",
  163. "C specific type conversion",
  164. "Incompatible pointer conversion"
  165. };
  166. return Name[Kind];
  167. }
  168. /// StandardConversionSequence - Set the standard conversion
  169. /// sequence to the identity conversion.
  170. void StandardConversionSequence::setAsIdentityConversion() {
  171. First = ICK_Identity;
  172. Second = ICK_Identity;
  173. Third = ICK_Identity;
  174. DeprecatedStringLiteralToCharPtr = false;
  175. QualificationIncludesObjCLifetime = false;
  176. ReferenceBinding = false;
  177. DirectBinding = false;
  178. IsLvalueReference = true;
  179. BindsToFunctionLvalue = false;
  180. BindsToRvalue = false;
  181. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  182. ObjCLifetimeConversionBinding = false;
  183. CopyConstructor = nullptr;
  184. }
  185. /// getRank - Retrieve the rank of this standard conversion sequence
  186. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  187. /// implicit conversions.
  188. ImplicitConversionRank StandardConversionSequence::getRank() const {
  189. ImplicitConversionRank Rank = ICR_Exact_Match;
  190. if (GetConversionRank(First) > Rank)
  191. Rank = GetConversionRank(First);
  192. if (GetConversionRank(Second) > Rank)
  193. Rank = GetConversionRank(Second);
  194. if (GetConversionRank(Third) > Rank)
  195. Rank = GetConversionRank(Third);
  196. return Rank;
  197. }
  198. /// isPointerConversionToBool - Determines whether this conversion is
  199. /// a conversion of a pointer or pointer-to-member to bool. This is
  200. /// used as part of the ranking of standard conversion sequences
  201. /// (C++ 13.3.3.2p4).
  202. bool StandardConversionSequence::isPointerConversionToBool() const {
  203. // Note that FromType has not necessarily been transformed by the
  204. // array-to-pointer or function-to-pointer implicit conversions, so
  205. // check for their presence as well as checking whether FromType is
  206. // a pointer.
  207. if (getToType(1)->isBooleanType() &&
  208. (getFromType()->isPointerType() ||
  209. getFromType()->isMemberPointerType() ||
  210. getFromType()->isObjCObjectPointerType() ||
  211. getFromType()->isBlockPointerType() ||
  212. getFromType()->isNullPtrType() ||
  213. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  214. return true;
  215. return false;
  216. }
  217. /// isPointerConversionToVoidPointer - Determines whether this
  218. /// conversion is a conversion of a pointer to a void pointer. This is
  219. /// used as part of the ranking of standard conversion sequences (C++
  220. /// 13.3.3.2p4).
  221. bool
  222. StandardConversionSequence::
  223. isPointerConversionToVoidPointer(ASTContext& Context) const {
  224. QualType FromType = getFromType();
  225. QualType ToType = getToType(1);
  226. // Note that FromType has not necessarily been transformed by the
  227. // array-to-pointer implicit conversion, so check for its presence
  228. // and redo the conversion to get a pointer.
  229. if (First == ICK_Array_To_Pointer)
  230. FromType = Context.getArrayDecayedType(FromType);
  231. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  232. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  233. return ToPtrType->getPointeeType()->isVoidType();
  234. return false;
  235. }
  236. /// Skip any implicit casts which could be either part of a narrowing conversion
  237. /// or after one in an implicit conversion.
  238. static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
  239. const Expr *Converted) {
  240. // We can have cleanups wrapping the converted expression; these need to be
  241. // preserved so that destructors run if necessary.
  242. if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
  243. Expr *Inner =
  244. const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
  245. return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
  246. EWC->getObjects());
  247. }
  248. while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  249. switch (ICE->getCastKind()) {
  250. case CK_NoOp:
  251. case CK_IntegralCast:
  252. case CK_IntegralToBoolean:
  253. case CK_IntegralToFloating:
  254. case CK_BooleanToSignedIntegral:
  255. case CK_FloatingToIntegral:
  256. case CK_FloatingToBoolean:
  257. case CK_FloatingCast:
  258. Converted = ICE->getSubExpr();
  259. continue;
  260. default:
  261. return Converted;
  262. }
  263. }
  264. return Converted;
  265. }
  266. /// Check if this standard conversion sequence represents a narrowing
  267. /// conversion, according to C++11 [dcl.init.list]p7.
  268. ///
  269. /// \param Ctx The AST context.
  270. /// \param Converted The result of applying this standard conversion sequence.
  271. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  272. /// value of the expression prior to the narrowing conversion.
  273. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  274. /// type of the expression prior to the narrowing conversion.
  275. /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
  276. /// from floating point types to integral types should be ignored.
  277. NarrowingKind StandardConversionSequence::getNarrowingKind(
  278. ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
  279. QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
  280. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  281. // C++11 [dcl.init.list]p7:
  282. // A narrowing conversion is an implicit conversion ...
  283. QualType FromType = getToType(0);
  284. QualType ToType = getToType(1);
  285. // A conversion to an enumeration type is narrowing if the conversion to
  286. // the underlying type is narrowing. This only arises for expressions of
  287. // the form 'Enum{init}'.
  288. if (auto *ET = ToType->getAs<EnumType>())
  289. ToType = ET->getDecl()->getIntegerType();
  290. switch (Second) {
  291. // 'bool' is an integral type; dispatch to the right place to handle it.
  292. case ICK_Boolean_Conversion:
  293. if (FromType->isRealFloatingType())
  294. goto FloatingIntegralConversion;
  295. if (FromType->isIntegralOrUnscopedEnumerationType())
  296. goto IntegralConversion;
  297. // Boolean conversions can be from pointers and pointers to members
  298. // [conv.bool], and those aren't considered narrowing conversions.
  299. return NK_Not_Narrowing;
  300. // -- from a floating-point type to an integer type, or
  301. //
  302. // -- from an integer type or unscoped enumeration type to a floating-point
  303. // type, except where the source is a constant expression and the actual
  304. // value after conversion will fit into the target type and will produce
  305. // the original value when converted back to the original type, or
  306. case ICK_Floating_Integral:
  307. FloatingIntegralConversion:
  308. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  309. return NK_Type_Narrowing;
  310. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  311. ToType->isRealFloatingType()) {
  312. if (IgnoreFloatToIntegralConversion)
  313. return NK_Not_Narrowing;
  314. llvm::APSInt IntConstantValue;
  315. const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
  316. assert(Initializer && "Unknown conversion expression");
  317. // If it's value-dependent, we can't tell whether it's narrowing.
  318. if (Initializer->isValueDependent())
  319. return NK_Dependent_Narrowing;
  320. if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  321. // Convert the integer to the floating type.
  322. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  323. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  324. llvm::APFloat::rmNearestTiesToEven);
  325. // And back.
  326. llvm::APSInt ConvertedValue = IntConstantValue;
  327. bool ignored;
  328. Result.convertToInteger(ConvertedValue,
  329. llvm::APFloat::rmTowardZero, &ignored);
  330. // If the resulting value is different, this was a narrowing conversion.
  331. if (IntConstantValue != ConvertedValue) {
  332. ConstantValue = APValue(IntConstantValue);
  333. ConstantType = Initializer->getType();
  334. return NK_Constant_Narrowing;
  335. }
  336. } else {
  337. // Variables are always narrowings.
  338. return NK_Variable_Narrowing;
  339. }
  340. }
  341. return NK_Not_Narrowing;
  342. // -- from long double to double or float, or from double to float, except
  343. // where the source is a constant expression and the actual value after
  344. // conversion is within the range of values that can be represented (even
  345. // if it cannot be represented exactly), or
  346. case ICK_Floating_Conversion:
  347. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  348. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  349. // FromType is larger than ToType.
  350. const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
  351. // If it's value-dependent, we can't tell whether it's narrowing.
  352. if (Initializer->isValueDependent())
  353. return NK_Dependent_Narrowing;
  354. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  355. // Constant!
  356. assert(ConstantValue.isFloat());
  357. llvm::APFloat FloatVal = ConstantValue.getFloat();
  358. // Convert the source value into the target type.
  359. bool ignored;
  360. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  361. Ctx.getFloatTypeSemantics(ToType),
  362. llvm::APFloat::rmNearestTiesToEven, &ignored);
  363. // If there was no overflow, the source value is within the range of
  364. // values that can be represented.
  365. if (ConvertStatus & llvm::APFloat::opOverflow) {
  366. ConstantType = Initializer->getType();
  367. return NK_Constant_Narrowing;
  368. }
  369. } else {
  370. return NK_Variable_Narrowing;
  371. }
  372. }
  373. return NK_Not_Narrowing;
  374. // -- from an integer type or unscoped enumeration type to an integer type
  375. // that cannot represent all the values of the original type, except where
  376. // the source is a constant expression and the actual value after
  377. // conversion will fit into the target type and will produce the original
  378. // value when converted back to the original type.
  379. case ICK_Integral_Conversion:
  380. IntegralConversion: {
  381. assert(FromType->isIntegralOrUnscopedEnumerationType());
  382. assert(ToType->isIntegralOrUnscopedEnumerationType());
  383. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  384. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  385. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  386. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  387. if (FromWidth > ToWidth ||
  388. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  389. (FromSigned && !ToSigned)) {
  390. // Not all values of FromType can be represented in ToType.
  391. llvm::APSInt InitializerValue;
  392. const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
  393. // If it's value-dependent, we can't tell whether it's narrowing.
  394. if (Initializer->isValueDependent())
  395. return NK_Dependent_Narrowing;
  396. if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  397. // Such conversions on variables are always narrowing.
  398. return NK_Variable_Narrowing;
  399. }
  400. bool Narrowing = false;
  401. if (FromWidth < ToWidth) {
  402. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  403. // narrowing.
  404. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  405. Narrowing = true;
  406. } else {
  407. // Add a bit to the InitializerValue so we don't have to worry about
  408. // signed vs. unsigned comparisons.
  409. InitializerValue = InitializerValue.extend(
  410. InitializerValue.getBitWidth() + 1);
  411. // Convert the initializer to and from the target width and signed-ness.
  412. llvm::APSInt ConvertedValue = InitializerValue;
  413. ConvertedValue = ConvertedValue.trunc(ToWidth);
  414. ConvertedValue.setIsSigned(ToSigned);
  415. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  416. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  417. // If the result is different, this was a narrowing conversion.
  418. if (ConvertedValue != InitializerValue)
  419. Narrowing = true;
  420. }
  421. if (Narrowing) {
  422. ConstantType = Initializer->getType();
  423. ConstantValue = APValue(InitializerValue);
  424. return NK_Constant_Narrowing;
  425. }
  426. }
  427. return NK_Not_Narrowing;
  428. }
  429. default:
  430. // Other kinds of conversions are not narrowings.
  431. return NK_Not_Narrowing;
  432. }
  433. }
  434. /// dump - Print this standard conversion sequence to standard
  435. /// error. Useful for debugging overloading issues.
  436. LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
  437. raw_ostream &OS = llvm::errs();
  438. bool PrintedSomething = false;
  439. if (First != ICK_Identity) {
  440. OS << GetImplicitConversionName(First);
  441. PrintedSomething = true;
  442. }
  443. if (Second != ICK_Identity) {
  444. if (PrintedSomething) {
  445. OS << " -> ";
  446. }
  447. OS << GetImplicitConversionName(Second);
  448. if (CopyConstructor) {
  449. OS << " (by copy constructor)";
  450. } else if (DirectBinding) {
  451. OS << " (direct reference binding)";
  452. } else if (ReferenceBinding) {
  453. OS << " (reference binding)";
  454. }
  455. PrintedSomething = true;
  456. }
  457. if (Third != ICK_Identity) {
  458. if (PrintedSomething) {
  459. OS << " -> ";
  460. }
  461. OS << GetImplicitConversionName(Third);
  462. PrintedSomething = true;
  463. }
  464. if (!PrintedSomething) {
  465. OS << "No conversions required";
  466. }
  467. }
  468. /// dump - Print this user-defined conversion sequence to standard
  469. /// error. Useful for debugging overloading issues.
  470. void UserDefinedConversionSequence::dump() const {
  471. raw_ostream &OS = llvm::errs();
  472. if (Before.First || Before.Second || Before.Third) {
  473. Before.dump();
  474. OS << " -> ";
  475. }
  476. if (ConversionFunction)
  477. OS << '\'' << *ConversionFunction << '\'';
  478. else
  479. OS << "aggregate initialization";
  480. if (After.First || After.Second || After.Third) {
  481. OS << " -> ";
  482. After.dump();
  483. }
  484. }
  485. /// dump - Print this implicit conversion sequence to standard
  486. /// error. Useful for debugging overloading issues.
  487. void ImplicitConversionSequence::dump() const {
  488. raw_ostream &OS = llvm::errs();
  489. if (isStdInitializerListElement())
  490. OS << "Worst std::initializer_list element conversion: ";
  491. switch (ConversionKind) {
  492. case StandardConversion:
  493. OS << "Standard conversion: ";
  494. Standard.dump();
  495. break;
  496. case UserDefinedConversion:
  497. OS << "User-defined conversion: ";
  498. UserDefined.dump();
  499. break;
  500. case EllipsisConversion:
  501. OS << "Ellipsis conversion";
  502. break;
  503. case AmbiguousConversion:
  504. OS << "Ambiguous conversion";
  505. break;
  506. case BadConversion:
  507. OS << "Bad conversion";
  508. break;
  509. }
  510. OS << "\n";
  511. }
  512. void AmbiguousConversionSequence::construct() {
  513. new (&conversions()) ConversionSet();
  514. }
  515. void AmbiguousConversionSequence::destruct() {
  516. conversions().~ConversionSet();
  517. }
  518. void
  519. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  520. FromTypePtr = O.FromTypePtr;
  521. ToTypePtr = O.ToTypePtr;
  522. new (&conversions()) ConversionSet(O.conversions());
  523. }
  524. namespace {
  525. // Structure used by DeductionFailureInfo to store
  526. // template argument information.
  527. struct DFIArguments {
  528. TemplateArgument FirstArg;
  529. TemplateArgument SecondArg;
  530. };
  531. // Structure used by DeductionFailureInfo to store
  532. // template parameter and template argument information.
  533. struct DFIParamWithArguments : DFIArguments {
  534. TemplateParameter Param;
  535. };
  536. // Structure used by DeductionFailureInfo to store template argument
  537. // information and the index of the problematic call argument.
  538. struct DFIDeducedMismatchArgs : DFIArguments {
  539. TemplateArgumentList *TemplateArgs;
  540. unsigned CallArgIndex;
  541. };
  542. }
  543. /// Convert from Sema's representation of template deduction information
  544. /// to the form used in overload-candidate information.
  545. DeductionFailureInfo
  546. clang::MakeDeductionFailureInfo(ASTContext &Context,
  547. Sema::TemplateDeductionResult TDK,
  548. TemplateDeductionInfo &Info) {
  549. DeductionFailureInfo Result;
  550. Result.Result = static_cast<unsigned>(TDK);
  551. Result.HasDiagnostic = false;
  552. switch (TDK) {
  553. case Sema::TDK_Invalid:
  554. case Sema::TDK_InstantiationDepth:
  555. case Sema::TDK_TooManyArguments:
  556. case Sema::TDK_TooFewArguments:
  557. case Sema::TDK_MiscellaneousDeductionFailure:
  558. case Sema::TDK_CUDATargetMismatch:
  559. Result.Data = nullptr;
  560. break;
  561. case Sema::TDK_Incomplete:
  562. case Sema::TDK_InvalidExplicitArguments:
  563. Result.Data = Info.Param.getOpaqueValue();
  564. break;
  565. case Sema::TDK_DeducedMismatch:
  566. case Sema::TDK_DeducedMismatchNested: {
  567. // FIXME: Should allocate from normal heap so that we can free this later.
  568. auto *Saved = new (Context) DFIDeducedMismatchArgs;
  569. Saved->FirstArg = Info.FirstArg;
  570. Saved->SecondArg = Info.SecondArg;
  571. Saved->TemplateArgs = Info.take();
  572. Saved->CallArgIndex = Info.CallArgIndex;
  573. Result.Data = Saved;
  574. break;
  575. }
  576. case Sema::TDK_NonDeducedMismatch: {
  577. // FIXME: Should allocate from normal heap so that we can free this later.
  578. DFIArguments *Saved = new (Context) DFIArguments;
  579. Saved->FirstArg = Info.FirstArg;
  580. Saved->SecondArg = Info.SecondArg;
  581. Result.Data = Saved;
  582. break;
  583. }
  584. case Sema::TDK_IncompletePack:
  585. // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
  586. case Sema::TDK_Inconsistent:
  587. case Sema::TDK_Underqualified: {
  588. // FIXME: Should allocate from normal heap so that we can free this later.
  589. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  590. Saved->Param = Info.Param;
  591. Saved->FirstArg = Info.FirstArg;
  592. Saved->SecondArg = Info.SecondArg;
  593. Result.Data = Saved;
  594. break;
  595. }
  596. case Sema::TDK_SubstitutionFailure:
  597. Result.Data = Info.take();
  598. if (Info.hasSFINAEDiagnostic()) {
  599. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  600. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  601. Info.takeSFINAEDiagnostic(*Diag);
  602. Result.HasDiagnostic = true;
  603. }
  604. break;
  605. case Sema::TDK_Success:
  606. case Sema::TDK_NonDependentConversionFailure:
  607. llvm_unreachable("not a deduction failure");
  608. }
  609. return Result;
  610. }
  611. void DeductionFailureInfo::Destroy() {
  612. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  613. case Sema::TDK_Success:
  614. case Sema::TDK_Invalid:
  615. case Sema::TDK_InstantiationDepth:
  616. case Sema::TDK_Incomplete:
  617. case Sema::TDK_TooManyArguments:
  618. case Sema::TDK_TooFewArguments:
  619. case Sema::TDK_InvalidExplicitArguments:
  620. case Sema::TDK_CUDATargetMismatch:
  621. case Sema::TDK_NonDependentConversionFailure:
  622. break;
  623. case Sema::TDK_IncompletePack:
  624. case Sema::TDK_Inconsistent:
  625. case Sema::TDK_Underqualified:
  626. case Sema::TDK_DeducedMismatch:
  627. case Sema::TDK_DeducedMismatchNested:
  628. case Sema::TDK_NonDeducedMismatch:
  629. // FIXME: Destroy the data?
  630. Data = nullptr;
  631. break;
  632. case Sema::TDK_SubstitutionFailure:
  633. // FIXME: Destroy the template argument list?
  634. Data = nullptr;
  635. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  636. Diag->~PartialDiagnosticAt();
  637. HasDiagnostic = false;
  638. }
  639. break;
  640. // Unhandled
  641. case Sema::TDK_MiscellaneousDeductionFailure:
  642. break;
  643. }
  644. }
  645. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  646. if (HasDiagnostic)
  647. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  648. return nullptr;
  649. }
  650. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  651. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  652. case Sema::TDK_Success:
  653. case Sema::TDK_Invalid:
  654. case Sema::TDK_InstantiationDepth:
  655. case Sema::TDK_TooManyArguments:
  656. case Sema::TDK_TooFewArguments:
  657. case Sema::TDK_SubstitutionFailure:
  658. case Sema::TDK_DeducedMismatch:
  659. case Sema::TDK_DeducedMismatchNested:
  660. case Sema::TDK_NonDeducedMismatch:
  661. case Sema::TDK_CUDATargetMismatch:
  662. case Sema::TDK_NonDependentConversionFailure:
  663. return TemplateParameter();
  664. case Sema::TDK_Incomplete:
  665. case Sema::TDK_InvalidExplicitArguments:
  666. return TemplateParameter::getFromOpaqueValue(Data);
  667. case Sema::TDK_IncompletePack:
  668. case Sema::TDK_Inconsistent:
  669. case Sema::TDK_Underqualified:
  670. return static_cast<DFIParamWithArguments*>(Data)->Param;
  671. // Unhandled
  672. case Sema::TDK_MiscellaneousDeductionFailure:
  673. break;
  674. }
  675. return TemplateParameter();
  676. }
  677. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  678. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  679. case Sema::TDK_Success:
  680. case Sema::TDK_Invalid:
  681. case Sema::TDK_InstantiationDepth:
  682. case Sema::TDK_TooManyArguments:
  683. case Sema::TDK_TooFewArguments:
  684. case Sema::TDK_Incomplete:
  685. case Sema::TDK_IncompletePack:
  686. case Sema::TDK_InvalidExplicitArguments:
  687. case Sema::TDK_Inconsistent:
  688. case Sema::TDK_Underqualified:
  689. case Sema::TDK_NonDeducedMismatch:
  690. case Sema::TDK_CUDATargetMismatch:
  691. case Sema::TDK_NonDependentConversionFailure:
  692. return nullptr;
  693. case Sema::TDK_DeducedMismatch:
  694. case Sema::TDK_DeducedMismatchNested:
  695. return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
  696. case Sema::TDK_SubstitutionFailure:
  697. return static_cast<TemplateArgumentList*>(Data);
  698. // Unhandled
  699. case Sema::TDK_MiscellaneousDeductionFailure:
  700. break;
  701. }
  702. return nullptr;
  703. }
  704. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  705. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  706. case Sema::TDK_Success:
  707. case Sema::TDK_Invalid:
  708. case Sema::TDK_InstantiationDepth:
  709. case Sema::TDK_Incomplete:
  710. case Sema::TDK_TooManyArguments:
  711. case Sema::TDK_TooFewArguments:
  712. case Sema::TDK_InvalidExplicitArguments:
  713. case Sema::TDK_SubstitutionFailure:
  714. case Sema::TDK_CUDATargetMismatch:
  715. case Sema::TDK_NonDependentConversionFailure:
  716. return nullptr;
  717. case Sema::TDK_IncompletePack:
  718. case Sema::TDK_Inconsistent:
  719. case Sema::TDK_Underqualified:
  720. case Sema::TDK_DeducedMismatch:
  721. case Sema::TDK_DeducedMismatchNested:
  722. case Sema::TDK_NonDeducedMismatch:
  723. return &static_cast<DFIArguments*>(Data)->FirstArg;
  724. // Unhandled
  725. case Sema::TDK_MiscellaneousDeductionFailure:
  726. break;
  727. }
  728. return nullptr;
  729. }
  730. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  731. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  732. case Sema::TDK_Success:
  733. case Sema::TDK_Invalid:
  734. case Sema::TDK_InstantiationDepth:
  735. case Sema::TDK_Incomplete:
  736. case Sema::TDK_IncompletePack:
  737. case Sema::TDK_TooManyArguments:
  738. case Sema::TDK_TooFewArguments:
  739. case Sema::TDK_InvalidExplicitArguments:
  740. case Sema::TDK_SubstitutionFailure:
  741. case Sema::TDK_CUDATargetMismatch:
  742. case Sema::TDK_NonDependentConversionFailure:
  743. return nullptr;
  744. case Sema::TDK_Inconsistent:
  745. case Sema::TDK_Underqualified:
  746. case Sema::TDK_DeducedMismatch:
  747. case Sema::TDK_DeducedMismatchNested:
  748. case Sema::TDK_NonDeducedMismatch:
  749. return &static_cast<DFIArguments*>(Data)->SecondArg;
  750. // Unhandled
  751. case Sema::TDK_MiscellaneousDeductionFailure:
  752. break;
  753. }
  754. return nullptr;
  755. }
  756. llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
  757. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  758. case Sema::TDK_DeducedMismatch:
  759. case Sema::TDK_DeducedMismatchNested:
  760. return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
  761. default:
  762. return llvm::None;
  763. }
  764. }
  765. bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
  766. OverloadedOperatorKind Op) {
  767. if (!AllowRewrittenCandidates)
  768. return false;
  769. return Op == OO_EqualEqual || Op == OO_Spaceship;
  770. }
  771. bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
  772. ASTContext &Ctx, const FunctionDecl *FD) {
  773. if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
  774. return false;
  775. // Don't bother adding a reversed candidate that can never be a better
  776. // match than the non-reversed version.
  777. return FD->getNumParams() != 2 ||
  778. !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
  779. FD->getParamDecl(1)->getType()) ||
  780. FD->hasAttr<EnableIfAttr>();
  781. }
  782. void OverloadCandidateSet::destroyCandidates() {
  783. for (iterator i = begin(), e = end(); i != e; ++i) {
  784. for (auto &C : i->Conversions)
  785. C.~ImplicitConversionSequence();
  786. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  787. i->DeductionFailure.Destroy();
  788. }
  789. }
  790. void OverloadCandidateSet::clear(CandidateSetKind CSK) {
  791. destroyCandidates();
  792. SlabAllocator.Reset();
  793. NumInlineBytesUsed = 0;
  794. Candidates.clear();
  795. Functions.clear();
  796. Kind = CSK;
  797. }
  798. namespace {
  799. class UnbridgedCastsSet {
  800. struct Entry {
  801. Expr **Addr;
  802. Expr *Saved;
  803. };
  804. SmallVector<Entry, 2> Entries;
  805. public:
  806. void save(Sema &S, Expr *&E) {
  807. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  808. Entry entry = { &E, E };
  809. Entries.push_back(entry);
  810. E = S.stripARCUnbridgedCast(E);
  811. }
  812. void restore() {
  813. for (SmallVectorImpl<Entry>::iterator
  814. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  815. *i->Addr = i->Saved;
  816. }
  817. };
  818. }
  819. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  820. /// preprocessing on the given expression.
  821. ///
  822. /// \param unbridgedCasts a collection to which to add unbridged casts;
  823. /// without this, they will be immediately diagnosed as errors
  824. ///
  825. /// Return true on unrecoverable error.
  826. static bool
  827. checkPlaceholderForOverload(Sema &S, Expr *&E,
  828. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  829. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  830. // We can't handle overloaded expressions here because overload
  831. // resolution might reasonably tweak them.
  832. if (placeholder->getKind() == BuiltinType::Overload) return false;
  833. // If the context potentially accepts unbridged ARC casts, strip
  834. // the unbridged cast and add it to the collection for later restoration.
  835. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  836. unbridgedCasts) {
  837. unbridgedCasts->save(S, E);
  838. return false;
  839. }
  840. // Go ahead and check everything else.
  841. ExprResult result = S.CheckPlaceholderExpr(E);
  842. if (result.isInvalid())
  843. return true;
  844. E = result.get();
  845. return false;
  846. }
  847. // Nothing to do.
  848. return false;
  849. }
  850. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  851. /// placeholders.
  852. static bool checkArgPlaceholdersForOverload(Sema &S,
  853. MultiExprArg Args,
  854. UnbridgedCastsSet &unbridged) {
  855. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  856. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  857. return true;
  858. return false;
  859. }
  860. /// Determine whether the given New declaration is an overload of the
  861. /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
  862. /// New and Old cannot be overloaded, e.g., if New has the same signature as
  863. /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
  864. /// functions (or function templates) at all. When it does return Ovl_Match or
  865. /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
  866. /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
  867. /// declaration.
  868. ///
  869. /// Example: Given the following input:
  870. ///
  871. /// void f(int, float); // #1
  872. /// void f(int, int); // #2
  873. /// int f(int, int); // #3
  874. ///
  875. /// When we process #1, there is no previous declaration of "f", so IsOverload
  876. /// will not be used.
  877. ///
  878. /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
  879. /// the parameter types, we see that #1 and #2 are overloaded (since they have
  880. /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
  881. /// unchanged.
  882. ///
  883. /// When we process #3, Old is an overload set containing #1 and #2. We compare
  884. /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
  885. /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
  886. /// functions are not part of the signature), IsOverload returns Ovl_Match and
  887. /// MatchedDecl will be set to point to the FunctionDecl for #2.
  888. ///
  889. /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
  890. /// by a using declaration. The rules for whether to hide shadow declarations
  891. /// ignore some properties which otherwise figure into a function template's
  892. /// signature.
  893. Sema::OverloadKind
  894. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  895. NamedDecl *&Match, bool NewIsUsingDecl) {
  896. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  897. I != E; ++I) {
  898. NamedDecl *OldD = *I;
  899. bool OldIsUsingDecl = false;
  900. if (isa<UsingShadowDecl>(OldD)) {
  901. OldIsUsingDecl = true;
  902. // We can always introduce two using declarations into the same
  903. // context, even if they have identical signatures.
  904. if (NewIsUsingDecl) continue;
  905. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  906. }
  907. // A using-declaration does not conflict with another declaration
  908. // if one of them is hidden.
  909. if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
  910. continue;
  911. // If either declaration was introduced by a using declaration,
  912. // we'll need to use slightly different rules for matching.
  913. // Essentially, these rules are the normal rules, except that
  914. // function templates hide function templates with different
  915. // return types or template parameter lists.
  916. bool UseMemberUsingDeclRules =
  917. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  918. !New->getFriendObjectKind();
  919. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  920. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  921. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  922. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  923. continue;
  924. }
  925. if (!isa<FunctionTemplateDecl>(OldD) &&
  926. !shouldLinkPossiblyHiddenDecl(*I, New))
  927. continue;
  928. Match = *I;
  929. return Ovl_Match;
  930. }
  931. // Builtins that have custom typechecking or have a reference should
  932. // not be overloadable or redeclarable.
  933. if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
  934. Match = *I;
  935. return Ovl_NonFunction;
  936. }
  937. } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
  938. // We can overload with these, which can show up when doing
  939. // redeclaration checks for UsingDecls.
  940. assert(Old.getLookupKind() == LookupUsingDeclName);
  941. } else if (isa<TagDecl>(OldD)) {
  942. // We can always overload with tags by hiding them.
  943. } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
  944. // Optimistically assume that an unresolved using decl will
  945. // overload; if it doesn't, we'll have to diagnose during
  946. // template instantiation.
  947. //
  948. // Exception: if the scope is dependent and this is not a class
  949. // member, the using declaration can only introduce an enumerator.
  950. if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
  951. Match = *I;
  952. return Ovl_NonFunction;
  953. }
  954. } else {
  955. // (C++ 13p1):
  956. // Only function declarations can be overloaded; object and type
  957. // declarations cannot be overloaded.
  958. Match = *I;
  959. return Ovl_NonFunction;
  960. }
  961. }
  962. // C++ [temp.friend]p1:
  963. // For a friend function declaration that is not a template declaration:
  964. // -- if the name of the friend is a qualified or unqualified template-id,
  965. // [...], otherwise
  966. // -- if the name of the friend is a qualified-id and a matching
  967. // non-template function is found in the specified class or namespace,
  968. // the friend declaration refers to that function, otherwise,
  969. // -- if the name of the friend is a qualified-id and a matching function
  970. // template is found in the specified class or namespace, the friend
  971. // declaration refers to the deduced specialization of that function
  972. // template, otherwise
  973. // -- the name shall be an unqualified-id [...]
  974. // If we get here for a qualified friend declaration, we've just reached the
  975. // third bullet. If the type of the friend is dependent, skip this lookup
  976. // until instantiation.
  977. if (New->getFriendObjectKind() && New->getQualifier() &&
  978. !New->getDescribedFunctionTemplate() &&
  979. !New->getDependentSpecializationInfo() &&
  980. !New->getType()->isDependentType()) {
  981. LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
  982. TemplateSpecResult.addAllDecls(Old);
  983. if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
  984. /*QualifiedFriend*/true)) {
  985. New->setInvalidDecl();
  986. return Ovl_Overload;
  987. }
  988. Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
  989. return Ovl_Match;
  990. }
  991. return Ovl_Overload;
  992. }
  993. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  994. bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
  995. // C++ [basic.start.main]p2: This function shall not be overloaded.
  996. if (New->isMain())
  997. return false;
  998. // MSVCRT user defined entry points cannot be overloaded.
  999. if (New->isMSVCRTEntryPoint())
  1000. return false;
  1001. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  1002. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  1003. // C++ [temp.fct]p2:
  1004. // A function template can be overloaded with other function templates
  1005. // and with normal (non-template) functions.
  1006. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  1007. return true;
  1008. // Is the function New an overload of the function Old?
  1009. QualType OldQType = Context.getCanonicalType(Old->getType());
  1010. QualType NewQType = Context.getCanonicalType(New->getType());
  1011. // Compare the signatures (C++ 1.3.10) of the two functions to
  1012. // determine whether they are overloads. If we find any mismatch
  1013. // in the signature, they are overloads.
  1014. // If either of these functions is a K&R-style function (no
  1015. // prototype), then we consider them to have matching signatures.
  1016. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  1017. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  1018. return false;
  1019. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  1020. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  1021. // The signature of a function includes the types of its
  1022. // parameters (C++ 1.3.10), which includes the presence or absence
  1023. // of the ellipsis; see C++ DR 357).
  1024. if (OldQType != NewQType &&
  1025. (OldType->getNumParams() != NewType->getNumParams() ||
  1026. OldType->isVariadic() != NewType->isVariadic() ||
  1027. !FunctionParamTypesAreEqual(OldType, NewType)))
  1028. return true;
  1029. // C++ [temp.over.link]p4:
  1030. // The signature of a function template consists of its function
  1031. // signature, its return type and its template parameter list. The names
  1032. // of the template parameters are significant only for establishing the
  1033. // relationship between the template parameters and the rest of the
  1034. // signature.
  1035. //
  1036. // We check the return type and template parameter lists for function
  1037. // templates first; the remaining checks follow.
  1038. //
  1039. // However, we don't consider either of these when deciding whether
  1040. // a member introduced by a shadow declaration is hidden.
  1041. if (!UseMemberUsingDeclRules && NewTemplate &&
  1042. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  1043. OldTemplate->getTemplateParameters(),
  1044. false, TPL_TemplateMatch) ||
  1045. !Context.hasSameType(Old->getDeclaredReturnType(),
  1046. New->getDeclaredReturnType())))
  1047. return true;
  1048. // If the function is a class member, its signature includes the
  1049. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  1050. //
  1051. // As part of this, also check whether one of the member functions
  1052. // is static, in which case they are not overloads (C++
  1053. // 13.1p2). While not part of the definition of the signature,
  1054. // this check is important to determine whether these functions
  1055. // can be overloaded.
  1056. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1057. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  1058. if (OldMethod && NewMethod &&
  1059. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  1060. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  1061. if (!UseMemberUsingDeclRules &&
  1062. (OldMethod->getRefQualifier() == RQ_None ||
  1063. NewMethod->getRefQualifier() == RQ_None)) {
  1064. // C++0x [over.load]p2:
  1065. // - Member function declarations with the same name and the same
  1066. // parameter-type-list as well as member function template
  1067. // declarations with the same name, the same parameter-type-list, and
  1068. // the same template parameter lists cannot be overloaded if any of
  1069. // them, but not all, have a ref-qualifier (8.3.5).
  1070. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  1071. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  1072. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  1073. }
  1074. return true;
  1075. }
  1076. // We may not have applied the implicit const for a constexpr member
  1077. // function yet (because we haven't yet resolved whether this is a static
  1078. // or non-static member function). Add it now, on the assumption that this
  1079. // is a redeclaration of OldMethod.
  1080. auto OldQuals = OldMethod->getMethodQualifiers();
  1081. auto NewQuals = NewMethod->getMethodQualifiers();
  1082. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  1083. !isa<CXXConstructorDecl>(NewMethod))
  1084. NewQuals.addConst();
  1085. // We do not allow overloading based off of '__restrict'.
  1086. OldQuals.removeRestrict();
  1087. NewQuals.removeRestrict();
  1088. if (OldQuals != NewQuals)
  1089. return true;
  1090. }
  1091. // Though pass_object_size is placed on parameters and takes an argument, we
  1092. // consider it to be a function-level modifier for the sake of function
  1093. // identity. Either the function has one or more parameters with
  1094. // pass_object_size or it doesn't.
  1095. if (functionHasPassObjectSizeParams(New) !=
  1096. functionHasPassObjectSizeParams(Old))
  1097. return true;
  1098. // enable_if attributes are an order-sensitive part of the signature.
  1099. for (specific_attr_iterator<EnableIfAttr>
  1100. NewI = New->specific_attr_begin<EnableIfAttr>(),
  1101. NewE = New->specific_attr_end<EnableIfAttr>(),
  1102. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  1103. OldE = Old->specific_attr_end<EnableIfAttr>();
  1104. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  1105. if (NewI == NewE || OldI == OldE)
  1106. return true;
  1107. llvm::FoldingSetNodeID NewID, OldID;
  1108. NewI->getCond()->Profile(NewID, Context, true);
  1109. OldI->getCond()->Profile(OldID, Context, true);
  1110. if (NewID != OldID)
  1111. return true;
  1112. }
  1113. if (getLangOpts().CUDA && ConsiderCudaAttrs) {
  1114. // Don't allow overloading of destructors. (In theory we could, but it
  1115. // would be a giant change to clang.)
  1116. if (isa<CXXDestructorDecl>(New))
  1117. return false;
  1118. CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
  1119. OldTarget = IdentifyCUDATarget(Old);
  1120. if (NewTarget == CFT_InvalidTarget)
  1121. return false;
  1122. assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
  1123. // Allow overloading of functions with same signature and different CUDA
  1124. // target attributes.
  1125. return NewTarget != OldTarget;
  1126. }
  1127. // The signatures match; this is not an overload.
  1128. return false;
  1129. }
  1130. /// Tries a user-defined conversion from From to ToType.
  1131. ///
  1132. /// Produces an implicit conversion sequence for when a standard conversion
  1133. /// is not an option. See TryImplicitConversion for more information.
  1134. static ImplicitConversionSequence
  1135. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1136. bool SuppressUserConversions,
  1137. bool AllowExplicit,
  1138. bool InOverloadResolution,
  1139. bool CStyle,
  1140. bool AllowObjCWritebackConversion,
  1141. bool AllowObjCConversionOnExplicit) {
  1142. ImplicitConversionSequence ICS;
  1143. if (SuppressUserConversions) {
  1144. // We're not in the case above, so there is no conversion that
  1145. // we can perform.
  1146. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1147. return ICS;
  1148. }
  1149. // Attempt user-defined conversion.
  1150. OverloadCandidateSet Conversions(From->getExprLoc(),
  1151. OverloadCandidateSet::CSK_Normal);
  1152. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1153. Conversions, AllowExplicit,
  1154. AllowObjCConversionOnExplicit)) {
  1155. case OR_Success:
  1156. case OR_Deleted:
  1157. ICS.setUserDefined();
  1158. // C++ [over.ics.user]p4:
  1159. // A conversion of an expression of class type to the same class
  1160. // type is given Exact Match rank, and a conversion of an
  1161. // expression of class type to a base class of that type is
  1162. // given Conversion rank, in spite of the fact that a copy
  1163. // constructor (i.e., a user-defined conversion function) is
  1164. // called for those cases.
  1165. if (CXXConstructorDecl *Constructor
  1166. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1167. QualType FromCanon
  1168. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1169. QualType ToCanon
  1170. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1171. if (Constructor->isCopyConstructor() &&
  1172. (FromCanon == ToCanon ||
  1173. S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
  1174. // Turn this into a "standard" conversion sequence, so that it
  1175. // gets ranked with standard conversion sequences.
  1176. DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
  1177. ICS.setStandard();
  1178. ICS.Standard.setAsIdentityConversion();
  1179. ICS.Standard.setFromType(From->getType());
  1180. ICS.Standard.setAllToTypes(ToType);
  1181. ICS.Standard.CopyConstructor = Constructor;
  1182. ICS.Standard.FoundCopyConstructor = Found;
  1183. if (ToCanon != FromCanon)
  1184. ICS.Standard.Second = ICK_Derived_To_Base;
  1185. }
  1186. }
  1187. break;
  1188. case OR_Ambiguous:
  1189. ICS.setAmbiguous();
  1190. ICS.Ambiguous.setFromType(From->getType());
  1191. ICS.Ambiguous.setToType(ToType);
  1192. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1193. Cand != Conversions.end(); ++Cand)
  1194. if (Cand->Viable)
  1195. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  1196. break;
  1197. // Fall through.
  1198. case OR_No_Viable_Function:
  1199. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1200. break;
  1201. }
  1202. return ICS;
  1203. }
  1204. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1205. /// from the given expression (Expr) to the given type (ToType). This
  1206. /// function returns an implicit conversion sequence that can be used
  1207. /// to perform the initialization. Given
  1208. ///
  1209. /// void f(float f);
  1210. /// void g(int i) { f(i); }
  1211. ///
  1212. /// this routine would produce an implicit conversion sequence to
  1213. /// describe the initialization of f from i, which will be a standard
  1214. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1215. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1216. //
  1217. /// Note that this routine only determines how the conversion can be
  1218. /// performed; it does not actually perform the conversion. As such,
  1219. /// it will not produce any diagnostics if no conversion is available,
  1220. /// but will instead return an implicit conversion sequence of kind
  1221. /// "BadConversion".
  1222. ///
  1223. /// If @p SuppressUserConversions, then user-defined conversions are
  1224. /// not permitted.
  1225. /// If @p AllowExplicit, then explicit user-defined conversions are
  1226. /// permitted.
  1227. ///
  1228. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1229. /// writeback conversion, which allows __autoreleasing id* parameters to
  1230. /// be initialized with __strong id* or __weak id* arguments.
  1231. static ImplicitConversionSequence
  1232. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1233. bool SuppressUserConversions,
  1234. bool AllowExplicit,
  1235. bool InOverloadResolution,
  1236. bool CStyle,
  1237. bool AllowObjCWritebackConversion,
  1238. bool AllowObjCConversionOnExplicit) {
  1239. ImplicitConversionSequence ICS;
  1240. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1241. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1242. ICS.setStandard();
  1243. return ICS;
  1244. }
  1245. if (!S.getLangOpts().CPlusPlus) {
  1246. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1247. return ICS;
  1248. }
  1249. // C++ [over.ics.user]p4:
  1250. // A conversion of an expression of class type to the same class
  1251. // type is given Exact Match rank, and a conversion of an
  1252. // expression of class type to a base class of that type is
  1253. // given Conversion rank, in spite of the fact that a copy/move
  1254. // constructor (i.e., a user-defined conversion function) is
  1255. // called for those cases.
  1256. QualType FromType = From->getType();
  1257. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1258. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1259. S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
  1260. ICS.setStandard();
  1261. ICS.Standard.setAsIdentityConversion();
  1262. ICS.Standard.setFromType(FromType);
  1263. ICS.Standard.setAllToTypes(ToType);
  1264. // We don't actually check at this point whether there is a valid
  1265. // copy/move constructor, since overloading just assumes that it
  1266. // exists. When we actually perform initialization, we'll find the
  1267. // appropriate constructor to copy the returned object, if needed.
  1268. ICS.Standard.CopyConstructor = nullptr;
  1269. // Determine whether this is considered a derived-to-base conversion.
  1270. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1271. ICS.Standard.Second = ICK_Derived_To_Base;
  1272. return ICS;
  1273. }
  1274. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1275. AllowExplicit, InOverloadResolution, CStyle,
  1276. AllowObjCWritebackConversion,
  1277. AllowObjCConversionOnExplicit);
  1278. }
  1279. ImplicitConversionSequence
  1280. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1281. bool SuppressUserConversions,
  1282. bool AllowExplicit,
  1283. bool InOverloadResolution,
  1284. bool CStyle,
  1285. bool AllowObjCWritebackConversion) {
  1286. return ::TryImplicitConversion(*this, From, ToType,
  1287. SuppressUserConversions, AllowExplicit,
  1288. InOverloadResolution, CStyle,
  1289. AllowObjCWritebackConversion,
  1290. /*AllowObjCConversionOnExplicit=*/false);
  1291. }
  1292. /// PerformImplicitConversion - Perform an implicit conversion of the
  1293. /// expression From to the type ToType. Returns the
  1294. /// converted expression. Flavor is the kind of conversion we're
  1295. /// performing, used in the error message. If @p AllowExplicit,
  1296. /// explicit user-defined conversions are permitted.
  1297. ExprResult
  1298. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1299. AssignmentAction Action, bool AllowExplicit) {
  1300. ImplicitConversionSequence ICS;
  1301. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1302. }
  1303. ExprResult
  1304. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1305. AssignmentAction Action, bool AllowExplicit,
  1306. ImplicitConversionSequence& ICS) {
  1307. if (checkPlaceholderForOverload(*this, From))
  1308. return ExprError();
  1309. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1310. bool AllowObjCWritebackConversion
  1311. = getLangOpts().ObjCAutoRefCount &&
  1312. (Action == AA_Passing || Action == AA_Sending);
  1313. if (getLangOpts().ObjC)
  1314. CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
  1315. From->getType(), From);
  1316. ICS = ::TryImplicitConversion(*this, From, ToType,
  1317. /*SuppressUserConversions=*/false,
  1318. AllowExplicit,
  1319. /*InOverloadResolution=*/false,
  1320. /*CStyle=*/false,
  1321. AllowObjCWritebackConversion,
  1322. /*AllowObjCConversionOnExplicit=*/false);
  1323. return PerformImplicitConversion(From, ToType, ICS, Action);
  1324. }
  1325. /// Determine whether the conversion from FromType to ToType is a valid
  1326. /// conversion that strips "noexcept" or "noreturn" off the nested function
  1327. /// type.
  1328. bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
  1329. QualType &ResultTy) {
  1330. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1331. return false;
  1332. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1333. // or F(t noexcept) -> F(t)
  1334. // where F adds one of the following at most once:
  1335. // - a pointer
  1336. // - a member pointer
  1337. // - a block pointer
  1338. // Changes here need matching changes in FindCompositePointerType.
  1339. CanQualType CanTo = Context.getCanonicalType(ToType);
  1340. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1341. Type::TypeClass TyClass = CanTo->getTypeClass();
  1342. if (TyClass != CanFrom->getTypeClass()) return false;
  1343. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1344. if (TyClass == Type::Pointer) {
  1345. CanTo = CanTo.castAs<PointerType>()->getPointeeType();
  1346. CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
  1347. } else if (TyClass == Type::BlockPointer) {
  1348. CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
  1349. CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
  1350. } else if (TyClass == Type::MemberPointer) {
  1351. auto ToMPT = CanTo.castAs<MemberPointerType>();
  1352. auto FromMPT = CanFrom.castAs<MemberPointerType>();
  1353. // A function pointer conversion cannot change the class of the function.
  1354. if (ToMPT->getClass() != FromMPT->getClass())
  1355. return false;
  1356. CanTo = ToMPT->getPointeeType();
  1357. CanFrom = FromMPT->getPointeeType();
  1358. } else {
  1359. return false;
  1360. }
  1361. TyClass = CanTo->getTypeClass();
  1362. if (TyClass != CanFrom->getTypeClass()) return false;
  1363. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1364. return false;
  1365. }
  1366. const auto *FromFn = cast<FunctionType>(CanFrom);
  1367. FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
  1368. const auto *ToFn = cast<FunctionType>(CanTo);
  1369. FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
  1370. bool Changed = false;
  1371. // Drop 'noreturn' if not present in target type.
  1372. if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
  1373. FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
  1374. Changed = true;
  1375. }
  1376. // Drop 'noexcept' if not present in target type.
  1377. if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
  1378. const auto *ToFPT = cast<FunctionProtoType>(ToFn);
  1379. if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
  1380. FromFn = cast<FunctionType>(
  1381. Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
  1382. EST_None)
  1383. .getTypePtr());
  1384. Changed = true;
  1385. }
  1386. // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
  1387. // only if the ExtParameterInfo lists of the two function prototypes can be
  1388. // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
  1389. SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
  1390. bool CanUseToFPT, CanUseFromFPT;
  1391. if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
  1392. CanUseFromFPT, NewParamInfos) &&
  1393. CanUseToFPT && !CanUseFromFPT) {
  1394. FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
  1395. ExtInfo.ExtParameterInfos =
  1396. NewParamInfos.empty() ? nullptr : NewParamInfos.data();
  1397. QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
  1398. FromFPT->getParamTypes(), ExtInfo);
  1399. FromFn = QT->getAs<FunctionType>();
  1400. Changed = true;
  1401. }
  1402. }
  1403. if (!Changed)
  1404. return false;
  1405. assert(QualType(FromFn, 0).isCanonical());
  1406. if (QualType(FromFn, 0) != CanTo) return false;
  1407. ResultTy = ToType;
  1408. return true;
  1409. }
  1410. /// Determine whether the conversion from FromType to ToType is a valid
  1411. /// vector conversion.
  1412. ///
  1413. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1414. /// conversion.
  1415. static bool IsVectorConversion(Sema &S, QualType FromType,
  1416. QualType ToType, ImplicitConversionKind &ICK) {
  1417. // We need at least one of these types to be a vector type to have a vector
  1418. // conversion.
  1419. if (!ToType->isVectorType() && !FromType->isVectorType())
  1420. return false;
  1421. // Identical types require no conversions.
  1422. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1423. return false;
  1424. // There are no conversions between extended vector types, only identity.
  1425. if (ToType->isExtVectorType()) {
  1426. // There are no conversions between extended vector types other than the
  1427. // identity conversion.
  1428. if (FromType->isExtVectorType())
  1429. return false;
  1430. // Vector splat from any arithmetic type to a vector.
  1431. if (FromType->isArithmeticType()) {
  1432. ICK = ICK_Vector_Splat;
  1433. return true;
  1434. }
  1435. }
  1436. // We can perform the conversion between vector types in the following cases:
  1437. // 1)vector types are equivalent AltiVec and GCC vector types
  1438. // 2)lax vector conversions are permitted and the vector types are of the
  1439. // same size
  1440. if (ToType->isVectorType() && FromType->isVectorType()) {
  1441. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1442. S.isLaxVectorConversion(FromType, ToType)) {
  1443. ICK = ICK_Vector_Conversion;
  1444. return true;
  1445. }
  1446. }
  1447. return false;
  1448. }
  1449. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1450. bool InOverloadResolution,
  1451. StandardConversionSequence &SCS,
  1452. bool CStyle);
  1453. /// IsStandardConversion - Determines whether there is a standard
  1454. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1455. /// expression From to the type ToType. Standard conversion sequences
  1456. /// only consider non-class types; for conversions that involve class
  1457. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1458. /// contain the standard conversion sequence required to perform this
  1459. /// conversion and this routine will return true. Otherwise, this
  1460. /// routine will return false and the value of SCS is unspecified.
  1461. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1462. bool InOverloadResolution,
  1463. StandardConversionSequence &SCS,
  1464. bool CStyle,
  1465. bool AllowObjCWritebackConversion) {
  1466. QualType FromType = From->getType();
  1467. // Standard conversions (C++ [conv])
  1468. SCS.setAsIdentityConversion();
  1469. SCS.IncompatibleObjC = false;
  1470. SCS.setFromType(FromType);
  1471. SCS.CopyConstructor = nullptr;
  1472. // There are no standard conversions for class types in C++, so
  1473. // abort early. When overloading in C, however, we do permit them.
  1474. if (S.getLangOpts().CPlusPlus &&
  1475. (FromType->isRecordType() || ToType->isRecordType()))
  1476. return false;
  1477. // The first conversion can be an lvalue-to-rvalue conversion,
  1478. // array-to-pointer conversion, or function-to-pointer conversion
  1479. // (C++ 4p1).
  1480. if (FromType == S.Context.OverloadTy) {
  1481. DeclAccessPair AccessPair;
  1482. if (FunctionDecl *Fn
  1483. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1484. AccessPair)) {
  1485. // We were able to resolve the address of the overloaded function,
  1486. // so we can convert to the type of that function.
  1487. FromType = Fn->getType();
  1488. SCS.setFromType(FromType);
  1489. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1490. // if the type matches (identity) or we are converting to bool
  1491. if (!S.Context.hasSameUnqualifiedType(
  1492. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1493. QualType resultTy;
  1494. // if the function type matches except for [[noreturn]], it's ok
  1495. if (!S.IsFunctionConversion(FromType,
  1496. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1497. // otherwise, only a boolean conversion is standard
  1498. if (!ToType->isBooleanType())
  1499. return false;
  1500. }
  1501. // Check if the "from" expression is taking the address of an overloaded
  1502. // function and recompute the FromType accordingly. Take advantage of the
  1503. // fact that non-static member functions *must* have such an address-of
  1504. // expression.
  1505. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1506. if (Method && !Method->isStatic()) {
  1507. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1508. "Non-unary operator on non-static member address");
  1509. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1510. == UO_AddrOf &&
  1511. "Non-address-of operator on non-static member address");
  1512. const Type *ClassType
  1513. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1514. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1515. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1516. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1517. UO_AddrOf &&
  1518. "Non-address-of operator for overloaded function expression");
  1519. FromType = S.Context.getPointerType(FromType);
  1520. }
  1521. // Check that we've computed the proper type after overload resolution.
  1522. // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
  1523. // be calling it from within an NDEBUG block.
  1524. assert(S.Context.hasSameType(
  1525. FromType,
  1526. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1527. } else {
  1528. return false;
  1529. }
  1530. }
  1531. // Lvalue-to-rvalue conversion (C++11 4.1):
  1532. // A glvalue (3.10) of a non-function, non-array type T can
  1533. // be converted to a prvalue.
  1534. bool argIsLValue = From->isGLValue();
  1535. if (argIsLValue &&
  1536. !FromType->isFunctionType() && !FromType->isArrayType() &&
  1537. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1538. SCS.First = ICK_Lvalue_To_Rvalue;
  1539. // C11 6.3.2.1p2:
  1540. // ... if the lvalue has atomic type, the value has the non-atomic version
  1541. // of the type of the lvalue ...
  1542. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1543. FromType = Atomic->getValueType();
  1544. // If T is a non-class type, the type of the rvalue is the
  1545. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1546. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1547. // just strip the qualifiers because they don't matter.
  1548. FromType = FromType.getUnqualifiedType();
  1549. } else if (FromType->isArrayType()) {
  1550. // Array-to-pointer conversion (C++ 4.2)
  1551. SCS.First = ICK_Array_To_Pointer;
  1552. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1553. // bound of T" can be converted to an rvalue of type "pointer to
  1554. // T" (C++ 4.2p1).
  1555. FromType = S.Context.getArrayDecayedType(FromType);
  1556. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1557. // This conversion is deprecated in C++03 (D.4)
  1558. SCS.DeprecatedStringLiteralToCharPtr = true;
  1559. // For the purpose of ranking in overload resolution
  1560. // (13.3.3.1.1), this conversion is considered an
  1561. // array-to-pointer conversion followed by a qualification
  1562. // conversion (4.4). (C++ 4.2p2)
  1563. SCS.Second = ICK_Identity;
  1564. SCS.Third = ICK_Qualification;
  1565. SCS.QualificationIncludesObjCLifetime = false;
  1566. SCS.setAllToTypes(FromType);
  1567. return true;
  1568. }
  1569. } else if (FromType->isFunctionType() && argIsLValue) {
  1570. // Function-to-pointer conversion (C++ 4.3).
  1571. SCS.First = ICK_Function_To_Pointer;
  1572. if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
  1573. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  1574. if (!S.checkAddressOfFunctionIsAvailable(FD))
  1575. return false;
  1576. // An lvalue of function type T can be converted to an rvalue of
  1577. // type "pointer to T." The result is a pointer to the
  1578. // function. (C++ 4.3p1).
  1579. FromType = S.Context.getPointerType(FromType);
  1580. } else {
  1581. // We don't require any conversions for the first step.
  1582. SCS.First = ICK_Identity;
  1583. }
  1584. SCS.setToType(0, FromType);
  1585. // The second conversion can be an integral promotion, floating
  1586. // point promotion, integral conversion, floating point conversion,
  1587. // floating-integral conversion, pointer conversion,
  1588. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1589. // For overloading in C, this can also be a "compatible-type"
  1590. // conversion.
  1591. bool IncompatibleObjC = false;
  1592. ImplicitConversionKind SecondICK = ICK_Identity;
  1593. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1594. // The unqualified versions of the types are the same: there's no
  1595. // conversion to do.
  1596. SCS.Second = ICK_Identity;
  1597. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1598. // Integral promotion (C++ 4.5).
  1599. SCS.Second = ICK_Integral_Promotion;
  1600. FromType = ToType.getUnqualifiedType();
  1601. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1602. // Floating point promotion (C++ 4.6).
  1603. SCS.Second = ICK_Floating_Promotion;
  1604. FromType = ToType.getUnqualifiedType();
  1605. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1606. // Complex promotion (Clang extension)
  1607. SCS.Second = ICK_Complex_Promotion;
  1608. FromType = ToType.getUnqualifiedType();
  1609. } else if (ToType->isBooleanType() &&
  1610. (FromType->isArithmeticType() ||
  1611. FromType->isAnyPointerType() ||
  1612. FromType->isBlockPointerType() ||
  1613. FromType->isMemberPointerType() ||
  1614. FromType->isNullPtrType())) {
  1615. // Boolean conversions (C++ 4.12).
  1616. SCS.Second = ICK_Boolean_Conversion;
  1617. FromType = S.Context.BoolTy;
  1618. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1619. ToType->isIntegralType(S.Context)) {
  1620. // Integral conversions (C++ 4.7).
  1621. SCS.Second = ICK_Integral_Conversion;
  1622. FromType = ToType.getUnqualifiedType();
  1623. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1624. // Complex conversions (C99 6.3.1.6)
  1625. SCS.Second = ICK_Complex_Conversion;
  1626. FromType = ToType.getUnqualifiedType();
  1627. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1628. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1629. // Complex-real conversions (C99 6.3.1.7)
  1630. SCS.Second = ICK_Complex_Real;
  1631. FromType = ToType.getUnqualifiedType();
  1632. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1633. // FIXME: disable conversions between long double and __float128 if
  1634. // their representation is different until there is back end support
  1635. // We of course allow this conversion if long double is really double.
  1636. if (&S.Context.getFloatTypeSemantics(FromType) !=
  1637. &S.Context.getFloatTypeSemantics(ToType)) {
  1638. bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
  1639. ToType == S.Context.LongDoubleTy) ||
  1640. (FromType == S.Context.LongDoubleTy &&
  1641. ToType == S.Context.Float128Ty));
  1642. if (Float128AndLongDouble &&
  1643. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  1644. &llvm::APFloat::PPCDoubleDouble()))
  1645. return false;
  1646. }
  1647. // Floating point conversions (C++ 4.8).
  1648. SCS.Second = ICK_Floating_Conversion;
  1649. FromType = ToType.getUnqualifiedType();
  1650. } else if ((FromType->isRealFloatingType() &&
  1651. ToType->isIntegralType(S.Context)) ||
  1652. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1653. ToType->isRealFloatingType())) {
  1654. // Floating-integral conversions (C++ 4.9).
  1655. SCS.Second = ICK_Floating_Integral;
  1656. FromType = ToType.getUnqualifiedType();
  1657. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1658. SCS.Second = ICK_Block_Pointer_Conversion;
  1659. } else if (AllowObjCWritebackConversion &&
  1660. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1661. SCS.Second = ICK_Writeback_Conversion;
  1662. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1663. FromType, IncompatibleObjC)) {
  1664. // Pointer conversions (C++ 4.10).
  1665. SCS.Second = ICK_Pointer_Conversion;
  1666. SCS.IncompatibleObjC = IncompatibleObjC;
  1667. FromType = FromType.getUnqualifiedType();
  1668. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1669. InOverloadResolution, FromType)) {
  1670. // Pointer to member conversions (4.11).
  1671. SCS.Second = ICK_Pointer_Member;
  1672. } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
  1673. SCS.Second = SecondICK;
  1674. FromType = ToType.getUnqualifiedType();
  1675. } else if (!S.getLangOpts().CPlusPlus &&
  1676. S.Context.typesAreCompatible(ToType, FromType)) {
  1677. // Compatible conversions (Clang extension for C function overloading)
  1678. SCS.Second = ICK_Compatible_Conversion;
  1679. FromType = ToType.getUnqualifiedType();
  1680. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1681. InOverloadResolution,
  1682. SCS, CStyle)) {
  1683. SCS.Second = ICK_TransparentUnionConversion;
  1684. FromType = ToType;
  1685. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1686. CStyle)) {
  1687. // tryAtomicConversion has updated the standard conversion sequence
  1688. // appropriately.
  1689. return true;
  1690. } else if (ToType->isEventT() &&
  1691. From->isIntegerConstantExpr(S.getASTContext()) &&
  1692. From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
  1693. SCS.Second = ICK_Zero_Event_Conversion;
  1694. FromType = ToType;
  1695. } else if (ToType->isQueueT() &&
  1696. From->isIntegerConstantExpr(S.getASTContext()) &&
  1697. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1698. SCS.Second = ICK_Zero_Queue_Conversion;
  1699. FromType = ToType;
  1700. } else if (ToType->isSamplerT() &&
  1701. From->isIntegerConstantExpr(S.getASTContext())) {
  1702. SCS.Second = ICK_Compatible_Conversion;
  1703. FromType = ToType;
  1704. } else {
  1705. // No second conversion required.
  1706. SCS.Second = ICK_Identity;
  1707. }
  1708. SCS.setToType(1, FromType);
  1709. // The third conversion can be a function pointer conversion or a
  1710. // qualification conversion (C++ [conv.fctptr], [conv.qual]).
  1711. bool ObjCLifetimeConversion;
  1712. if (S.IsFunctionConversion(FromType, ToType, FromType)) {
  1713. // Function pointer conversions (removing 'noexcept') including removal of
  1714. // 'noreturn' (Clang extension).
  1715. SCS.Third = ICK_Function_Conversion;
  1716. } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1717. ObjCLifetimeConversion)) {
  1718. SCS.Third = ICK_Qualification;
  1719. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1720. FromType = ToType;
  1721. } else {
  1722. // No conversion required
  1723. SCS.Third = ICK_Identity;
  1724. }
  1725. // C++ [over.best.ics]p6:
  1726. // [...] Any difference in top-level cv-qualification is
  1727. // subsumed by the initialization itself and does not constitute
  1728. // a conversion. [...]
  1729. QualType CanonFrom = S.Context.getCanonicalType(FromType);
  1730. QualType CanonTo = S.Context.getCanonicalType(ToType);
  1731. if (CanonFrom.getLocalUnqualifiedType()
  1732. == CanonTo.getLocalUnqualifiedType() &&
  1733. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1734. FromType = ToType;
  1735. CanonFrom = CanonTo;
  1736. }
  1737. SCS.setToType(2, FromType);
  1738. if (CanonFrom == CanonTo)
  1739. return true;
  1740. // If we have not converted the argument type to the parameter type,
  1741. // this is a bad conversion sequence, unless we're resolving an overload in C.
  1742. if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
  1743. return false;
  1744. ExprResult ER = ExprResult{From};
  1745. Sema::AssignConvertType Conv =
  1746. S.CheckSingleAssignmentConstraints(ToType, ER,
  1747. /*Diagnose=*/false,
  1748. /*DiagnoseCFAudited=*/false,
  1749. /*ConvertRHS=*/false);
  1750. ImplicitConversionKind SecondConv;
  1751. switch (Conv) {
  1752. case Sema::Compatible:
  1753. SecondConv = ICK_C_Only_Conversion;
  1754. break;
  1755. // For our purposes, discarding qualifiers is just as bad as using an
  1756. // incompatible pointer. Note that an IncompatiblePointer conversion can drop
  1757. // qualifiers, as well.
  1758. case Sema::CompatiblePointerDiscardsQualifiers:
  1759. case Sema::IncompatiblePointer:
  1760. case Sema::IncompatiblePointerSign:
  1761. SecondConv = ICK_Incompatible_Pointer_Conversion;
  1762. break;
  1763. default:
  1764. return false;
  1765. }
  1766. // First can only be an lvalue conversion, so we pretend that this was the
  1767. // second conversion. First should already be valid from earlier in the
  1768. // function.
  1769. SCS.Second = SecondConv;
  1770. SCS.setToType(1, ToType);
  1771. // Third is Identity, because Second should rank us worse than any other
  1772. // conversion. This could also be ICK_Qualification, but it's simpler to just
  1773. // lump everything in with the second conversion, and we don't gain anything
  1774. // from making this ICK_Qualification.
  1775. SCS.Third = ICK_Identity;
  1776. SCS.setToType(2, ToType);
  1777. return true;
  1778. }
  1779. static bool
  1780. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1781. QualType &ToType,
  1782. bool InOverloadResolution,
  1783. StandardConversionSequence &SCS,
  1784. bool CStyle) {
  1785. const RecordType *UT = ToType->getAsUnionType();
  1786. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1787. return false;
  1788. // The field to initialize within the transparent union.
  1789. RecordDecl *UD = UT->getDecl();
  1790. // It's compatible if the expression matches any of the fields.
  1791. for (const auto *it : UD->fields()) {
  1792. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1793. CStyle, /*AllowObjCWritebackConversion=*/false)) {
  1794. ToType = it->getType();
  1795. return true;
  1796. }
  1797. }
  1798. return false;
  1799. }
  1800. /// IsIntegralPromotion - Determines whether the conversion from the
  1801. /// expression From (whose potentially-adjusted type is FromType) to
  1802. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1803. /// sets PromotedType to the promoted type.
  1804. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1805. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1806. // All integers are built-in.
  1807. if (!To) {
  1808. return false;
  1809. }
  1810. // An rvalue of type char, signed char, unsigned char, short int, or
  1811. // unsigned short int can be converted to an rvalue of type int if
  1812. // int can represent all the values of the source type; otherwise,
  1813. // the source rvalue can be converted to an rvalue of type unsigned
  1814. // int (C++ 4.5p1).
  1815. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1816. !FromType->isEnumeralType()) {
  1817. if (// We can promote any signed, promotable integer type to an int
  1818. (FromType->isSignedIntegerType() ||
  1819. // We can promote any unsigned integer type whose size is
  1820. // less than int to an int.
  1821. Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
  1822. return To->getKind() == BuiltinType::Int;
  1823. }
  1824. return To->getKind() == BuiltinType::UInt;
  1825. }
  1826. // C++11 [conv.prom]p3:
  1827. // A prvalue of an unscoped enumeration type whose underlying type is not
  1828. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1829. // following types that can represent all the values of the enumeration
  1830. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1831. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1832. // long long int. If none of the types in that list can represent all the
  1833. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1834. // type can be converted to an rvalue a prvalue of the extended integer type
  1835. // with lowest integer conversion rank (4.13) greater than the rank of long
  1836. // long in which all the values of the enumeration can be represented. If
  1837. // there are two such extended types, the signed one is chosen.
  1838. // C++11 [conv.prom]p4:
  1839. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  1840. // can be converted to a prvalue of its underlying type. Moreover, if
  1841. // integral promotion can be applied to its underlying type, a prvalue of an
  1842. // unscoped enumeration type whose underlying type is fixed can also be
  1843. // converted to a prvalue of the promoted underlying type.
  1844. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1845. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1846. // provided for a scoped enumeration.
  1847. if (FromEnumType->getDecl()->isScoped())
  1848. return false;
  1849. // We can perform an integral promotion to the underlying type of the enum,
  1850. // even if that's not the promoted type. Note that the check for promoting
  1851. // the underlying type is based on the type alone, and does not consider
  1852. // the bitfield-ness of the actual source expression.
  1853. if (FromEnumType->getDecl()->isFixed()) {
  1854. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  1855. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  1856. IsIntegralPromotion(nullptr, Underlying, ToType);
  1857. }
  1858. // We have already pre-calculated the promotion type, so this is trivial.
  1859. if (ToType->isIntegerType() &&
  1860. isCompleteType(From->getBeginLoc(), FromType))
  1861. return Context.hasSameUnqualifiedType(
  1862. ToType, FromEnumType->getDecl()->getPromotionType());
  1863. // C++ [conv.prom]p5:
  1864. // If the bit-field has an enumerated type, it is treated as any other
  1865. // value of that type for promotion purposes.
  1866. //
  1867. // ... so do not fall through into the bit-field checks below in C++.
  1868. if (getLangOpts().CPlusPlus)
  1869. return false;
  1870. }
  1871. // C++0x [conv.prom]p2:
  1872. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1873. // to an rvalue a prvalue of the first of the following types that can
  1874. // represent all the values of its underlying type: int, unsigned int,
  1875. // long int, unsigned long int, long long int, or unsigned long long int.
  1876. // If none of the types in that list can represent all the values of its
  1877. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1878. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1879. // type.
  1880. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1881. ToType->isIntegerType()) {
  1882. // Determine whether the type we're converting from is signed or
  1883. // unsigned.
  1884. bool FromIsSigned = FromType->isSignedIntegerType();
  1885. uint64_t FromSize = Context.getTypeSize(FromType);
  1886. // The types we'll try to promote to, in the appropriate
  1887. // order. Try each of these types.
  1888. QualType PromoteTypes[6] = {
  1889. Context.IntTy, Context.UnsignedIntTy,
  1890. Context.LongTy, Context.UnsignedLongTy ,
  1891. Context.LongLongTy, Context.UnsignedLongLongTy
  1892. };
  1893. for (int Idx = 0; Idx < 6; ++Idx) {
  1894. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1895. if (FromSize < ToSize ||
  1896. (FromSize == ToSize &&
  1897. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1898. // We found the type that we can promote to. If this is the
  1899. // type we wanted, we have a promotion. Otherwise, no
  1900. // promotion.
  1901. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1902. }
  1903. }
  1904. }
  1905. // An rvalue for an integral bit-field (9.6) can be converted to an
  1906. // rvalue of type int if int can represent all the values of the
  1907. // bit-field; otherwise, it can be converted to unsigned int if
  1908. // unsigned int can represent all the values of the bit-field. If
  1909. // the bit-field is larger yet, no integral promotion applies to
  1910. // it. If the bit-field has an enumerated type, it is treated as any
  1911. // other value of that type for promotion purposes (C++ 4.5p3).
  1912. // FIXME: We should delay checking of bit-fields until we actually perform the
  1913. // conversion.
  1914. //
  1915. // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
  1916. // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
  1917. // bit-fields and those whose underlying type is larger than int) for GCC
  1918. // compatibility.
  1919. if (From) {
  1920. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  1921. llvm::APSInt BitWidth;
  1922. if (FromType->isIntegralType(Context) &&
  1923. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1924. llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1925. ToSize = Context.getTypeSize(ToType);
  1926. // Are we promoting to an int from a bitfield that fits in an int?
  1927. if (BitWidth < ToSize ||
  1928. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1929. return To->getKind() == BuiltinType::Int;
  1930. }
  1931. // Are we promoting to an unsigned int from an unsigned bitfield
  1932. // that fits into an unsigned int?
  1933. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1934. return To->getKind() == BuiltinType::UInt;
  1935. }
  1936. return false;
  1937. }
  1938. }
  1939. }
  1940. // An rvalue of type bool can be converted to an rvalue of type int,
  1941. // with false becoming zero and true becoming one (C++ 4.5p4).
  1942. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1943. return true;
  1944. }
  1945. return false;
  1946. }
  1947. /// IsFloatingPointPromotion - Determines whether the conversion from
  1948. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1949. /// returns true and sets PromotedType to the promoted type.
  1950. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1951. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1952. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1953. /// An rvalue of type float can be converted to an rvalue of type
  1954. /// double. (C++ 4.6p1).
  1955. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1956. ToBuiltin->getKind() == BuiltinType::Double)
  1957. return true;
  1958. // C99 6.3.1.5p1:
  1959. // When a float is promoted to double or long double, or a
  1960. // double is promoted to long double [...].
  1961. if (!getLangOpts().CPlusPlus &&
  1962. (FromBuiltin->getKind() == BuiltinType::Float ||
  1963. FromBuiltin->getKind() == BuiltinType::Double) &&
  1964. (ToBuiltin->getKind() == BuiltinType::LongDouble ||
  1965. ToBuiltin->getKind() == BuiltinType::Float128))
  1966. return true;
  1967. // Half can be promoted to float.
  1968. if (!getLangOpts().NativeHalfType &&
  1969. FromBuiltin->getKind() == BuiltinType::Half &&
  1970. ToBuiltin->getKind() == BuiltinType::Float)
  1971. return true;
  1972. }
  1973. return false;
  1974. }
  1975. /// Determine if a conversion is a complex promotion.
  1976. ///
  1977. /// A complex promotion is defined as a complex -> complex conversion
  1978. /// where the conversion between the underlying real types is a
  1979. /// floating-point or integral promotion.
  1980. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1981. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1982. if (!FromComplex)
  1983. return false;
  1984. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1985. if (!ToComplex)
  1986. return false;
  1987. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1988. ToComplex->getElementType()) ||
  1989. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  1990. ToComplex->getElementType());
  1991. }
  1992. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1993. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1994. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1995. /// if non-empty, will be a pointer to ToType that may or may not have
  1996. /// the right set of qualifiers on its pointee.
  1997. ///
  1998. static QualType
  1999. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  2000. QualType ToPointee, QualType ToType,
  2001. ASTContext &Context,
  2002. bool StripObjCLifetime = false) {
  2003. assert((FromPtr->getTypeClass() == Type::Pointer ||
  2004. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  2005. "Invalid similarly-qualified pointer type");
  2006. /// Conversions to 'id' subsume cv-qualifier conversions.
  2007. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  2008. return ToType.getUnqualifiedType();
  2009. QualType CanonFromPointee
  2010. = Context.getCanonicalType(FromPtr->getPointeeType());
  2011. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  2012. Qualifiers Quals = CanonFromPointee.getQualifiers();
  2013. if (StripObjCLifetime)
  2014. Quals.removeObjCLifetime();
  2015. // Exact qualifier match -> return the pointer type we're converting to.
  2016. if (CanonToPointee.getLocalQualifiers() == Quals) {
  2017. // ToType is exactly what we need. Return it.
  2018. if (!ToType.isNull())
  2019. return ToType.getUnqualifiedType();
  2020. // Build a pointer to ToPointee. It has the right qualifiers
  2021. // already.
  2022. if (isa<ObjCObjectPointerType>(ToType))
  2023. return Context.getObjCObjectPointerType(ToPointee);
  2024. return Context.getPointerType(ToPointee);
  2025. }
  2026. // Just build a canonical type that has the right qualifiers.
  2027. QualType QualifiedCanonToPointee
  2028. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  2029. if (isa<ObjCObjectPointerType>(ToType))
  2030. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  2031. return Context.getPointerType(QualifiedCanonToPointee);
  2032. }
  2033. static bool isNullPointerConstantForConversion(Expr *Expr,
  2034. bool InOverloadResolution,
  2035. ASTContext &Context) {
  2036. // Handle value-dependent integral null pointer constants correctly.
  2037. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  2038. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  2039. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  2040. return !InOverloadResolution;
  2041. return Expr->isNullPointerConstant(Context,
  2042. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2043. : Expr::NPC_ValueDependentIsNull);
  2044. }
  2045. /// IsPointerConversion - Determines whether the conversion of the
  2046. /// expression From, which has the (possibly adjusted) type FromType,
  2047. /// can be converted to the type ToType via a pointer conversion (C++
  2048. /// 4.10). If so, returns true and places the converted type (that
  2049. /// might differ from ToType in its cv-qualifiers at some level) into
  2050. /// ConvertedType.
  2051. ///
  2052. /// This routine also supports conversions to and from block pointers
  2053. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  2054. /// pointers to interfaces. FIXME: Once we've determined the
  2055. /// appropriate overloading rules for Objective-C, we may want to
  2056. /// split the Objective-C checks into a different routine; however,
  2057. /// GCC seems to consider all of these conversions to be pointer
  2058. /// conversions, so for now they live here. IncompatibleObjC will be
  2059. /// set if the conversion is an allowed Objective-C conversion that
  2060. /// should result in a warning.
  2061. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  2062. bool InOverloadResolution,
  2063. QualType& ConvertedType,
  2064. bool &IncompatibleObjC) {
  2065. IncompatibleObjC = false;
  2066. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  2067. IncompatibleObjC))
  2068. return true;
  2069. // Conversion from a null pointer constant to any Objective-C pointer type.
  2070. if (ToType->isObjCObjectPointerType() &&
  2071. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2072. ConvertedType = ToType;
  2073. return true;
  2074. }
  2075. // Blocks: Block pointers can be converted to void*.
  2076. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  2077. ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  2078. ConvertedType = ToType;
  2079. return true;
  2080. }
  2081. // Blocks: A null pointer constant can be converted to a block
  2082. // pointer type.
  2083. if (ToType->isBlockPointerType() &&
  2084. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2085. ConvertedType = ToType;
  2086. return true;
  2087. }
  2088. // If the left-hand-side is nullptr_t, the right side can be a null
  2089. // pointer constant.
  2090. if (ToType->isNullPtrType() &&
  2091. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2092. ConvertedType = ToType;
  2093. return true;
  2094. }
  2095. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  2096. if (!ToTypePtr)
  2097. return false;
  2098. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  2099. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  2100. ConvertedType = ToType;
  2101. return true;
  2102. }
  2103. // Beyond this point, both types need to be pointers
  2104. // , including objective-c pointers.
  2105. QualType ToPointeeType = ToTypePtr->getPointeeType();
  2106. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  2107. !getLangOpts().ObjCAutoRefCount) {
  2108. ConvertedType = BuildSimilarlyQualifiedPointerType(
  2109. FromType->getAs<ObjCObjectPointerType>(),
  2110. ToPointeeType,
  2111. ToType, Context);
  2112. return true;
  2113. }
  2114. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  2115. if (!FromTypePtr)
  2116. return false;
  2117. QualType FromPointeeType = FromTypePtr->getPointeeType();
  2118. // If the unqualified pointee types are the same, this can't be a
  2119. // pointer conversion, so don't do all of the work below.
  2120. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  2121. return false;
  2122. // An rvalue of type "pointer to cv T," where T is an object type,
  2123. // can be converted to an rvalue of type "pointer to cv void" (C++
  2124. // 4.10p2).
  2125. if (FromPointeeType->isIncompleteOrObjectType() &&
  2126. ToPointeeType->isVoidType()) {
  2127. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2128. ToPointeeType,
  2129. ToType, Context,
  2130. /*StripObjCLifetime=*/true);
  2131. return true;
  2132. }
  2133. // MSVC allows implicit function to void* type conversion.
  2134. if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
  2135. ToPointeeType->isVoidType()) {
  2136. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2137. ToPointeeType,
  2138. ToType, Context);
  2139. return true;
  2140. }
  2141. // When we're overloading in C, we allow a special kind of pointer
  2142. // conversion for compatible-but-not-identical pointee types.
  2143. if (!getLangOpts().CPlusPlus &&
  2144. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  2145. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2146. ToPointeeType,
  2147. ToType, Context);
  2148. return true;
  2149. }
  2150. // C++ [conv.ptr]p3:
  2151. //
  2152. // An rvalue of type "pointer to cv D," where D is a class type,
  2153. // can be converted to an rvalue of type "pointer to cv B," where
  2154. // B is a base class (clause 10) of D. If B is an inaccessible
  2155. // (clause 11) or ambiguous (10.2) base class of D, a program that
  2156. // necessitates this conversion is ill-formed. The result of the
  2157. // conversion is a pointer to the base class sub-object of the
  2158. // derived class object. The null pointer value is converted to
  2159. // the null pointer value of the destination type.
  2160. //
  2161. // Note that we do not check for ambiguity or inaccessibility
  2162. // here. That is handled by CheckPointerConversion.
  2163. if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
  2164. ToPointeeType->isRecordType() &&
  2165. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  2166. IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
  2167. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2168. ToPointeeType,
  2169. ToType, Context);
  2170. return true;
  2171. }
  2172. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  2173. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  2174. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  2175. ToPointeeType,
  2176. ToType, Context);
  2177. return true;
  2178. }
  2179. return false;
  2180. }
  2181. /// Adopt the given qualifiers for the given type.
  2182. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  2183. Qualifiers TQs = T.getQualifiers();
  2184. // Check whether qualifiers already match.
  2185. if (TQs == Qs)
  2186. return T;
  2187. if (Qs.compatiblyIncludes(TQs))
  2188. return Context.getQualifiedType(T, Qs);
  2189. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  2190. }
  2191. /// isObjCPointerConversion - Determines whether this is an
  2192. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  2193. /// with the same arguments and return values.
  2194. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  2195. QualType& ConvertedType,
  2196. bool &IncompatibleObjC) {
  2197. if (!getLangOpts().ObjC)
  2198. return false;
  2199. // The set of qualifiers on the type we're converting from.
  2200. Qualifiers FromQualifiers = FromType.getQualifiers();
  2201. // First, we handle all conversions on ObjC object pointer types.
  2202. const ObjCObjectPointerType* ToObjCPtr =
  2203. ToType->getAs<ObjCObjectPointerType>();
  2204. const ObjCObjectPointerType *FromObjCPtr =
  2205. FromType->getAs<ObjCObjectPointerType>();
  2206. if (ToObjCPtr && FromObjCPtr) {
  2207. // If the pointee types are the same (ignoring qualifications),
  2208. // then this is not a pointer conversion.
  2209. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  2210. FromObjCPtr->getPointeeType()))
  2211. return false;
  2212. // Conversion between Objective-C pointers.
  2213. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  2214. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  2215. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  2216. if (getLangOpts().CPlusPlus && LHS && RHS &&
  2217. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  2218. FromObjCPtr->getPointeeType()))
  2219. return false;
  2220. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2221. ToObjCPtr->getPointeeType(),
  2222. ToType, Context);
  2223. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2224. return true;
  2225. }
  2226. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2227. // Okay: this is some kind of implicit downcast of Objective-C
  2228. // interfaces, which is permitted. However, we're going to
  2229. // complain about it.
  2230. IncompatibleObjC = true;
  2231. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2232. ToObjCPtr->getPointeeType(),
  2233. ToType, Context);
  2234. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2235. return true;
  2236. }
  2237. }
  2238. // Beyond this point, both types need to be C pointers or block pointers.
  2239. QualType ToPointeeType;
  2240. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2241. ToPointeeType = ToCPtr->getPointeeType();
  2242. else if (const BlockPointerType *ToBlockPtr =
  2243. ToType->getAs<BlockPointerType>()) {
  2244. // Objective C++: We're able to convert from a pointer to any object
  2245. // to a block pointer type.
  2246. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2247. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2248. return true;
  2249. }
  2250. ToPointeeType = ToBlockPtr->getPointeeType();
  2251. }
  2252. else if (FromType->getAs<BlockPointerType>() &&
  2253. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2254. // Objective C++: We're able to convert from a block pointer type to a
  2255. // pointer to any object.
  2256. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2257. return true;
  2258. }
  2259. else
  2260. return false;
  2261. QualType FromPointeeType;
  2262. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2263. FromPointeeType = FromCPtr->getPointeeType();
  2264. else if (const BlockPointerType *FromBlockPtr =
  2265. FromType->getAs<BlockPointerType>())
  2266. FromPointeeType = FromBlockPtr->getPointeeType();
  2267. else
  2268. return false;
  2269. // If we have pointers to pointers, recursively check whether this
  2270. // is an Objective-C conversion.
  2271. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2272. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2273. IncompatibleObjC)) {
  2274. // We always complain about this conversion.
  2275. IncompatibleObjC = true;
  2276. ConvertedType = Context.getPointerType(ConvertedType);
  2277. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2278. return true;
  2279. }
  2280. // Allow conversion of pointee being objective-c pointer to another one;
  2281. // as in I* to id.
  2282. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2283. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2284. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2285. IncompatibleObjC)) {
  2286. ConvertedType = Context.getPointerType(ConvertedType);
  2287. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2288. return true;
  2289. }
  2290. // If we have pointers to functions or blocks, check whether the only
  2291. // differences in the argument and result types are in Objective-C
  2292. // pointer conversions. If so, we permit the conversion (but
  2293. // complain about it).
  2294. const FunctionProtoType *FromFunctionType
  2295. = FromPointeeType->getAs<FunctionProtoType>();
  2296. const FunctionProtoType *ToFunctionType
  2297. = ToPointeeType->getAs<FunctionProtoType>();
  2298. if (FromFunctionType && ToFunctionType) {
  2299. // If the function types are exactly the same, this isn't an
  2300. // Objective-C pointer conversion.
  2301. if (Context.getCanonicalType(FromPointeeType)
  2302. == Context.getCanonicalType(ToPointeeType))
  2303. return false;
  2304. // Perform the quick checks that will tell us whether these
  2305. // function types are obviously different.
  2306. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2307. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2308. FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
  2309. return false;
  2310. bool HasObjCConversion = false;
  2311. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2312. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2313. // Okay, the types match exactly. Nothing to do.
  2314. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2315. ToFunctionType->getReturnType(),
  2316. ConvertedType, IncompatibleObjC)) {
  2317. // Okay, we have an Objective-C pointer conversion.
  2318. HasObjCConversion = true;
  2319. } else {
  2320. // Function types are too different. Abort.
  2321. return false;
  2322. }
  2323. // Check argument types.
  2324. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2325. ArgIdx != NumArgs; ++ArgIdx) {
  2326. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2327. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2328. if (Context.getCanonicalType(FromArgType)
  2329. == Context.getCanonicalType(ToArgType)) {
  2330. // Okay, the types match exactly. Nothing to do.
  2331. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2332. ConvertedType, IncompatibleObjC)) {
  2333. // Okay, we have an Objective-C pointer conversion.
  2334. HasObjCConversion = true;
  2335. } else {
  2336. // Argument types are too different. Abort.
  2337. return false;
  2338. }
  2339. }
  2340. if (HasObjCConversion) {
  2341. // We had an Objective-C conversion. Allow this pointer
  2342. // conversion, but complain about it.
  2343. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2344. IncompatibleObjC = true;
  2345. return true;
  2346. }
  2347. }
  2348. return false;
  2349. }
  2350. /// Determine whether this is an Objective-C writeback conversion,
  2351. /// used for parameter passing when performing automatic reference counting.
  2352. ///
  2353. /// \param FromType The type we're converting form.
  2354. ///
  2355. /// \param ToType The type we're converting to.
  2356. ///
  2357. /// \param ConvertedType The type that will be produced after applying
  2358. /// this conversion.
  2359. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2360. QualType &ConvertedType) {
  2361. if (!getLangOpts().ObjCAutoRefCount ||
  2362. Context.hasSameUnqualifiedType(FromType, ToType))
  2363. return false;
  2364. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2365. QualType ToPointee;
  2366. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2367. ToPointee = ToPointer->getPointeeType();
  2368. else
  2369. return false;
  2370. Qualifiers ToQuals = ToPointee.getQualifiers();
  2371. if (!ToPointee->isObjCLifetimeType() ||
  2372. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2373. !ToQuals.withoutObjCLifetime().empty())
  2374. return false;
  2375. // Argument must be a pointer to __strong to __weak.
  2376. QualType FromPointee;
  2377. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2378. FromPointee = FromPointer->getPointeeType();
  2379. else
  2380. return false;
  2381. Qualifiers FromQuals = FromPointee.getQualifiers();
  2382. if (!FromPointee->isObjCLifetimeType() ||
  2383. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2384. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2385. return false;
  2386. // Make sure that we have compatible qualifiers.
  2387. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2388. if (!ToQuals.compatiblyIncludes(FromQuals))
  2389. return false;
  2390. // Remove qualifiers from the pointee type we're converting from; they
  2391. // aren't used in the compatibility check belong, and we'll be adding back
  2392. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2393. FromPointee = FromPointee.getUnqualifiedType();
  2394. // The unqualified form of the pointee types must be compatible.
  2395. ToPointee = ToPointee.getUnqualifiedType();
  2396. bool IncompatibleObjC;
  2397. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2398. FromPointee = ToPointee;
  2399. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2400. IncompatibleObjC))
  2401. return false;
  2402. /// Construct the type we're converting to, which is a pointer to
  2403. /// __autoreleasing pointee.
  2404. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2405. ConvertedType = Context.getPointerType(FromPointee);
  2406. return true;
  2407. }
  2408. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2409. QualType& ConvertedType) {
  2410. QualType ToPointeeType;
  2411. if (const BlockPointerType *ToBlockPtr =
  2412. ToType->getAs<BlockPointerType>())
  2413. ToPointeeType = ToBlockPtr->getPointeeType();
  2414. else
  2415. return false;
  2416. QualType FromPointeeType;
  2417. if (const BlockPointerType *FromBlockPtr =
  2418. FromType->getAs<BlockPointerType>())
  2419. FromPointeeType = FromBlockPtr->getPointeeType();
  2420. else
  2421. return false;
  2422. // We have pointer to blocks, check whether the only
  2423. // differences in the argument and result types are in Objective-C
  2424. // pointer conversions. If so, we permit the conversion.
  2425. const FunctionProtoType *FromFunctionType
  2426. = FromPointeeType->getAs<FunctionProtoType>();
  2427. const FunctionProtoType *ToFunctionType
  2428. = ToPointeeType->getAs<FunctionProtoType>();
  2429. if (!FromFunctionType || !ToFunctionType)
  2430. return false;
  2431. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2432. return true;
  2433. // Perform the quick checks that will tell us whether these
  2434. // function types are obviously different.
  2435. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2436. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2437. return false;
  2438. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2439. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2440. if (FromEInfo != ToEInfo)
  2441. return false;
  2442. bool IncompatibleObjC = false;
  2443. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2444. ToFunctionType->getReturnType())) {
  2445. // Okay, the types match exactly. Nothing to do.
  2446. } else {
  2447. QualType RHS = FromFunctionType->getReturnType();
  2448. QualType LHS = ToFunctionType->getReturnType();
  2449. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2450. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2451. LHS = LHS.getUnqualifiedType();
  2452. if (Context.hasSameType(RHS,LHS)) {
  2453. // OK exact match.
  2454. } else if (isObjCPointerConversion(RHS, LHS,
  2455. ConvertedType, IncompatibleObjC)) {
  2456. if (IncompatibleObjC)
  2457. return false;
  2458. // Okay, we have an Objective-C pointer conversion.
  2459. }
  2460. else
  2461. return false;
  2462. }
  2463. // Check argument types.
  2464. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2465. ArgIdx != NumArgs; ++ArgIdx) {
  2466. IncompatibleObjC = false;
  2467. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2468. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2469. if (Context.hasSameType(FromArgType, ToArgType)) {
  2470. // Okay, the types match exactly. Nothing to do.
  2471. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2472. ConvertedType, IncompatibleObjC)) {
  2473. if (IncompatibleObjC)
  2474. return false;
  2475. // Okay, we have an Objective-C pointer conversion.
  2476. } else
  2477. // Argument types are too different. Abort.
  2478. return false;
  2479. }
  2480. SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
  2481. bool CanUseToFPT, CanUseFromFPT;
  2482. if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
  2483. CanUseToFPT, CanUseFromFPT,
  2484. NewParamInfos))
  2485. return false;
  2486. ConvertedType = ToType;
  2487. return true;
  2488. }
  2489. enum {
  2490. ft_default,
  2491. ft_different_class,
  2492. ft_parameter_arity,
  2493. ft_parameter_mismatch,
  2494. ft_return_type,
  2495. ft_qualifer_mismatch,
  2496. ft_noexcept
  2497. };
  2498. /// Attempts to get the FunctionProtoType from a Type. Handles
  2499. /// MemberFunctionPointers properly.
  2500. static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
  2501. if (auto *FPT = FromType->getAs<FunctionProtoType>())
  2502. return FPT;
  2503. if (auto *MPT = FromType->getAs<MemberPointerType>())
  2504. return MPT->getPointeeType()->getAs<FunctionProtoType>();
  2505. return nullptr;
  2506. }
  2507. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2508. /// function types. Catches different number of parameter, mismatch in
  2509. /// parameter types, and different return types.
  2510. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2511. QualType FromType, QualType ToType) {
  2512. // If either type is not valid, include no extra info.
  2513. if (FromType.isNull() || ToType.isNull()) {
  2514. PDiag << ft_default;
  2515. return;
  2516. }
  2517. // Get the function type from the pointers.
  2518. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2519. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2520. *ToMember = ToType->getAs<MemberPointerType>();
  2521. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2522. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2523. << QualType(FromMember->getClass(), 0);
  2524. return;
  2525. }
  2526. FromType = FromMember->getPointeeType();
  2527. ToType = ToMember->getPointeeType();
  2528. }
  2529. if (FromType->isPointerType())
  2530. FromType = FromType->getPointeeType();
  2531. if (ToType->isPointerType())
  2532. ToType = ToType->getPointeeType();
  2533. // Remove references.
  2534. FromType = FromType.getNonReferenceType();
  2535. ToType = ToType.getNonReferenceType();
  2536. // Don't print extra info for non-specialized template functions.
  2537. if (FromType->isInstantiationDependentType() &&
  2538. !FromType->getAs<TemplateSpecializationType>()) {
  2539. PDiag << ft_default;
  2540. return;
  2541. }
  2542. // No extra info for same types.
  2543. if (Context.hasSameType(FromType, ToType)) {
  2544. PDiag << ft_default;
  2545. return;
  2546. }
  2547. const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
  2548. *ToFunction = tryGetFunctionProtoType(ToType);
  2549. // Both types need to be function types.
  2550. if (!FromFunction || !ToFunction) {
  2551. PDiag << ft_default;
  2552. return;
  2553. }
  2554. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2555. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2556. << FromFunction->getNumParams();
  2557. return;
  2558. }
  2559. // Handle different parameter types.
  2560. unsigned ArgPos;
  2561. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2562. PDiag << ft_parameter_mismatch << ArgPos + 1
  2563. << ToFunction->getParamType(ArgPos)
  2564. << FromFunction->getParamType(ArgPos);
  2565. return;
  2566. }
  2567. // Handle different return type.
  2568. if (!Context.hasSameType(FromFunction->getReturnType(),
  2569. ToFunction->getReturnType())) {
  2570. PDiag << ft_return_type << ToFunction->getReturnType()
  2571. << FromFunction->getReturnType();
  2572. return;
  2573. }
  2574. if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
  2575. PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
  2576. << FromFunction->getMethodQuals();
  2577. return;
  2578. }
  2579. // Handle exception specification differences on canonical type (in C++17
  2580. // onwards).
  2581. if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
  2582. ->isNothrow() !=
  2583. cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
  2584. ->isNothrow()) {
  2585. PDiag << ft_noexcept;
  2586. return;
  2587. }
  2588. // Unable to find a difference, so add no extra info.
  2589. PDiag << ft_default;
  2590. }
  2591. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2592. /// for equality of their argument types. Caller has already checked that
  2593. /// they have same number of arguments. If the parameters are different,
  2594. /// ArgPos will have the parameter index of the first different parameter.
  2595. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2596. const FunctionProtoType *NewType,
  2597. unsigned *ArgPos) {
  2598. for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
  2599. N = NewType->param_type_begin(),
  2600. E = OldType->param_type_end();
  2601. O && (O != E); ++O, ++N) {
  2602. if (!Context.hasSameType(O->getUnqualifiedType(),
  2603. N->getUnqualifiedType())) {
  2604. if (ArgPos)
  2605. *ArgPos = O - OldType->param_type_begin();
  2606. return false;
  2607. }
  2608. }
  2609. return true;
  2610. }
  2611. /// CheckPointerConversion - Check the pointer conversion from the
  2612. /// expression From to the type ToType. This routine checks for
  2613. /// ambiguous or inaccessible derived-to-base pointer
  2614. /// conversions for which IsPointerConversion has already returned
  2615. /// true. It returns true and produces a diagnostic if there was an
  2616. /// error, or returns false otherwise.
  2617. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2618. CastKind &Kind,
  2619. CXXCastPath& BasePath,
  2620. bool IgnoreBaseAccess,
  2621. bool Diagnose) {
  2622. QualType FromType = From->getType();
  2623. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2624. Kind = CK_BitCast;
  2625. if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2626. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2627. Expr::NPCK_ZeroExpression) {
  2628. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2629. DiagRuntimeBehavior(From->getExprLoc(), From,
  2630. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2631. << ToType << From->getSourceRange());
  2632. else if (!isUnevaluatedContext())
  2633. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2634. << ToType << From->getSourceRange();
  2635. }
  2636. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2637. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2638. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2639. ToPointeeType = ToPtrType->getPointeeType();
  2640. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2641. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2642. // We must have a derived-to-base conversion. Check an
  2643. // ambiguous or inaccessible conversion.
  2644. unsigned InaccessibleID = 0;
  2645. unsigned AmbigiousID = 0;
  2646. if (Diagnose) {
  2647. InaccessibleID = diag::err_upcast_to_inaccessible_base;
  2648. AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
  2649. }
  2650. if (CheckDerivedToBaseConversion(
  2651. FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
  2652. From->getExprLoc(), From->getSourceRange(), DeclarationName(),
  2653. &BasePath, IgnoreBaseAccess))
  2654. return true;
  2655. // The conversion was successful.
  2656. Kind = CK_DerivedToBase;
  2657. }
  2658. if (Diagnose && !IsCStyleOrFunctionalCast &&
  2659. FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
  2660. assert(getLangOpts().MSVCCompat &&
  2661. "this should only be possible with MSVCCompat!");
  2662. Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
  2663. << From->getSourceRange();
  2664. }
  2665. }
  2666. } else if (const ObjCObjectPointerType *ToPtrType =
  2667. ToType->getAs<ObjCObjectPointerType>()) {
  2668. if (const ObjCObjectPointerType *FromPtrType =
  2669. FromType->getAs<ObjCObjectPointerType>()) {
  2670. // Objective-C++ conversions are always okay.
  2671. // FIXME: We should have a different class of conversions for the
  2672. // Objective-C++ implicit conversions.
  2673. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2674. return false;
  2675. } else if (FromType->isBlockPointerType()) {
  2676. Kind = CK_BlockPointerToObjCPointerCast;
  2677. } else {
  2678. Kind = CK_CPointerToObjCPointerCast;
  2679. }
  2680. } else if (ToType->isBlockPointerType()) {
  2681. if (!FromType->isBlockPointerType())
  2682. Kind = CK_AnyPointerToBlockPointerCast;
  2683. }
  2684. // We shouldn't fall into this case unless it's valid for other
  2685. // reasons.
  2686. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2687. Kind = CK_NullToPointer;
  2688. return false;
  2689. }
  2690. /// IsMemberPointerConversion - Determines whether the conversion of the
  2691. /// expression From, which has the (possibly adjusted) type FromType, can be
  2692. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2693. /// If so, returns true and places the converted type (that might differ from
  2694. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2695. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2696. QualType ToType,
  2697. bool InOverloadResolution,
  2698. QualType &ConvertedType) {
  2699. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2700. if (!ToTypePtr)
  2701. return false;
  2702. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2703. if (From->isNullPointerConstant(Context,
  2704. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2705. : Expr::NPC_ValueDependentIsNull)) {
  2706. ConvertedType = ToType;
  2707. return true;
  2708. }
  2709. // Otherwise, both types have to be member pointers.
  2710. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2711. if (!FromTypePtr)
  2712. return false;
  2713. // A pointer to member of B can be converted to a pointer to member of D,
  2714. // where D is derived from B (C++ 4.11p2).
  2715. QualType FromClass(FromTypePtr->getClass(), 0);
  2716. QualType ToClass(ToTypePtr->getClass(), 0);
  2717. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2718. IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
  2719. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2720. ToClass.getTypePtr());
  2721. return true;
  2722. }
  2723. return false;
  2724. }
  2725. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2726. /// expression From to the type ToType. This routine checks for ambiguous or
  2727. /// virtual or inaccessible base-to-derived member pointer conversions
  2728. /// for which IsMemberPointerConversion has already returned true. It returns
  2729. /// true and produces a diagnostic if there was an error, or returns false
  2730. /// otherwise.
  2731. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2732. CastKind &Kind,
  2733. CXXCastPath &BasePath,
  2734. bool IgnoreBaseAccess) {
  2735. QualType FromType = From->getType();
  2736. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2737. if (!FromPtrType) {
  2738. // This must be a null pointer to member pointer conversion
  2739. assert(From->isNullPointerConstant(Context,
  2740. Expr::NPC_ValueDependentIsNull) &&
  2741. "Expr must be null pointer constant!");
  2742. Kind = CK_NullToMemberPointer;
  2743. return false;
  2744. }
  2745. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2746. assert(ToPtrType && "No member pointer cast has a target type "
  2747. "that is not a member pointer.");
  2748. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2749. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2750. // FIXME: What about dependent types?
  2751. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2752. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2753. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2754. /*DetectVirtual=*/true);
  2755. bool DerivationOkay =
  2756. IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
  2757. assert(DerivationOkay &&
  2758. "Should not have been called if derivation isn't OK.");
  2759. (void)DerivationOkay;
  2760. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2761. getUnqualifiedType())) {
  2762. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2763. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2764. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2765. return true;
  2766. }
  2767. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2768. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2769. << FromClass << ToClass << QualType(VBase, 0)
  2770. << From->getSourceRange();
  2771. return true;
  2772. }
  2773. if (!IgnoreBaseAccess)
  2774. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2775. Paths.front(),
  2776. diag::err_downcast_from_inaccessible_base);
  2777. // Must be a base to derived member conversion.
  2778. BuildBasePathArray(Paths, BasePath);
  2779. Kind = CK_BaseToDerivedMemberPointer;
  2780. return false;
  2781. }
  2782. /// Determine whether the lifetime conversion between the two given
  2783. /// qualifiers sets is nontrivial.
  2784. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2785. Qualifiers ToQuals) {
  2786. // Converting anything to const __unsafe_unretained is trivial.
  2787. if (ToQuals.hasConst() &&
  2788. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2789. return false;
  2790. return true;
  2791. }
  2792. /// IsQualificationConversion - Determines whether the conversion from
  2793. /// an rvalue of type FromType to ToType is a qualification conversion
  2794. /// (C++ 4.4).
  2795. ///
  2796. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2797. /// when the qualification conversion involves a change in the Objective-C
  2798. /// object lifetime.
  2799. bool
  2800. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2801. bool CStyle, bool &ObjCLifetimeConversion) {
  2802. FromType = Context.getCanonicalType(FromType);
  2803. ToType = Context.getCanonicalType(ToType);
  2804. ObjCLifetimeConversion = false;
  2805. // If FromType and ToType are the same type, this is not a
  2806. // qualification conversion.
  2807. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2808. return false;
  2809. // (C++ 4.4p4):
  2810. // A conversion can add cv-qualifiers at levels other than the first
  2811. // in multi-level pointers, subject to the following rules: [...]
  2812. bool PreviousToQualsIncludeConst = true;
  2813. bool UnwrappedAnyPointer = false;
  2814. while (Context.UnwrapSimilarTypes(FromType, ToType)) {
  2815. // Within each iteration of the loop, we check the qualifiers to
  2816. // determine if this still looks like a qualification
  2817. // conversion. Then, if all is well, we unwrap one more level of
  2818. // pointers or pointers-to-members and do it all again
  2819. // until there are no more pointers or pointers-to-members left to
  2820. // unwrap.
  2821. UnwrappedAnyPointer = true;
  2822. Qualifiers FromQuals = FromType.getQualifiers();
  2823. Qualifiers ToQuals = ToType.getQualifiers();
  2824. // Ignore __unaligned qualifier if this type is void.
  2825. if (ToType.getUnqualifiedType()->isVoidType())
  2826. FromQuals.removeUnaligned();
  2827. // Objective-C ARC:
  2828. // Check Objective-C lifetime conversions.
  2829. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2830. UnwrappedAnyPointer) {
  2831. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2832. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2833. ObjCLifetimeConversion = true;
  2834. FromQuals.removeObjCLifetime();
  2835. ToQuals.removeObjCLifetime();
  2836. } else {
  2837. // Qualification conversions cannot cast between different
  2838. // Objective-C lifetime qualifiers.
  2839. return false;
  2840. }
  2841. }
  2842. // Allow addition/removal of GC attributes but not changing GC attributes.
  2843. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2844. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2845. FromQuals.removeObjCGCAttr();
  2846. ToQuals.removeObjCGCAttr();
  2847. }
  2848. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2849. // 2,j, and similarly for volatile.
  2850. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2851. return false;
  2852. // -- if the cv 1,j and cv 2,j are different, then const is in
  2853. // every cv for 0 < k < j.
  2854. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2855. && !PreviousToQualsIncludeConst)
  2856. return false;
  2857. // Keep track of whether all prior cv-qualifiers in the "to" type
  2858. // include const.
  2859. PreviousToQualsIncludeConst
  2860. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2861. }
  2862. // Allows address space promotion by language rules implemented in
  2863. // Type::Qualifiers::isAddressSpaceSupersetOf.
  2864. Qualifiers FromQuals = FromType.getQualifiers();
  2865. Qualifiers ToQuals = ToType.getQualifiers();
  2866. if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
  2867. !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
  2868. return false;
  2869. }
  2870. // We are left with FromType and ToType being the pointee types
  2871. // after unwrapping the original FromType and ToType the same number
  2872. // of types. If we unwrapped any pointers, and if FromType and
  2873. // ToType have the same unqualified type (since we checked
  2874. // qualifiers above), then this is a qualification conversion.
  2875. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2876. }
  2877. /// - Determine whether this is a conversion from a scalar type to an
  2878. /// atomic type.
  2879. ///
  2880. /// If successful, updates \c SCS's second and third steps in the conversion
  2881. /// sequence to finish the conversion.
  2882. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2883. bool InOverloadResolution,
  2884. StandardConversionSequence &SCS,
  2885. bool CStyle) {
  2886. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2887. if (!ToAtomic)
  2888. return false;
  2889. StandardConversionSequence InnerSCS;
  2890. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2891. InOverloadResolution, InnerSCS,
  2892. CStyle, /*AllowObjCWritebackConversion=*/false))
  2893. return false;
  2894. SCS.Second = InnerSCS.Second;
  2895. SCS.setToType(1, InnerSCS.getToType(1));
  2896. SCS.Third = InnerSCS.Third;
  2897. SCS.QualificationIncludesObjCLifetime
  2898. = InnerSCS.QualificationIncludesObjCLifetime;
  2899. SCS.setToType(2, InnerSCS.getToType(2));
  2900. return true;
  2901. }
  2902. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2903. CXXConstructorDecl *Constructor,
  2904. QualType Type) {
  2905. const FunctionProtoType *CtorType =
  2906. Constructor->getType()->getAs<FunctionProtoType>();
  2907. if (CtorType->getNumParams() > 0) {
  2908. QualType FirstArg = CtorType->getParamType(0);
  2909. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2910. return true;
  2911. }
  2912. return false;
  2913. }
  2914. static OverloadingResult
  2915. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2916. CXXRecordDecl *To,
  2917. UserDefinedConversionSequence &User,
  2918. OverloadCandidateSet &CandidateSet,
  2919. bool AllowExplicit) {
  2920. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  2921. for (auto *D : S.LookupConstructors(To)) {
  2922. auto Info = getConstructorInfo(D);
  2923. if (!Info)
  2924. continue;
  2925. bool Usable = !Info.Constructor->isInvalidDecl() &&
  2926. S.isInitListConstructor(Info.Constructor) &&
  2927. (AllowExplicit || !Info.Constructor->isExplicit());
  2928. if (Usable) {
  2929. // If the first argument is (a reference to) the target type,
  2930. // suppress conversions.
  2931. bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2932. S.Context, Info.Constructor, ToType);
  2933. if (Info.ConstructorTmpl)
  2934. S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
  2935. /*ExplicitArgs*/ nullptr, From,
  2936. CandidateSet, SuppressUserConversions,
  2937. /*PartialOverloading*/ false,
  2938. AllowExplicit);
  2939. else
  2940. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
  2941. CandidateSet, SuppressUserConversions,
  2942. /*PartialOverloading*/ false, AllowExplicit);
  2943. }
  2944. }
  2945. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2946. OverloadCandidateSet::iterator Best;
  2947. switch (auto Result =
  2948. CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
  2949. case OR_Deleted:
  2950. case OR_Success: {
  2951. // Record the standard conversion we used and the conversion function.
  2952. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2953. QualType ThisType = Constructor->getThisType();
  2954. // Initializer lists don't have conversions as such.
  2955. User.Before.setAsIdentityConversion();
  2956. User.HadMultipleCandidates = HadMultipleCandidates;
  2957. User.ConversionFunction = Constructor;
  2958. User.FoundConversionFunction = Best->FoundDecl;
  2959. User.After.setAsIdentityConversion();
  2960. User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
  2961. User.After.setAllToTypes(ToType);
  2962. return Result;
  2963. }
  2964. case OR_No_Viable_Function:
  2965. return OR_No_Viable_Function;
  2966. case OR_Ambiguous:
  2967. return OR_Ambiguous;
  2968. }
  2969. llvm_unreachable("Invalid OverloadResult!");
  2970. }
  2971. /// Determines whether there is a user-defined conversion sequence
  2972. /// (C++ [over.ics.user]) that converts expression From to the type
  2973. /// ToType. If such a conversion exists, User will contain the
  2974. /// user-defined conversion sequence that performs such a conversion
  2975. /// and this routine will return true. Otherwise, this routine returns
  2976. /// false and User is unspecified.
  2977. ///
  2978. /// \param AllowExplicit true if the conversion should consider C++0x
  2979. /// "explicit" conversion functions as well as non-explicit conversion
  2980. /// functions (C++0x [class.conv.fct]p2).
  2981. ///
  2982. /// \param AllowObjCConversionOnExplicit true if the conversion should
  2983. /// allow an extra Objective-C pointer conversion on uses of explicit
  2984. /// constructors. Requires \c AllowExplicit to also be set.
  2985. static OverloadingResult
  2986. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2987. UserDefinedConversionSequence &User,
  2988. OverloadCandidateSet &CandidateSet,
  2989. bool AllowExplicit,
  2990. bool AllowObjCConversionOnExplicit) {
  2991. assert(AllowExplicit || !AllowObjCConversionOnExplicit);
  2992. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  2993. // Whether we will only visit constructors.
  2994. bool ConstructorsOnly = false;
  2995. // If the type we are conversion to is a class type, enumerate its
  2996. // constructors.
  2997. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2998. // C++ [over.match.ctor]p1:
  2999. // When objects of class type are direct-initialized (8.5), or
  3000. // copy-initialized from an expression of the same or a
  3001. // derived class type (8.5), overload resolution selects the
  3002. // constructor. [...] For copy-initialization, the candidate
  3003. // functions are all the converting constructors (12.3.1) of
  3004. // that class. The argument list is the expression-list within
  3005. // the parentheses of the initializer.
  3006. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  3007. (From->getType()->getAs<RecordType>() &&
  3008. S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
  3009. ConstructorsOnly = true;
  3010. if (!S.isCompleteType(From->getExprLoc(), ToType)) {
  3011. // We're not going to find any constructors.
  3012. } else if (CXXRecordDecl *ToRecordDecl
  3013. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  3014. Expr **Args = &From;
  3015. unsigned NumArgs = 1;
  3016. bool ListInitializing = false;
  3017. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  3018. // But first, see if there is an init-list-constructor that will work.
  3019. OverloadingResult Result = IsInitializerListConstructorConversion(
  3020. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  3021. if (Result != OR_No_Viable_Function)
  3022. return Result;
  3023. // Never mind.
  3024. CandidateSet.clear(
  3025. OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3026. // If we're list-initializing, we pass the individual elements as
  3027. // arguments, not the entire list.
  3028. Args = InitList->getInits();
  3029. NumArgs = InitList->getNumInits();
  3030. ListInitializing = true;
  3031. }
  3032. for (auto *D : S.LookupConstructors(ToRecordDecl)) {
  3033. auto Info = getConstructorInfo(D);
  3034. if (!Info)
  3035. continue;
  3036. bool Usable = !Info.Constructor->isInvalidDecl();
  3037. if (ListInitializing)
  3038. Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
  3039. else
  3040. Usable = Usable &&
  3041. Info.Constructor->isConvertingConstructor(AllowExplicit);
  3042. if (Usable) {
  3043. bool SuppressUserConversions = !ConstructorsOnly;
  3044. if (SuppressUserConversions && ListInitializing) {
  3045. SuppressUserConversions = false;
  3046. if (NumArgs == 1) {
  3047. // If the first argument is (a reference to) the target type,
  3048. // suppress conversions.
  3049. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  3050. S.Context, Info.Constructor, ToType);
  3051. }
  3052. }
  3053. if (Info.ConstructorTmpl)
  3054. S.AddTemplateOverloadCandidate(
  3055. Info.ConstructorTmpl, Info.FoundDecl,
  3056. /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
  3057. CandidateSet, SuppressUserConversions,
  3058. /*PartialOverloading*/ false, AllowExplicit);
  3059. else
  3060. // Allow one user-defined conversion when user specifies a
  3061. // From->ToType conversion via an static cast (c-style, etc).
  3062. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
  3063. llvm::makeArrayRef(Args, NumArgs),
  3064. CandidateSet, SuppressUserConversions,
  3065. /*PartialOverloading*/ false, AllowExplicit);
  3066. }
  3067. }
  3068. }
  3069. }
  3070. // Enumerate conversion functions, if we're allowed to.
  3071. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  3072. } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
  3073. // No conversion functions from incomplete types.
  3074. } else if (const RecordType *FromRecordType =
  3075. From->getType()->getAs<RecordType>()) {
  3076. if (CXXRecordDecl *FromRecordDecl
  3077. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  3078. // Add all of the conversion functions as candidates.
  3079. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  3080. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3081. DeclAccessPair FoundDecl = I.getPair();
  3082. NamedDecl *D = FoundDecl.getDecl();
  3083. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  3084. if (isa<UsingShadowDecl>(D))
  3085. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3086. CXXConversionDecl *Conv;
  3087. FunctionTemplateDecl *ConvTemplate;
  3088. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  3089. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3090. else
  3091. Conv = cast<CXXConversionDecl>(D);
  3092. if (AllowExplicit || !Conv->isExplicit()) {
  3093. if (ConvTemplate)
  3094. S.AddTemplateConversionCandidate(
  3095. ConvTemplate, FoundDecl, ActingContext, From, ToType,
  3096. CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
  3097. else
  3098. S.AddConversionCandidate(
  3099. Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
  3100. AllowObjCConversionOnExplicit, AllowExplicit);
  3101. }
  3102. }
  3103. }
  3104. }
  3105. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3106. OverloadCandidateSet::iterator Best;
  3107. switch (auto Result =
  3108. CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
  3109. case OR_Success:
  3110. case OR_Deleted:
  3111. // Record the standard conversion we used and the conversion function.
  3112. if (CXXConstructorDecl *Constructor
  3113. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  3114. // C++ [over.ics.user]p1:
  3115. // If the user-defined conversion is specified by a
  3116. // constructor (12.3.1), the initial standard conversion
  3117. // sequence converts the source type to the type required by
  3118. // the argument of the constructor.
  3119. //
  3120. QualType ThisType = Constructor->getThisType();
  3121. if (isa<InitListExpr>(From)) {
  3122. // Initializer lists don't have conversions as such.
  3123. User.Before.setAsIdentityConversion();
  3124. } else {
  3125. if (Best->Conversions[0].isEllipsis())
  3126. User.EllipsisConversion = true;
  3127. else {
  3128. User.Before = Best->Conversions[0].Standard;
  3129. User.EllipsisConversion = false;
  3130. }
  3131. }
  3132. User.HadMultipleCandidates = HadMultipleCandidates;
  3133. User.ConversionFunction = Constructor;
  3134. User.FoundConversionFunction = Best->FoundDecl;
  3135. User.After.setAsIdentityConversion();
  3136. User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
  3137. User.After.setAllToTypes(ToType);
  3138. return Result;
  3139. }
  3140. if (CXXConversionDecl *Conversion
  3141. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  3142. // C++ [over.ics.user]p1:
  3143. //
  3144. // [...] If the user-defined conversion is specified by a
  3145. // conversion function (12.3.2), the initial standard
  3146. // conversion sequence converts the source type to the
  3147. // implicit object parameter of the conversion function.
  3148. User.Before = Best->Conversions[0].Standard;
  3149. User.HadMultipleCandidates = HadMultipleCandidates;
  3150. User.ConversionFunction = Conversion;
  3151. User.FoundConversionFunction = Best->FoundDecl;
  3152. User.EllipsisConversion = false;
  3153. // C++ [over.ics.user]p2:
  3154. // The second standard conversion sequence converts the
  3155. // result of the user-defined conversion to the target type
  3156. // for the sequence. Since an implicit conversion sequence
  3157. // is an initialization, the special rules for
  3158. // initialization by user-defined conversion apply when
  3159. // selecting the best user-defined conversion for a
  3160. // user-defined conversion sequence (see 13.3.3 and
  3161. // 13.3.3.1).
  3162. User.After = Best->FinalConversion;
  3163. return Result;
  3164. }
  3165. llvm_unreachable("Not a constructor or conversion function?");
  3166. case OR_No_Viable_Function:
  3167. return OR_No_Viable_Function;
  3168. case OR_Ambiguous:
  3169. return OR_Ambiguous;
  3170. }
  3171. llvm_unreachable("Invalid OverloadResult!");
  3172. }
  3173. bool
  3174. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  3175. ImplicitConversionSequence ICS;
  3176. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  3177. OverloadCandidateSet::CSK_Normal);
  3178. OverloadingResult OvResult =
  3179. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  3180. CandidateSet, false, false);
  3181. if (!(OvResult == OR_Ambiguous ||
  3182. (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
  3183. return false;
  3184. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
  3185. if (OvResult == OR_Ambiguous)
  3186. Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
  3187. << From->getType() << ToType << From->getSourceRange();
  3188. else { // OR_No_Viable_Function && !CandidateSet.empty()
  3189. if (!RequireCompleteType(From->getBeginLoc(), ToType,
  3190. diag::err_typecheck_nonviable_condition_incomplete,
  3191. From->getType(), From->getSourceRange()))
  3192. Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
  3193. << false << From->getType() << From->getSourceRange() << ToType;
  3194. }
  3195. CandidateSet.NoteCandidates(
  3196. *this, From, Cands);
  3197. return true;
  3198. }
  3199. /// Compare the user-defined conversion functions or constructors
  3200. /// of two user-defined conversion sequences to determine whether any ordering
  3201. /// is possible.
  3202. static ImplicitConversionSequence::CompareKind
  3203. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  3204. FunctionDecl *Function2) {
  3205. if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
  3206. return ImplicitConversionSequence::Indistinguishable;
  3207. // Objective-C++:
  3208. // If both conversion functions are implicitly-declared conversions from
  3209. // a lambda closure type to a function pointer and a block pointer,
  3210. // respectively, always prefer the conversion to a function pointer,
  3211. // because the function pointer is more lightweight and is more likely
  3212. // to keep code working.
  3213. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  3214. if (!Conv1)
  3215. return ImplicitConversionSequence::Indistinguishable;
  3216. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  3217. if (!Conv2)
  3218. return ImplicitConversionSequence::Indistinguishable;
  3219. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  3220. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  3221. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  3222. if (Block1 != Block2)
  3223. return Block1 ? ImplicitConversionSequence::Worse
  3224. : ImplicitConversionSequence::Better;
  3225. }
  3226. return ImplicitConversionSequence::Indistinguishable;
  3227. }
  3228. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  3229. const ImplicitConversionSequence &ICS) {
  3230. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  3231. (ICS.isUserDefined() &&
  3232. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  3233. }
  3234. /// CompareImplicitConversionSequences - Compare two implicit
  3235. /// conversion sequences to determine whether one is better than the
  3236. /// other or if they are indistinguishable (C++ 13.3.3.2).
  3237. static ImplicitConversionSequence::CompareKind
  3238. CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
  3239. const ImplicitConversionSequence& ICS1,
  3240. const ImplicitConversionSequence& ICS2)
  3241. {
  3242. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  3243. // conversion sequences (as defined in 13.3.3.1)
  3244. // -- a standard conversion sequence (13.3.3.1.1) is a better
  3245. // conversion sequence than a user-defined conversion sequence or
  3246. // an ellipsis conversion sequence, and
  3247. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3248. // conversion sequence than an ellipsis conversion sequence
  3249. // (13.3.3.1.3).
  3250. //
  3251. // C++0x [over.best.ics]p10:
  3252. // For the purpose of ranking implicit conversion sequences as
  3253. // described in 13.3.3.2, the ambiguous conversion sequence is
  3254. // treated as a user-defined sequence that is indistinguishable
  3255. // from any other user-defined conversion sequence.
  3256. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3257. // been removed from C++11. We still accept this conversion, if it happens at
  3258. // the best viable function. Otherwise, this conversion is considered worse
  3259. // than ellipsis conversion. Consider this as an extension; this is not in the
  3260. // standard. For example:
  3261. //
  3262. // int &f(...); // #1
  3263. // void f(char*); // #2
  3264. // void g() { int &r = f("foo"); }
  3265. //
  3266. // In C++03, we pick #2 as the best viable function.
  3267. // In C++11, we pick #1 as the best viable function, because ellipsis
  3268. // conversion is better than string-literal to char* conversion (since there
  3269. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3270. // convert arguments, #2 would be the best viable function in C++11.
  3271. // If the best viable function has this conversion, a warning will be issued
  3272. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3273. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3274. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3275. hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
  3276. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3277. ? ImplicitConversionSequence::Worse
  3278. : ImplicitConversionSequence::Better;
  3279. if (ICS1.getKindRank() < ICS2.getKindRank())
  3280. return ImplicitConversionSequence::Better;
  3281. if (ICS2.getKindRank() < ICS1.getKindRank())
  3282. return ImplicitConversionSequence::Worse;
  3283. // The following checks require both conversion sequences to be of
  3284. // the same kind.
  3285. if (ICS1.getKind() != ICS2.getKind())
  3286. return ImplicitConversionSequence::Indistinguishable;
  3287. ImplicitConversionSequence::CompareKind Result =
  3288. ImplicitConversionSequence::Indistinguishable;
  3289. // Two implicit conversion sequences of the same form are
  3290. // indistinguishable conversion sequences unless one of the
  3291. // following rules apply: (C++ 13.3.3.2p3):
  3292. // List-initialization sequence L1 is a better conversion sequence than
  3293. // list-initialization sequence L2 if:
  3294. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3295. // if not that,
  3296. // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
  3297. // and N1 is smaller than N2.,
  3298. // even if one of the other rules in this paragraph would otherwise apply.
  3299. if (!ICS1.isBad()) {
  3300. if (ICS1.isStdInitializerListElement() &&
  3301. !ICS2.isStdInitializerListElement())
  3302. return ImplicitConversionSequence::Better;
  3303. if (!ICS1.isStdInitializerListElement() &&
  3304. ICS2.isStdInitializerListElement())
  3305. return ImplicitConversionSequence::Worse;
  3306. }
  3307. if (ICS1.isStandard())
  3308. // Standard conversion sequence S1 is a better conversion sequence than
  3309. // standard conversion sequence S2 if [...]
  3310. Result = CompareStandardConversionSequences(S, Loc,
  3311. ICS1.Standard, ICS2.Standard);
  3312. else if (ICS1.isUserDefined()) {
  3313. // User-defined conversion sequence U1 is a better conversion
  3314. // sequence than another user-defined conversion sequence U2 if
  3315. // they contain the same user-defined conversion function or
  3316. // constructor and if the second standard conversion sequence of
  3317. // U1 is better than the second standard conversion sequence of
  3318. // U2 (C++ 13.3.3.2p3).
  3319. if (ICS1.UserDefined.ConversionFunction ==
  3320. ICS2.UserDefined.ConversionFunction)
  3321. Result = CompareStandardConversionSequences(S, Loc,
  3322. ICS1.UserDefined.After,
  3323. ICS2.UserDefined.After);
  3324. else
  3325. Result = compareConversionFunctions(S,
  3326. ICS1.UserDefined.ConversionFunction,
  3327. ICS2.UserDefined.ConversionFunction);
  3328. }
  3329. return Result;
  3330. }
  3331. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3332. // determine if one is a proper subset of the other.
  3333. static ImplicitConversionSequence::CompareKind
  3334. compareStandardConversionSubsets(ASTContext &Context,
  3335. const StandardConversionSequence& SCS1,
  3336. const StandardConversionSequence& SCS2) {
  3337. ImplicitConversionSequence::CompareKind Result
  3338. = ImplicitConversionSequence::Indistinguishable;
  3339. // the identity conversion sequence is considered to be a subsequence of
  3340. // any non-identity conversion sequence
  3341. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3342. return ImplicitConversionSequence::Better;
  3343. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3344. return ImplicitConversionSequence::Worse;
  3345. if (SCS1.Second != SCS2.Second) {
  3346. if (SCS1.Second == ICK_Identity)
  3347. Result = ImplicitConversionSequence::Better;
  3348. else if (SCS2.Second == ICK_Identity)
  3349. Result = ImplicitConversionSequence::Worse;
  3350. else
  3351. return ImplicitConversionSequence::Indistinguishable;
  3352. } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
  3353. return ImplicitConversionSequence::Indistinguishable;
  3354. if (SCS1.Third == SCS2.Third) {
  3355. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3356. : ImplicitConversionSequence::Indistinguishable;
  3357. }
  3358. if (SCS1.Third == ICK_Identity)
  3359. return Result == ImplicitConversionSequence::Worse
  3360. ? ImplicitConversionSequence::Indistinguishable
  3361. : ImplicitConversionSequence::Better;
  3362. if (SCS2.Third == ICK_Identity)
  3363. return Result == ImplicitConversionSequence::Better
  3364. ? ImplicitConversionSequence::Indistinguishable
  3365. : ImplicitConversionSequence::Worse;
  3366. return ImplicitConversionSequence::Indistinguishable;
  3367. }
  3368. /// Determine whether one of the given reference bindings is better
  3369. /// than the other based on what kind of bindings they are.
  3370. static bool
  3371. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3372. const StandardConversionSequence &SCS2) {
  3373. // C++0x [over.ics.rank]p3b4:
  3374. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3375. // implicit object parameter of a non-static member function declared
  3376. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3377. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3378. // lvalue reference to a function lvalue and S2 binds an rvalue
  3379. // reference*.
  3380. //
  3381. // FIXME: Rvalue references. We're going rogue with the above edits,
  3382. // because the semantics in the current C++0x working paper (N3225 at the
  3383. // time of this writing) break the standard definition of std::forward
  3384. // and std::reference_wrapper when dealing with references to functions.
  3385. // Proposed wording changes submitted to CWG for consideration.
  3386. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3387. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3388. return false;
  3389. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3390. SCS2.IsLvalueReference) ||
  3391. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3392. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3393. }
  3394. enum class FixedEnumPromotion {
  3395. None,
  3396. ToUnderlyingType,
  3397. ToPromotedUnderlyingType
  3398. };
  3399. /// Returns kind of fixed enum promotion the \a SCS uses.
  3400. static FixedEnumPromotion
  3401. getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
  3402. if (SCS.Second != ICK_Integral_Promotion)
  3403. return FixedEnumPromotion::None;
  3404. QualType FromType = SCS.getFromType();
  3405. if (!FromType->isEnumeralType())
  3406. return FixedEnumPromotion::None;
  3407. EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
  3408. if (!Enum->isFixed())
  3409. return FixedEnumPromotion::None;
  3410. QualType UnderlyingType = Enum->getIntegerType();
  3411. if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
  3412. return FixedEnumPromotion::ToUnderlyingType;
  3413. return FixedEnumPromotion::ToPromotedUnderlyingType;
  3414. }
  3415. /// CompareStandardConversionSequences - Compare two standard
  3416. /// conversion sequences to determine whether one is better than the
  3417. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3418. static ImplicitConversionSequence::CompareKind
  3419. CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
  3420. const StandardConversionSequence& SCS1,
  3421. const StandardConversionSequence& SCS2)
  3422. {
  3423. // Standard conversion sequence S1 is a better conversion sequence
  3424. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3425. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3426. // sequences in the canonical form defined by 13.3.3.1.1,
  3427. // excluding any Lvalue Transformation; the identity conversion
  3428. // sequence is considered to be a subsequence of any
  3429. // non-identity conversion sequence) or, if not that,
  3430. if (ImplicitConversionSequence::CompareKind CK
  3431. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3432. return CK;
  3433. // -- the rank of S1 is better than the rank of S2 (by the rules
  3434. // defined below), or, if not that,
  3435. ImplicitConversionRank Rank1 = SCS1.getRank();
  3436. ImplicitConversionRank Rank2 = SCS2.getRank();
  3437. if (Rank1 < Rank2)
  3438. return ImplicitConversionSequence::Better;
  3439. else if (Rank2 < Rank1)
  3440. return ImplicitConversionSequence::Worse;
  3441. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3442. // are indistinguishable unless one of the following rules
  3443. // applies:
  3444. // A conversion that is not a conversion of a pointer, or
  3445. // pointer to member, to bool is better than another conversion
  3446. // that is such a conversion.
  3447. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3448. return SCS2.isPointerConversionToBool()
  3449. ? ImplicitConversionSequence::Better
  3450. : ImplicitConversionSequence::Worse;
  3451. // C++14 [over.ics.rank]p4b2:
  3452. // This is retroactively applied to C++11 by CWG 1601.
  3453. //
  3454. // A conversion that promotes an enumeration whose underlying type is fixed
  3455. // to its underlying type is better than one that promotes to the promoted
  3456. // underlying type, if the two are different.
  3457. FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
  3458. FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
  3459. if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
  3460. FEP1 != FEP2)
  3461. return FEP1 == FixedEnumPromotion::ToUnderlyingType
  3462. ? ImplicitConversionSequence::Better
  3463. : ImplicitConversionSequence::Worse;
  3464. // C++ [over.ics.rank]p4b2:
  3465. //
  3466. // If class B is derived directly or indirectly from class A,
  3467. // conversion of B* to A* is better than conversion of B* to
  3468. // void*, and conversion of A* to void* is better than conversion
  3469. // of B* to void*.
  3470. bool SCS1ConvertsToVoid
  3471. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3472. bool SCS2ConvertsToVoid
  3473. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3474. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3475. // Exactly one of the conversion sequences is a conversion to
  3476. // a void pointer; it's the worse conversion.
  3477. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3478. : ImplicitConversionSequence::Worse;
  3479. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3480. // Neither conversion sequence converts to a void pointer; compare
  3481. // their derived-to-base conversions.
  3482. if (ImplicitConversionSequence::CompareKind DerivedCK
  3483. = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
  3484. return DerivedCK;
  3485. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3486. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3487. // Both conversion sequences are conversions to void
  3488. // pointers. Compare the source types to determine if there's an
  3489. // inheritance relationship in their sources.
  3490. QualType FromType1 = SCS1.getFromType();
  3491. QualType FromType2 = SCS2.getFromType();
  3492. // Adjust the types we're converting from via the array-to-pointer
  3493. // conversion, if we need to.
  3494. if (SCS1.First == ICK_Array_To_Pointer)
  3495. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3496. if (SCS2.First == ICK_Array_To_Pointer)
  3497. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3498. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3499. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3500. if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3501. return ImplicitConversionSequence::Better;
  3502. else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3503. return ImplicitConversionSequence::Worse;
  3504. // Objective-C++: If one interface is more specific than the
  3505. // other, it is the better one.
  3506. const ObjCObjectPointerType* FromObjCPtr1
  3507. = FromType1->getAs<ObjCObjectPointerType>();
  3508. const ObjCObjectPointerType* FromObjCPtr2
  3509. = FromType2->getAs<ObjCObjectPointerType>();
  3510. if (FromObjCPtr1 && FromObjCPtr2) {
  3511. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3512. FromObjCPtr2);
  3513. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3514. FromObjCPtr1);
  3515. if (AssignLeft != AssignRight) {
  3516. return AssignLeft? ImplicitConversionSequence::Better
  3517. : ImplicitConversionSequence::Worse;
  3518. }
  3519. }
  3520. }
  3521. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3522. // bullet 3).
  3523. if (ImplicitConversionSequence::CompareKind QualCK
  3524. = CompareQualificationConversions(S, SCS1, SCS2))
  3525. return QualCK;
  3526. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3527. // Check for a better reference binding based on the kind of bindings.
  3528. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3529. return ImplicitConversionSequence::Better;
  3530. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3531. return ImplicitConversionSequence::Worse;
  3532. // C++ [over.ics.rank]p3b4:
  3533. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3534. // which the references refer are the same type except for
  3535. // top-level cv-qualifiers, and the type to which the reference
  3536. // initialized by S2 refers is more cv-qualified than the type
  3537. // to which the reference initialized by S1 refers.
  3538. QualType T1 = SCS1.getToType(2);
  3539. QualType T2 = SCS2.getToType(2);
  3540. T1 = S.Context.getCanonicalType(T1);
  3541. T2 = S.Context.getCanonicalType(T2);
  3542. Qualifiers T1Quals, T2Quals;
  3543. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3544. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3545. if (UnqualT1 == UnqualT2) {
  3546. // Objective-C++ ARC: If the references refer to objects with different
  3547. // lifetimes, prefer bindings that don't change lifetime.
  3548. if (SCS1.ObjCLifetimeConversionBinding !=
  3549. SCS2.ObjCLifetimeConversionBinding) {
  3550. return SCS1.ObjCLifetimeConversionBinding
  3551. ? ImplicitConversionSequence::Worse
  3552. : ImplicitConversionSequence::Better;
  3553. }
  3554. // If the type is an array type, promote the element qualifiers to the
  3555. // type for comparison.
  3556. if (isa<ArrayType>(T1) && T1Quals)
  3557. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3558. if (isa<ArrayType>(T2) && T2Quals)
  3559. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3560. if (T2.isMoreQualifiedThan(T1))
  3561. return ImplicitConversionSequence::Better;
  3562. else if (T1.isMoreQualifiedThan(T2))
  3563. return ImplicitConversionSequence::Worse;
  3564. }
  3565. }
  3566. // In Microsoft mode, prefer an integral conversion to a
  3567. // floating-to-integral conversion if the integral conversion
  3568. // is between types of the same size.
  3569. // For example:
  3570. // void f(float);
  3571. // void f(int);
  3572. // int main {
  3573. // long a;
  3574. // f(a);
  3575. // }
  3576. // Here, MSVC will call f(int) instead of generating a compile error
  3577. // as clang will do in standard mode.
  3578. if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
  3579. SCS2.Second == ICK_Floating_Integral &&
  3580. S.Context.getTypeSize(SCS1.getFromType()) ==
  3581. S.Context.getTypeSize(SCS1.getToType(2)))
  3582. return ImplicitConversionSequence::Better;
  3583. // Prefer a compatible vector conversion over a lax vector conversion
  3584. // For example:
  3585. //
  3586. // typedef float __v4sf __attribute__((__vector_size__(16)));
  3587. // void f(vector float);
  3588. // void f(vector signed int);
  3589. // int main() {
  3590. // __v4sf a;
  3591. // f(a);
  3592. // }
  3593. // Here, we'd like to choose f(vector float) and not
  3594. // report an ambiguous call error
  3595. if (SCS1.Second == ICK_Vector_Conversion &&
  3596. SCS2.Second == ICK_Vector_Conversion) {
  3597. bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
  3598. SCS1.getFromType(), SCS1.getToType(2));
  3599. bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
  3600. SCS2.getFromType(), SCS2.getToType(2));
  3601. if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
  3602. return SCS1IsCompatibleVectorConversion
  3603. ? ImplicitConversionSequence::Better
  3604. : ImplicitConversionSequence::Worse;
  3605. }
  3606. return ImplicitConversionSequence::Indistinguishable;
  3607. }
  3608. /// CompareQualificationConversions - Compares two standard conversion
  3609. /// sequences to determine whether they can be ranked based on their
  3610. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3611. static ImplicitConversionSequence::CompareKind
  3612. CompareQualificationConversions(Sema &S,
  3613. const StandardConversionSequence& SCS1,
  3614. const StandardConversionSequence& SCS2) {
  3615. // C++ 13.3.3.2p3:
  3616. // -- S1 and S2 differ only in their qualification conversion and
  3617. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3618. // cv-qualification signature of type T1 is a proper subset of
  3619. // the cv-qualification signature of type T2, and S1 is not the
  3620. // deprecated string literal array-to-pointer conversion (4.2).
  3621. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3622. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3623. return ImplicitConversionSequence::Indistinguishable;
  3624. // FIXME: the example in the standard doesn't use a qualification
  3625. // conversion (!)
  3626. QualType T1 = SCS1.getToType(2);
  3627. QualType T2 = SCS2.getToType(2);
  3628. T1 = S.Context.getCanonicalType(T1);
  3629. T2 = S.Context.getCanonicalType(T2);
  3630. Qualifiers T1Quals, T2Quals;
  3631. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3632. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3633. // If the types are the same, we won't learn anything by unwrapped
  3634. // them.
  3635. if (UnqualT1 == UnqualT2)
  3636. return ImplicitConversionSequence::Indistinguishable;
  3637. // If the type is an array type, promote the element qualifiers to the type
  3638. // for comparison.
  3639. if (isa<ArrayType>(T1) && T1Quals)
  3640. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3641. if (isa<ArrayType>(T2) && T2Quals)
  3642. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3643. ImplicitConversionSequence::CompareKind Result
  3644. = ImplicitConversionSequence::Indistinguishable;
  3645. // Objective-C++ ARC:
  3646. // Prefer qualification conversions not involving a change in lifetime
  3647. // to qualification conversions that do not change lifetime.
  3648. if (SCS1.QualificationIncludesObjCLifetime !=
  3649. SCS2.QualificationIncludesObjCLifetime) {
  3650. Result = SCS1.QualificationIncludesObjCLifetime
  3651. ? ImplicitConversionSequence::Worse
  3652. : ImplicitConversionSequence::Better;
  3653. }
  3654. while (S.Context.UnwrapSimilarTypes(T1, T2)) {
  3655. // Within each iteration of the loop, we check the qualifiers to
  3656. // determine if this still looks like a qualification
  3657. // conversion. Then, if all is well, we unwrap one more level of
  3658. // pointers or pointers-to-members and do it all again
  3659. // until there are no more pointers or pointers-to-members left
  3660. // to unwrap. This essentially mimics what
  3661. // IsQualificationConversion does, but here we're checking for a
  3662. // strict subset of qualifiers.
  3663. if (T1.getQualifiers().withoutObjCLifetime() ==
  3664. T2.getQualifiers().withoutObjCLifetime())
  3665. // The qualifiers are the same, so this doesn't tell us anything
  3666. // about how the sequences rank.
  3667. // ObjC ownership quals are omitted above as they interfere with
  3668. // the ARC overload rule.
  3669. ;
  3670. else if (T2.isMoreQualifiedThan(T1)) {
  3671. // T1 has fewer qualifiers, so it could be the better sequence.
  3672. if (Result == ImplicitConversionSequence::Worse)
  3673. // Neither has qualifiers that are a subset of the other's
  3674. // qualifiers.
  3675. return ImplicitConversionSequence::Indistinguishable;
  3676. Result = ImplicitConversionSequence::Better;
  3677. } else if (T1.isMoreQualifiedThan(T2)) {
  3678. // T2 has fewer qualifiers, so it could be the better sequence.
  3679. if (Result == ImplicitConversionSequence::Better)
  3680. // Neither has qualifiers that are a subset of the other's
  3681. // qualifiers.
  3682. return ImplicitConversionSequence::Indistinguishable;
  3683. Result = ImplicitConversionSequence::Worse;
  3684. } else {
  3685. // Qualifiers are disjoint.
  3686. return ImplicitConversionSequence::Indistinguishable;
  3687. }
  3688. // If the types after this point are equivalent, we're done.
  3689. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3690. break;
  3691. }
  3692. // Check that the winning standard conversion sequence isn't using
  3693. // the deprecated string literal array to pointer conversion.
  3694. switch (Result) {
  3695. case ImplicitConversionSequence::Better:
  3696. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3697. Result = ImplicitConversionSequence::Indistinguishable;
  3698. break;
  3699. case ImplicitConversionSequence::Indistinguishable:
  3700. break;
  3701. case ImplicitConversionSequence::Worse:
  3702. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3703. Result = ImplicitConversionSequence::Indistinguishable;
  3704. break;
  3705. }
  3706. return Result;
  3707. }
  3708. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3709. /// sequences to determine whether they can be ranked based on their
  3710. /// various kinds of derived-to-base conversions (C++
  3711. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3712. /// conversions between Objective-C interface types.
  3713. static ImplicitConversionSequence::CompareKind
  3714. CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
  3715. const StandardConversionSequence& SCS1,
  3716. const StandardConversionSequence& SCS2) {
  3717. QualType FromType1 = SCS1.getFromType();
  3718. QualType ToType1 = SCS1.getToType(1);
  3719. QualType FromType2 = SCS2.getFromType();
  3720. QualType ToType2 = SCS2.getToType(1);
  3721. // Adjust the types we're converting from via the array-to-pointer
  3722. // conversion, if we need to.
  3723. if (SCS1.First == ICK_Array_To_Pointer)
  3724. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3725. if (SCS2.First == ICK_Array_To_Pointer)
  3726. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3727. // Canonicalize all of the types.
  3728. FromType1 = S.Context.getCanonicalType(FromType1);
  3729. ToType1 = S.Context.getCanonicalType(ToType1);
  3730. FromType2 = S.Context.getCanonicalType(FromType2);
  3731. ToType2 = S.Context.getCanonicalType(ToType2);
  3732. // C++ [over.ics.rank]p4b3:
  3733. //
  3734. // If class B is derived directly or indirectly from class A and
  3735. // class C is derived directly or indirectly from B,
  3736. //
  3737. // Compare based on pointer conversions.
  3738. if (SCS1.Second == ICK_Pointer_Conversion &&
  3739. SCS2.Second == ICK_Pointer_Conversion &&
  3740. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3741. FromType1->isPointerType() && FromType2->isPointerType() &&
  3742. ToType1->isPointerType() && ToType2->isPointerType()) {
  3743. QualType FromPointee1 =
  3744. FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3745. QualType ToPointee1 =
  3746. ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3747. QualType FromPointee2 =
  3748. FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3749. QualType ToPointee2 =
  3750. ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3751. // -- conversion of C* to B* is better than conversion of C* to A*,
  3752. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3753. if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
  3754. return ImplicitConversionSequence::Better;
  3755. else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
  3756. return ImplicitConversionSequence::Worse;
  3757. }
  3758. // -- conversion of B* to A* is better than conversion of C* to A*,
  3759. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3760. if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3761. return ImplicitConversionSequence::Better;
  3762. else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3763. return ImplicitConversionSequence::Worse;
  3764. }
  3765. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3766. SCS2.Second == ICK_Pointer_Conversion) {
  3767. const ObjCObjectPointerType *FromPtr1
  3768. = FromType1->getAs<ObjCObjectPointerType>();
  3769. const ObjCObjectPointerType *FromPtr2
  3770. = FromType2->getAs<ObjCObjectPointerType>();
  3771. const ObjCObjectPointerType *ToPtr1
  3772. = ToType1->getAs<ObjCObjectPointerType>();
  3773. const ObjCObjectPointerType *ToPtr2
  3774. = ToType2->getAs<ObjCObjectPointerType>();
  3775. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3776. // Apply the same conversion ranking rules for Objective-C pointer types
  3777. // that we do for C++ pointers to class types. However, we employ the
  3778. // Objective-C pseudo-subtyping relationship used for assignment of
  3779. // Objective-C pointer types.
  3780. bool FromAssignLeft
  3781. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3782. bool FromAssignRight
  3783. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3784. bool ToAssignLeft
  3785. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3786. bool ToAssignRight
  3787. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3788. // A conversion to an a non-id object pointer type or qualified 'id'
  3789. // type is better than a conversion to 'id'.
  3790. if (ToPtr1->isObjCIdType() &&
  3791. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3792. return ImplicitConversionSequence::Worse;
  3793. if (ToPtr2->isObjCIdType() &&
  3794. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3795. return ImplicitConversionSequence::Better;
  3796. // A conversion to a non-id object pointer type is better than a
  3797. // conversion to a qualified 'id' type
  3798. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3799. return ImplicitConversionSequence::Worse;
  3800. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3801. return ImplicitConversionSequence::Better;
  3802. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3803. // type is better than a conversion to 'Class'.
  3804. if (ToPtr1->isObjCClassType() &&
  3805. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3806. return ImplicitConversionSequence::Worse;
  3807. if (ToPtr2->isObjCClassType() &&
  3808. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3809. return ImplicitConversionSequence::Better;
  3810. // A conversion to a non-Class object pointer type is better than a
  3811. // conversion to a qualified 'Class' type.
  3812. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3813. return ImplicitConversionSequence::Worse;
  3814. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3815. return ImplicitConversionSequence::Better;
  3816. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3817. if (S.Context.hasSameType(FromType1, FromType2) &&
  3818. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3819. (ToAssignLeft != ToAssignRight)) {
  3820. if (FromPtr1->isSpecialized()) {
  3821. // "conversion of B<A> * to B * is better than conversion of B * to
  3822. // C *.
  3823. bool IsFirstSame =
  3824. FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
  3825. bool IsSecondSame =
  3826. FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
  3827. if (IsFirstSame) {
  3828. if (!IsSecondSame)
  3829. return ImplicitConversionSequence::Better;
  3830. } else if (IsSecondSame)
  3831. return ImplicitConversionSequence::Worse;
  3832. }
  3833. return ToAssignLeft? ImplicitConversionSequence::Worse
  3834. : ImplicitConversionSequence::Better;
  3835. }
  3836. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3837. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3838. (FromAssignLeft != FromAssignRight))
  3839. return FromAssignLeft? ImplicitConversionSequence::Better
  3840. : ImplicitConversionSequence::Worse;
  3841. }
  3842. }
  3843. // Ranking of member-pointer types.
  3844. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3845. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3846. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3847. const MemberPointerType * FromMemPointer1 =
  3848. FromType1->getAs<MemberPointerType>();
  3849. const MemberPointerType * ToMemPointer1 =
  3850. ToType1->getAs<MemberPointerType>();
  3851. const MemberPointerType * FromMemPointer2 =
  3852. FromType2->getAs<MemberPointerType>();
  3853. const MemberPointerType * ToMemPointer2 =
  3854. ToType2->getAs<MemberPointerType>();
  3855. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3856. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3857. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3858. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3859. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3860. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3861. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3862. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3863. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3864. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3865. if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
  3866. return ImplicitConversionSequence::Worse;
  3867. else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
  3868. return ImplicitConversionSequence::Better;
  3869. }
  3870. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3871. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3872. if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
  3873. return ImplicitConversionSequence::Better;
  3874. else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
  3875. return ImplicitConversionSequence::Worse;
  3876. }
  3877. }
  3878. if (SCS1.Second == ICK_Derived_To_Base) {
  3879. // -- conversion of C to B is better than conversion of C to A,
  3880. // -- binding of an expression of type C to a reference of type
  3881. // B& is better than binding an expression of type C to a
  3882. // reference of type A&,
  3883. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3884. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3885. if (S.IsDerivedFrom(Loc, ToType1, ToType2))
  3886. return ImplicitConversionSequence::Better;
  3887. else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
  3888. return ImplicitConversionSequence::Worse;
  3889. }
  3890. // -- conversion of B to A is better than conversion of C to A.
  3891. // -- binding of an expression of type B to a reference of type
  3892. // A& is better than binding an expression of type C to a
  3893. // reference of type A&,
  3894. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3895. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3896. if (S.IsDerivedFrom(Loc, FromType2, FromType1))
  3897. return ImplicitConversionSequence::Better;
  3898. else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
  3899. return ImplicitConversionSequence::Worse;
  3900. }
  3901. }
  3902. return ImplicitConversionSequence::Indistinguishable;
  3903. }
  3904. /// Determine whether the given type is valid, e.g., it is not an invalid
  3905. /// C++ class.
  3906. static bool isTypeValid(QualType T) {
  3907. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3908. return !Record->isInvalidDecl();
  3909. return true;
  3910. }
  3911. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3912. /// determine whether they are reference-related,
  3913. /// reference-compatible, reference-compatible with added
  3914. /// qualification, or incompatible, for use in C++ initialization by
  3915. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3916. /// type, and the first type (T1) is the pointee type of the reference
  3917. /// type being initialized.
  3918. Sema::ReferenceCompareResult
  3919. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3920. QualType OrigT1, QualType OrigT2,
  3921. bool &DerivedToBase,
  3922. bool &ObjCConversion,
  3923. bool &ObjCLifetimeConversion,
  3924. bool &FunctionConversion) {
  3925. assert(!OrigT1->isReferenceType() &&
  3926. "T1 must be the pointee type of the reference type");
  3927. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3928. QualType T1 = Context.getCanonicalType(OrigT1);
  3929. QualType T2 = Context.getCanonicalType(OrigT2);
  3930. Qualifiers T1Quals, T2Quals;
  3931. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3932. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3933. // C++ [dcl.init.ref]p4:
  3934. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3935. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3936. // T1 is a base class of T2.
  3937. DerivedToBase = false;
  3938. ObjCConversion = false;
  3939. ObjCLifetimeConversion = false;
  3940. QualType ConvertedT2;
  3941. if (UnqualT1 == UnqualT2) {
  3942. // Nothing to do.
  3943. } else if (isCompleteType(Loc, OrigT2) &&
  3944. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3945. IsDerivedFrom(Loc, UnqualT2, UnqualT1))
  3946. DerivedToBase = true;
  3947. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3948. UnqualT2->isObjCObjectOrInterfaceType() &&
  3949. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3950. ObjCConversion = true;
  3951. else if (UnqualT2->isFunctionType() &&
  3952. IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
  3953. // C++1z [dcl.init.ref]p4:
  3954. // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
  3955. // function" and T1 is "function"
  3956. //
  3957. // We extend this to also apply to 'noreturn', so allow any function
  3958. // conversion between function types.
  3959. FunctionConversion = true;
  3960. return Ref_Compatible;
  3961. } else
  3962. return Ref_Incompatible;
  3963. // At this point, we know that T1 and T2 are reference-related (at
  3964. // least).
  3965. // If the type is an array type, promote the element qualifiers to the type
  3966. // for comparison.
  3967. if (isa<ArrayType>(T1) && T1Quals)
  3968. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3969. if (isa<ArrayType>(T2) && T2Quals)
  3970. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3971. // C++ [dcl.init.ref]p4:
  3972. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3973. // reference-related to T2 and cv1 is the same cv-qualification
  3974. // as, or greater cv-qualification than, cv2. For purposes of
  3975. // overload resolution, cases for which cv1 is greater
  3976. // cv-qualification than cv2 are identified as
  3977. // reference-compatible with added qualification (see 13.3.3.2).
  3978. //
  3979. // Note that we also require equivalence of Objective-C GC and address-space
  3980. // qualifiers when performing these computations, so that e.g., an int in
  3981. // address space 1 is not reference-compatible with an int in address
  3982. // space 2.
  3983. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3984. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3985. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3986. ObjCLifetimeConversion = true;
  3987. T1Quals.removeObjCLifetime();
  3988. T2Quals.removeObjCLifetime();
  3989. }
  3990. // MS compiler ignores __unaligned qualifier for references; do the same.
  3991. T1Quals.removeUnaligned();
  3992. T2Quals.removeUnaligned();
  3993. if (T1Quals.compatiblyIncludes(T2Quals))
  3994. return Ref_Compatible;
  3995. else
  3996. return Ref_Related;
  3997. }
  3998. /// Look for a user-defined conversion to a value reference-compatible
  3999. /// with DeclType. Return true if something definite is found.
  4000. static bool
  4001. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  4002. QualType DeclType, SourceLocation DeclLoc,
  4003. Expr *Init, QualType T2, bool AllowRvalues,
  4004. bool AllowExplicit) {
  4005. assert(T2->isRecordType() && "Can only find conversions of record types.");
  4006. CXXRecordDecl *T2RecordDecl
  4007. = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
  4008. OverloadCandidateSet CandidateSet(
  4009. DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4010. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  4011. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4012. NamedDecl *D = *I;
  4013. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4014. if (isa<UsingShadowDecl>(D))
  4015. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4016. FunctionTemplateDecl *ConvTemplate
  4017. = dyn_cast<FunctionTemplateDecl>(D);
  4018. CXXConversionDecl *Conv;
  4019. if (ConvTemplate)
  4020. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4021. else
  4022. Conv = cast<CXXConversionDecl>(D);
  4023. // If this is an explicit conversion, and we're not allowed to consider
  4024. // explicit conversions, skip it.
  4025. if (!AllowExplicit && Conv->isExplicit())
  4026. continue;
  4027. if (AllowRvalues) {
  4028. bool DerivedToBase = false;
  4029. bool ObjCConversion = false;
  4030. bool ObjCLifetimeConversion = false;
  4031. bool FunctionConversion = false;
  4032. // If we are initializing an rvalue reference, don't permit conversion
  4033. // functions that return lvalues.
  4034. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  4035. const ReferenceType *RefType
  4036. = Conv->getConversionType()->getAs<LValueReferenceType>();
  4037. if (RefType && !RefType->getPointeeType()->isFunctionType())
  4038. continue;
  4039. }
  4040. if (!ConvTemplate &&
  4041. S.CompareReferenceRelationship(
  4042. DeclLoc,
  4043. Conv->getConversionType()
  4044. .getNonReferenceType()
  4045. .getUnqualifiedType(),
  4046. DeclType.getNonReferenceType().getUnqualifiedType(),
  4047. DerivedToBase, ObjCConversion, ObjCLifetimeConversion,
  4048. FunctionConversion) == Sema::Ref_Incompatible)
  4049. continue;
  4050. } else {
  4051. // If the conversion function doesn't return a reference type,
  4052. // it can't be considered for this conversion. An rvalue reference
  4053. // is only acceptable if its referencee is a function type.
  4054. const ReferenceType *RefType =
  4055. Conv->getConversionType()->getAs<ReferenceType>();
  4056. if (!RefType ||
  4057. (!RefType->isLValueReferenceType() &&
  4058. !RefType->getPointeeType()->isFunctionType()))
  4059. continue;
  4060. }
  4061. if (ConvTemplate)
  4062. S.AddTemplateConversionCandidate(
  4063. ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4064. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4065. else
  4066. S.AddConversionCandidate(
  4067. Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4068. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4069. }
  4070. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4071. OverloadCandidateSet::iterator Best;
  4072. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  4073. case OR_Success:
  4074. // C++ [over.ics.ref]p1:
  4075. //
  4076. // [...] If the parameter binds directly to the result of
  4077. // applying a conversion function to the argument
  4078. // expression, the implicit conversion sequence is a
  4079. // user-defined conversion sequence (13.3.3.1.2), with the
  4080. // second standard conversion sequence either an identity
  4081. // conversion or, if the conversion function returns an
  4082. // entity of a type that is a derived class of the parameter
  4083. // type, a derived-to-base Conversion.
  4084. if (!Best->FinalConversion.DirectBinding)
  4085. return false;
  4086. ICS.setUserDefined();
  4087. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  4088. ICS.UserDefined.After = Best->FinalConversion;
  4089. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  4090. ICS.UserDefined.ConversionFunction = Best->Function;
  4091. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  4092. ICS.UserDefined.EllipsisConversion = false;
  4093. assert(ICS.UserDefined.After.ReferenceBinding &&
  4094. ICS.UserDefined.After.DirectBinding &&
  4095. "Expected a direct reference binding!");
  4096. return true;
  4097. case OR_Ambiguous:
  4098. ICS.setAmbiguous();
  4099. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  4100. Cand != CandidateSet.end(); ++Cand)
  4101. if (Cand->Viable)
  4102. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  4103. return true;
  4104. case OR_No_Viable_Function:
  4105. case OR_Deleted:
  4106. // There was no suitable conversion, or we found a deleted
  4107. // conversion; continue with other checks.
  4108. return false;
  4109. }
  4110. llvm_unreachable("Invalid OverloadResult!");
  4111. }
  4112. /// Compute an implicit conversion sequence for reference
  4113. /// initialization.
  4114. static ImplicitConversionSequence
  4115. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  4116. SourceLocation DeclLoc,
  4117. bool SuppressUserConversions,
  4118. bool AllowExplicit) {
  4119. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  4120. // Most paths end in a failed conversion.
  4121. ImplicitConversionSequence ICS;
  4122. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4123. QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
  4124. QualType T2 = Init->getType();
  4125. // If the initializer is the address of an overloaded function, try
  4126. // to resolve the overloaded function. If all goes well, T2 is the
  4127. // type of the resulting function.
  4128. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4129. DeclAccessPair Found;
  4130. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  4131. false, Found))
  4132. T2 = Fn->getType();
  4133. }
  4134. // Compute some basic properties of the types and the initializer.
  4135. bool isRValRef = DeclType->isRValueReferenceType();
  4136. bool DerivedToBase = false;
  4137. bool ObjCConversion = false;
  4138. bool ObjCLifetimeConversion = false;
  4139. bool FunctionConversion = false;
  4140. Expr::Classification InitCategory = Init->Classify(S.Context);
  4141. Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship(
  4142. DeclLoc, T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion,
  4143. FunctionConversion);
  4144. // C++0x [dcl.init.ref]p5:
  4145. // A reference to type "cv1 T1" is initialized by an expression
  4146. // of type "cv2 T2" as follows:
  4147. // -- If reference is an lvalue reference and the initializer expression
  4148. if (!isRValRef) {
  4149. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  4150. // reference-compatible with "cv2 T2," or
  4151. //
  4152. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  4153. if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
  4154. // C++ [over.ics.ref]p1:
  4155. // When a parameter of reference type binds directly (8.5.3)
  4156. // to an argument expression, the implicit conversion sequence
  4157. // is the identity conversion, unless the argument expression
  4158. // has a type that is a derived class of the parameter type,
  4159. // in which case the implicit conversion sequence is a
  4160. // derived-to-base Conversion (13.3.3.1).
  4161. ICS.setStandard();
  4162. ICS.Standard.First = ICK_Identity;
  4163. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  4164. : ObjCConversion? ICK_Compatible_Conversion
  4165. : ICK_Identity;
  4166. ICS.Standard.Third = ICK_Identity;
  4167. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  4168. ICS.Standard.setToType(0, T2);
  4169. ICS.Standard.setToType(1, T1);
  4170. ICS.Standard.setToType(2, T1);
  4171. ICS.Standard.ReferenceBinding = true;
  4172. ICS.Standard.DirectBinding = true;
  4173. ICS.Standard.IsLvalueReference = !isRValRef;
  4174. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4175. ICS.Standard.BindsToRvalue = false;
  4176. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4177. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  4178. ICS.Standard.CopyConstructor = nullptr;
  4179. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4180. // Nothing more to do: the inaccessibility/ambiguity check for
  4181. // derived-to-base conversions is suppressed when we're
  4182. // computing the implicit conversion sequence (C++
  4183. // [over.best.ics]p2).
  4184. return ICS;
  4185. }
  4186. // -- has a class type (i.e., T2 is a class type), where T1 is
  4187. // not reference-related to T2, and can be implicitly
  4188. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  4189. // is reference-compatible with "cv3 T3" 92) (this
  4190. // conversion is selected by enumerating the applicable
  4191. // conversion functions (13.3.1.6) and choosing the best
  4192. // one through overload resolution (13.3)),
  4193. if (!SuppressUserConversions && T2->isRecordType() &&
  4194. S.isCompleteType(DeclLoc, T2) &&
  4195. RefRelationship == Sema::Ref_Incompatible) {
  4196. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4197. Init, T2, /*AllowRvalues=*/false,
  4198. AllowExplicit))
  4199. return ICS;
  4200. }
  4201. }
  4202. // -- Otherwise, the reference shall be an lvalue reference to a
  4203. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4204. // shall be an rvalue reference.
  4205. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  4206. return ICS;
  4207. // -- If the initializer expression
  4208. //
  4209. // -- is an xvalue, class prvalue, array prvalue or function
  4210. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  4211. if (RefRelationship == Sema::Ref_Compatible &&
  4212. (InitCategory.isXValue() ||
  4213. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  4214. (InitCategory.isLValue() && T2->isFunctionType()))) {
  4215. ICS.setStandard();
  4216. ICS.Standard.First = ICK_Identity;
  4217. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  4218. : ObjCConversion? ICK_Compatible_Conversion
  4219. : ICK_Identity;
  4220. ICS.Standard.Third = ICK_Identity;
  4221. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  4222. ICS.Standard.setToType(0, T2);
  4223. ICS.Standard.setToType(1, T1);
  4224. ICS.Standard.setToType(2, T1);
  4225. ICS.Standard.ReferenceBinding = true;
  4226. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  4227. // binding unless we're binding to a class prvalue.
  4228. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  4229. // allow the use of rvalue references in C++98/03 for the benefit of
  4230. // standard library implementors; therefore, we need the xvalue check here.
  4231. ICS.Standard.DirectBinding =
  4232. S.getLangOpts().CPlusPlus11 ||
  4233. !(InitCategory.isPRValue() || T2->isRecordType());
  4234. ICS.Standard.IsLvalueReference = !isRValRef;
  4235. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4236. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  4237. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4238. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  4239. ICS.Standard.CopyConstructor = nullptr;
  4240. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4241. return ICS;
  4242. }
  4243. // -- has a class type (i.e., T2 is a class type), where T1 is not
  4244. // reference-related to T2, and can be implicitly converted to
  4245. // an xvalue, class prvalue, or function lvalue of type
  4246. // "cv3 T3", where "cv1 T1" is reference-compatible with
  4247. // "cv3 T3",
  4248. //
  4249. // then the reference is bound to the value of the initializer
  4250. // expression in the first case and to the result of the conversion
  4251. // in the second case (or, in either case, to an appropriate base
  4252. // class subobject).
  4253. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4254. T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
  4255. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4256. Init, T2, /*AllowRvalues=*/true,
  4257. AllowExplicit)) {
  4258. // In the second case, if the reference is an rvalue reference
  4259. // and the second standard conversion sequence of the
  4260. // user-defined conversion sequence includes an lvalue-to-rvalue
  4261. // conversion, the program is ill-formed.
  4262. if (ICS.isUserDefined() && isRValRef &&
  4263. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  4264. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4265. return ICS;
  4266. }
  4267. // A temporary of function type cannot be created; don't even try.
  4268. if (T1->isFunctionType())
  4269. return ICS;
  4270. // -- Otherwise, a temporary of type "cv1 T1" is created and
  4271. // initialized from the initializer expression using the
  4272. // rules for a non-reference copy initialization (8.5). The
  4273. // reference is then bound to the temporary. If T1 is
  4274. // reference-related to T2, cv1 must be the same
  4275. // cv-qualification as, or greater cv-qualification than,
  4276. // cv2; otherwise, the program is ill-formed.
  4277. if (RefRelationship == Sema::Ref_Related) {
  4278. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  4279. // we would be reference-compatible or reference-compatible with
  4280. // added qualification. But that wasn't the case, so the reference
  4281. // initialization fails.
  4282. //
  4283. // Note that we only want to check address spaces and cvr-qualifiers here.
  4284. // ObjC GC, lifetime and unaligned qualifiers aren't important.
  4285. Qualifiers T1Quals = T1.getQualifiers();
  4286. Qualifiers T2Quals = T2.getQualifiers();
  4287. T1Quals.removeObjCGCAttr();
  4288. T1Quals.removeObjCLifetime();
  4289. T2Quals.removeObjCGCAttr();
  4290. T2Quals.removeObjCLifetime();
  4291. // MS compiler ignores __unaligned qualifier for references; do the same.
  4292. T1Quals.removeUnaligned();
  4293. T2Quals.removeUnaligned();
  4294. if (!T1Quals.compatiblyIncludes(T2Quals))
  4295. return ICS;
  4296. }
  4297. // If at least one of the types is a class type, the types are not
  4298. // related, and we aren't allowed any user conversions, the
  4299. // reference binding fails. This case is important for breaking
  4300. // recursion, since TryImplicitConversion below will attempt to
  4301. // create a temporary through the use of a copy constructor.
  4302. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4303. (T1->isRecordType() || T2->isRecordType()))
  4304. return ICS;
  4305. // If T1 is reference-related to T2 and the reference is an rvalue
  4306. // reference, the initializer expression shall not be an lvalue.
  4307. if (RefRelationship >= Sema::Ref_Related &&
  4308. isRValRef && Init->Classify(S.Context).isLValue())
  4309. return ICS;
  4310. // C++ [over.ics.ref]p2:
  4311. // When a parameter of reference type is not bound directly to
  4312. // an argument expression, the conversion sequence is the one
  4313. // required to convert the argument expression to the
  4314. // underlying type of the reference according to
  4315. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  4316. // to copy-initializing a temporary of the underlying type with
  4317. // the argument expression. Any difference in top-level
  4318. // cv-qualification is subsumed by the initialization itself
  4319. // and does not constitute a conversion.
  4320. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4321. /*AllowExplicit=*/false,
  4322. /*InOverloadResolution=*/false,
  4323. /*CStyle=*/false,
  4324. /*AllowObjCWritebackConversion=*/false,
  4325. /*AllowObjCConversionOnExplicit=*/false);
  4326. // Of course, that's still a reference binding.
  4327. if (ICS.isStandard()) {
  4328. ICS.Standard.ReferenceBinding = true;
  4329. ICS.Standard.IsLvalueReference = !isRValRef;
  4330. ICS.Standard.BindsToFunctionLvalue = false;
  4331. ICS.Standard.BindsToRvalue = true;
  4332. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4333. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4334. } else if (ICS.isUserDefined()) {
  4335. const ReferenceType *LValRefType =
  4336. ICS.UserDefined.ConversionFunction->getReturnType()
  4337. ->getAs<LValueReferenceType>();
  4338. // C++ [over.ics.ref]p3:
  4339. // Except for an implicit object parameter, for which see 13.3.1, a
  4340. // standard conversion sequence cannot be formed if it requires [...]
  4341. // binding an rvalue reference to an lvalue other than a function
  4342. // lvalue.
  4343. // Note that the function case is not possible here.
  4344. if (DeclType->isRValueReferenceType() && LValRefType) {
  4345. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4346. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4347. // reference to an rvalue!
  4348. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4349. return ICS;
  4350. }
  4351. ICS.UserDefined.After.ReferenceBinding = true;
  4352. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4353. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4354. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4355. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4356. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4357. }
  4358. return ICS;
  4359. }
  4360. static ImplicitConversionSequence
  4361. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4362. bool SuppressUserConversions,
  4363. bool InOverloadResolution,
  4364. bool AllowObjCWritebackConversion,
  4365. bool AllowExplicit = false);
  4366. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4367. /// initializer list From.
  4368. static ImplicitConversionSequence
  4369. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4370. bool SuppressUserConversions,
  4371. bool InOverloadResolution,
  4372. bool AllowObjCWritebackConversion) {
  4373. // C++11 [over.ics.list]p1:
  4374. // When an argument is an initializer list, it is not an expression and
  4375. // special rules apply for converting it to a parameter type.
  4376. ImplicitConversionSequence Result;
  4377. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4378. // We need a complete type for what follows. Incomplete types can never be
  4379. // initialized from init lists.
  4380. if (!S.isCompleteType(From->getBeginLoc(), ToType))
  4381. return Result;
  4382. // Per DR1467:
  4383. // If the parameter type is a class X and the initializer list has a single
  4384. // element of type cv U, where U is X or a class derived from X, the
  4385. // implicit conversion sequence is the one required to convert the element
  4386. // to the parameter type.
  4387. //
  4388. // Otherwise, if the parameter type is a character array [... ]
  4389. // and the initializer list has a single element that is an
  4390. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4391. // implicit conversion sequence is the identity conversion.
  4392. if (From->getNumInits() == 1) {
  4393. if (ToType->isRecordType()) {
  4394. QualType InitType = From->getInit(0)->getType();
  4395. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4396. S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
  4397. return TryCopyInitialization(S, From->getInit(0), ToType,
  4398. SuppressUserConversions,
  4399. InOverloadResolution,
  4400. AllowObjCWritebackConversion);
  4401. }
  4402. // FIXME: Check the other conditions here: array of character type,
  4403. // initializer is a string literal.
  4404. if (ToType->isArrayType()) {
  4405. InitializedEntity Entity =
  4406. InitializedEntity::InitializeParameter(S.Context, ToType,
  4407. /*Consumed=*/false);
  4408. if (S.CanPerformCopyInitialization(Entity, From)) {
  4409. Result.setStandard();
  4410. Result.Standard.setAsIdentityConversion();
  4411. Result.Standard.setFromType(ToType);
  4412. Result.Standard.setAllToTypes(ToType);
  4413. return Result;
  4414. }
  4415. }
  4416. }
  4417. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4418. // C++11 [over.ics.list]p2:
  4419. // If the parameter type is std::initializer_list<X> or "array of X" and
  4420. // all the elements can be implicitly converted to X, the implicit
  4421. // conversion sequence is the worst conversion necessary to convert an
  4422. // element of the list to X.
  4423. //
  4424. // C++14 [over.ics.list]p3:
  4425. // Otherwise, if the parameter type is "array of N X", if the initializer
  4426. // list has exactly N elements or if it has fewer than N elements and X is
  4427. // default-constructible, and if all the elements of the initializer list
  4428. // can be implicitly converted to X, the implicit conversion sequence is
  4429. // the worst conversion necessary to convert an element of the list to X.
  4430. //
  4431. // FIXME: We're missing a lot of these checks.
  4432. bool toStdInitializerList = false;
  4433. QualType X;
  4434. if (ToType->isArrayType())
  4435. X = S.Context.getAsArrayType(ToType)->getElementType();
  4436. else
  4437. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4438. if (!X.isNull()) {
  4439. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4440. Expr *Init = From->getInit(i);
  4441. ImplicitConversionSequence ICS =
  4442. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4443. InOverloadResolution,
  4444. AllowObjCWritebackConversion);
  4445. // If a single element isn't convertible, fail.
  4446. if (ICS.isBad()) {
  4447. Result = ICS;
  4448. break;
  4449. }
  4450. // Otherwise, look for the worst conversion.
  4451. if (Result.isBad() || CompareImplicitConversionSequences(
  4452. S, From->getBeginLoc(), ICS, Result) ==
  4453. ImplicitConversionSequence::Worse)
  4454. Result = ICS;
  4455. }
  4456. // For an empty list, we won't have computed any conversion sequence.
  4457. // Introduce the identity conversion sequence.
  4458. if (From->getNumInits() == 0) {
  4459. Result.setStandard();
  4460. Result.Standard.setAsIdentityConversion();
  4461. Result.Standard.setFromType(ToType);
  4462. Result.Standard.setAllToTypes(ToType);
  4463. }
  4464. Result.setStdInitializerListElement(toStdInitializerList);
  4465. return Result;
  4466. }
  4467. // C++14 [over.ics.list]p4:
  4468. // C++11 [over.ics.list]p3:
  4469. // Otherwise, if the parameter is a non-aggregate class X and overload
  4470. // resolution chooses a single best constructor [...] the implicit
  4471. // conversion sequence is a user-defined conversion sequence. If multiple
  4472. // constructors are viable but none is better than the others, the
  4473. // implicit conversion sequence is a user-defined conversion sequence.
  4474. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4475. // This function can deal with initializer lists.
  4476. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4477. /*AllowExplicit=*/false,
  4478. InOverloadResolution, /*CStyle=*/false,
  4479. AllowObjCWritebackConversion,
  4480. /*AllowObjCConversionOnExplicit=*/false);
  4481. }
  4482. // C++14 [over.ics.list]p5:
  4483. // C++11 [over.ics.list]p4:
  4484. // Otherwise, if the parameter has an aggregate type which can be
  4485. // initialized from the initializer list [...] the implicit conversion
  4486. // sequence is a user-defined conversion sequence.
  4487. if (ToType->isAggregateType()) {
  4488. // Type is an aggregate, argument is an init list. At this point it comes
  4489. // down to checking whether the initialization works.
  4490. // FIXME: Find out whether this parameter is consumed or not.
  4491. InitializedEntity Entity =
  4492. InitializedEntity::InitializeParameter(S.Context, ToType,
  4493. /*Consumed=*/false);
  4494. if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
  4495. From)) {
  4496. Result.setUserDefined();
  4497. Result.UserDefined.Before.setAsIdentityConversion();
  4498. // Initializer lists don't have a type.
  4499. Result.UserDefined.Before.setFromType(QualType());
  4500. Result.UserDefined.Before.setAllToTypes(QualType());
  4501. Result.UserDefined.After.setAsIdentityConversion();
  4502. Result.UserDefined.After.setFromType(ToType);
  4503. Result.UserDefined.After.setAllToTypes(ToType);
  4504. Result.UserDefined.ConversionFunction = nullptr;
  4505. }
  4506. return Result;
  4507. }
  4508. // C++14 [over.ics.list]p6:
  4509. // C++11 [over.ics.list]p5:
  4510. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4511. if (ToType->isReferenceType()) {
  4512. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4513. // mention initializer lists in any way. So we go by what list-
  4514. // initialization would do and try to extrapolate from that.
  4515. QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
  4516. // If the initializer list has a single element that is reference-related
  4517. // to the parameter type, we initialize the reference from that.
  4518. if (From->getNumInits() == 1) {
  4519. Expr *Init = From->getInit(0);
  4520. QualType T2 = Init->getType();
  4521. // If the initializer is the address of an overloaded function, try
  4522. // to resolve the overloaded function. If all goes well, T2 is the
  4523. // type of the resulting function.
  4524. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4525. DeclAccessPair Found;
  4526. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4527. Init, ToType, false, Found))
  4528. T2 = Fn->getType();
  4529. }
  4530. // Compute some basic properties of the types and the initializer.
  4531. bool dummy1 = false;
  4532. bool dummy2 = false;
  4533. bool dummy3 = false;
  4534. bool dummy4 = false;
  4535. Sema::ReferenceCompareResult RefRelationship =
  4536. S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
  4537. dummy2, dummy3, dummy4);
  4538. if (RefRelationship >= Sema::Ref_Related) {
  4539. return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
  4540. SuppressUserConversions,
  4541. /*AllowExplicit=*/false);
  4542. }
  4543. }
  4544. // Otherwise, we bind the reference to a temporary created from the
  4545. // initializer list.
  4546. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4547. InOverloadResolution,
  4548. AllowObjCWritebackConversion);
  4549. if (Result.isFailure())
  4550. return Result;
  4551. assert(!Result.isEllipsis() &&
  4552. "Sub-initialization cannot result in ellipsis conversion.");
  4553. // Can we even bind to a temporary?
  4554. if (ToType->isRValueReferenceType() ||
  4555. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4556. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4557. Result.UserDefined.After;
  4558. SCS.ReferenceBinding = true;
  4559. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4560. SCS.BindsToRvalue = true;
  4561. SCS.BindsToFunctionLvalue = false;
  4562. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4563. SCS.ObjCLifetimeConversionBinding = false;
  4564. } else
  4565. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4566. From, ToType);
  4567. return Result;
  4568. }
  4569. // C++14 [over.ics.list]p7:
  4570. // C++11 [over.ics.list]p6:
  4571. // Otherwise, if the parameter type is not a class:
  4572. if (!ToType->isRecordType()) {
  4573. // - if the initializer list has one element that is not itself an
  4574. // initializer list, the implicit conversion sequence is the one
  4575. // required to convert the element to the parameter type.
  4576. unsigned NumInits = From->getNumInits();
  4577. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4578. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4579. SuppressUserConversions,
  4580. InOverloadResolution,
  4581. AllowObjCWritebackConversion);
  4582. // - if the initializer list has no elements, the implicit conversion
  4583. // sequence is the identity conversion.
  4584. else if (NumInits == 0) {
  4585. Result.setStandard();
  4586. Result.Standard.setAsIdentityConversion();
  4587. Result.Standard.setFromType(ToType);
  4588. Result.Standard.setAllToTypes(ToType);
  4589. }
  4590. return Result;
  4591. }
  4592. // C++14 [over.ics.list]p8:
  4593. // C++11 [over.ics.list]p7:
  4594. // In all cases other than those enumerated above, no conversion is possible
  4595. return Result;
  4596. }
  4597. /// TryCopyInitialization - Try to copy-initialize a value of type
  4598. /// ToType from the expression From. Return the implicit conversion
  4599. /// sequence required to pass this argument, which may be a bad
  4600. /// conversion sequence (meaning that the argument cannot be passed to
  4601. /// a parameter of this type). If @p SuppressUserConversions, then we
  4602. /// do not permit any user-defined conversion sequences.
  4603. static ImplicitConversionSequence
  4604. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4605. bool SuppressUserConversions,
  4606. bool InOverloadResolution,
  4607. bool AllowObjCWritebackConversion,
  4608. bool AllowExplicit) {
  4609. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4610. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4611. InOverloadResolution,AllowObjCWritebackConversion);
  4612. if (ToType->isReferenceType())
  4613. return TryReferenceInit(S, From, ToType,
  4614. /*FIXME:*/ From->getBeginLoc(),
  4615. SuppressUserConversions, AllowExplicit);
  4616. return TryImplicitConversion(S, From, ToType,
  4617. SuppressUserConversions,
  4618. /*AllowExplicit=*/false,
  4619. InOverloadResolution,
  4620. /*CStyle=*/false,
  4621. AllowObjCWritebackConversion,
  4622. /*AllowObjCConversionOnExplicit=*/false);
  4623. }
  4624. static bool TryCopyInitialization(const CanQualType FromQTy,
  4625. const CanQualType ToQTy,
  4626. Sema &S,
  4627. SourceLocation Loc,
  4628. ExprValueKind FromVK) {
  4629. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4630. ImplicitConversionSequence ICS =
  4631. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4632. return !ICS.isBad();
  4633. }
  4634. /// TryObjectArgumentInitialization - Try to initialize the object
  4635. /// parameter of the given member function (@c Method) from the
  4636. /// expression @p From.
  4637. static ImplicitConversionSequence
  4638. TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
  4639. Expr::Classification FromClassification,
  4640. CXXMethodDecl *Method,
  4641. CXXRecordDecl *ActingContext) {
  4642. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4643. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4644. // const volatile object.
  4645. Qualifiers Quals = Method->getMethodQualifiers();
  4646. if (isa<CXXDestructorDecl>(Method)) {
  4647. Quals.addConst();
  4648. Quals.addVolatile();
  4649. }
  4650. QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
  4651. // Set up the conversion sequence as a "bad" conversion, to allow us
  4652. // to exit early.
  4653. ImplicitConversionSequence ICS;
  4654. // We need to have an object of class type.
  4655. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4656. FromType = PT->getPointeeType();
  4657. // When we had a pointer, it's implicitly dereferenced, so we
  4658. // better have an lvalue.
  4659. assert(FromClassification.isLValue());
  4660. }
  4661. assert(FromType->isRecordType());
  4662. // C++0x [over.match.funcs]p4:
  4663. // For non-static member functions, the type of the implicit object
  4664. // parameter is
  4665. //
  4666. // - "lvalue reference to cv X" for functions declared without a
  4667. // ref-qualifier or with the & ref-qualifier
  4668. // - "rvalue reference to cv X" for functions declared with the &&
  4669. // ref-qualifier
  4670. //
  4671. // where X is the class of which the function is a member and cv is the
  4672. // cv-qualification on the member function declaration.
  4673. //
  4674. // However, when finding an implicit conversion sequence for the argument, we
  4675. // are not allowed to perform user-defined conversions
  4676. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4677. // reference binding here, that allows class rvalues to bind to
  4678. // non-constant references.
  4679. // First check the qualifiers.
  4680. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4681. if (ImplicitParamType.getCVRQualifiers()
  4682. != FromTypeCanon.getLocalCVRQualifiers() &&
  4683. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4684. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4685. FromType, ImplicitParamType);
  4686. return ICS;
  4687. }
  4688. if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
  4689. Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
  4690. Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
  4691. if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
  4692. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4693. FromType, ImplicitParamType);
  4694. return ICS;
  4695. }
  4696. }
  4697. // Check that we have either the same type or a derived type. It
  4698. // affects the conversion rank.
  4699. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4700. ImplicitConversionKind SecondKind;
  4701. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4702. SecondKind = ICK_Identity;
  4703. } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
  4704. SecondKind = ICK_Derived_To_Base;
  4705. else {
  4706. ICS.setBad(BadConversionSequence::unrelated_class,
  4707. FromType, ImplicitParamType);
  4708. return ICS;
  4709. }
  4710. // Check the ref-qualifier.
  4711. switch (Method->getRefQualifier()) {
  4712. case RQ_None:
  4713. // Do nothing; we don't care about lvalueness or rvalueness.
  4714. break;
  4715. case RQ_LValue:
  4716. if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
  4717. // non-const lvalue reference cannot bind to an rvalue
  4718. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4719. ImplicitParamType);
  4720. return ICS;
  4721. }
  4722. break;
  4723. case RQ_RValue:
  4724. if (!FromClassification.isRValue()) {
  4725. // rvalue reference cannot bind to an lvalue
  4726. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4727. ImplicitParamType);
  4728. return ICS;
  4729. }
  4730. break;
  4731. }
  4732. // Success. Mark this as a reference binding.
  4733. ICS.setStandard();
  4734. ICS.Standard.setAsIdentityConversion();
  4735. ICS.Standard.Second = SecondKind;
  4736. ICS.Standard.setFromType(FromType);
  4737. ICS.Standard.setAllToTypes(ImplicitParamType);
  4738. ICS.Standard.ReferenceBinding = true;
  4739. ICS.Standard.DirectBinding = true;
  4740. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4741. ICS.Standard.BindsToFunctionLvalue = false;
  4742. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4743. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4744. = (Method->getRefQualifier() == RQ_None);
  4745. return ICS;
  4746. }
  4747. /// PerformObjectArgumentInitialization - Perform initialization of
  4748. /// the implicit object parameter for the given Method with the given
  4749. /// expression.
  4750. ExprResult
  4751. Sema::PerformObjectArgumentInitialization(Expr *From,
  4752. NestedNameSpecifier *Qualifier,
  4753. NamedDecl *FoundDecl,
  4754. CXXMethodDecl *Method) {
  4755. QualType FromRecordType, DestType;
  4756. QualType ImplicitParamRecordType =
  4757. Method->getThisType()->castAs<PointerType>()->getPointeeType();
  4758. Expr::Classification FromClassification;
  4759. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4760. FromRecordType = PT->getPointeeType();
  4761. DestType = Method->getThisType();
  4762. FromClassification = Expr::Classification::makeSimpleLValue();
  4763. } else {
  4764. FromRecordType = From->getType();
  4765. DestType = ImplicitParamRecordType;
  4766. FromClassification = From->Classify(Context);
  4767. // When performing member access on an rvalue, materialize a temporary.
  4768. if (From->isRValue()) {
  4769. From = CreateMaterializeTemporaryExpr(FromRecordType, From,
  4770. Method->getRefQualifier() !=
  4771. RefQualifierKind::RQ_RValue);
  4772. }
  4773. }
  4774. // Note that we always use the true parent context when performing
  4775. // the actual argument initialization.
  4776. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4777. *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
  4778. Method->getParent());
  4779. if (ICS.isBad()) {
  4780. switch (ICS.Bad.Kind) {
  4781. case BadConversionSequence::bad_qualifiers: {
  4782. Qualifiers FromQs = FromRecordType.getQualifiers();
  4783. Qualifiers ToQs = DestType.getQualifiers();
  4784. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4785. if (CVR) {
  4786. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
  4787. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4788. << From->getSourceRange();
  4789. Diag(Method->getLocation(), diag::note_previous_decl)
  4790. << Method->getDeclName();
  4791. return ExprError();
  4792. }
  4793. break;
  4794. }
  4795. case BadConversionSequence::lvalue_ref_to_rvalue:
  4796. case BadConversionSequence::rvalue_ref_to_lvalue: {
  4797. bool IsRValueQualified =
  4798. Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
  4799. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
  4800. << Method->getDeclName() << FromClassification.isRValue()
  4801. << IsRValueQualified;
  4802. Diag(Method->getLocation(), diag::note_previous_decl)
  4803. << Method->getDeclName();
  4804. return ExprError();
  4805. }
  4806. case BadConversionSequence::no_conversion:
  4807. case BadConversionSequence::unrelated_class:
  4808. break;
  4809. }
  4810. return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
  4811. << ImplicitParamRecordType << FromRecordType
  4812. << From->getSourceRange();
  4813. }
  4814. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4815. ExprResult FromRes =
  4816. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4817. if (FromRes.isInvalid())
  4818. return ExprError();
  4819. From = FromRes.get();
  4820. }
  4821. if (!Context.hasSameType(From->getType(), DestType)) {
  4822. CastKind CK;
  4823. if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
  4824. CK = CK_AddressSpaceConversion;
  4825. else
  4826. CK = CK_NoOp;
  4827. From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
  4828. }
  4829. return From;
  4830. }
  4831. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4832. /// expression From to bool (C++0x [conv]p3).
  4833. static ImplicitConversionSequence
  4834. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4835. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4836. /*SuppressUserConversions=*/false,
  4837. /*AllowExplicit=*/true,
  4838. /*InOverloadResolution=*/false,
  4839. /*CStyle=*/false,
  4840. /*AllowObjCWritebackConversion=*/false,
  4841. /*AllowObjCConversionOnExplicit=*/false);
  4842. }
  4843. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4844. /// of the expression From to bool (C++0x [conv]p3).
  4845. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4846. if (checkPlaceholderForOverload(*this, From))
  4847. return ExprError();
  4848. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4849. if (!ICS.isBad())
  4850. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4851. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4852. return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
  4853. << From->getType() << From->getSourceRange();
  4854. return ExprError();
  4855. }
  4856. /// Check that the specified conversion is permitted in a converted constant
  4857. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4858. /// is acceptable.
  4859. static bool CheckConvertedConstantConversions(Sema &S,
  4860. StandardConversionSequence &SCS) {
  4861. // Since we know that the target type is an integral or unscoped enumeration
  4862. // type, most conversion kinds are impossible. All possible First and Third
  4863. // conversions are fine.
  4864. switch (SCS.Second) {
  4865. case ICK_Identity:
  4866. case ICK_Function_Conversion:
  4867. case ICK_Integral_Promotion:
  4868. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4869. case ICK_Zero_Queue_Conversion:
  4870. return true;
  4871. case ICK_Boolean_Conversion:
  4872. // Conversion from an integral or unscoped enumeration type to bool is
  4873. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4874. // conversion, so we allow it in a converted constant expression.
  4875. //
  4876. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4877. // a lot of popular code. We should at least add a warning for this
  4878. // (non-conforming) extension.
  4879. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4880. SCS.getToType(2)->isBooleanType();
  4881. case ICK_Pointer_Conversion:
  4882. case ICK_Pointer_Member:
  4883. // C++1z: null pointer conversions and null member pointer conversions are
  4884. // only permitted if the source type is std::nullptr_t.
  4885. return SCS.getFromType()->isNullPtrType();
  4886. case ICK_Floating_Promotion:
  4887. case ICK_Complex_Promotion:
  4888. case ICK_Floating_Conversion:
  4889. case ICK_Complex_Conversion:
  4890. case ICK_Floating_Integral:
  4891. case ICK_Compatible_Conversion:
  4892. case ICK_Derived_To_Base:
  4893. case ICK_Vector_Conversion:
  4894. case ICK_Vector_Splat:
  4895. case ICK_Complex_Real:
  4896. case ICK_Block_Pointer_Conversion:
  4897. case ICK_TransparentUnionConversion:
  4898. case ICK_Writeback_Conversion:
  4899. case ICK_Zero_Event_Conversion:
  4900. case ICK_C_Only_Conversion:
  4901. case ICK_Incompatible_Pointer_Conversion:
  4902. return false;
  4903. case ICK_Lvalue_To_Rvalue:
  4904. case ICK_Array_To_Pointer:
  4905. case ICK_Function_To_Pointer:
  4906. llvm_unreachable("found a first conversion kind in Second");
  4907. case ICK_Qualification:
  4908. llvm_unreachable("found a third conversion kind in Second");
  4909. case ICK_Num_Conversion_Kinds:
  4910. break;
  4911. }
  4912. llvm_unreachable("unknown conversion kind");
  4913. }
  4914. /// CheckConvertedConstantExpression - Check that the expression From is a
  4915. /// converted constant expression of type T, perform the conversion and produce
  4916. /// the converted expression, per C++11 [expr.const]p3.
  4917. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4918. QualType T, APValue &Value,
  4919. Sema::CCEKind CCE,
  4920. bool RequireInt) {
  4921. assert(S.getLangOpts().CPlusPlus11 &&
  4922. "converted constant expression outside C++11");
  4923. if (checkPlaceholderForOverload(S, From))
  4924. return ExprError();
  4925. // C++1z [expr.const]p3:
  4926. // A converted constant expression of type T is an expression,
  4927. // implicitly converted to type T, where the converted
  4928. // expression is a constant expression and the implicit conversion
  4929. // sequence contains only [... list of conversions ...].
  4930. // C++1z [stmt.if]p2:
  4931. // If the if statement is of the form if constexpr, the value of the
  4932. // condition shall be a contextually converted constant expression of type
  4933. // bool.
  4934. ImplicitConversionSequence ICS =
  4935. CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
  4936. ? TryContextuallyConvertToBool(S, From)
  4937. : TryCopyInitialization(S, From, T,
  4938. /*SuppressUserConversions=*/false,
  4939. /*InOverloadResolution=*/false,
  4940. /*AllowObjCWritebackConversion=*/false,
  4941. /*AllowExplicit=*/false);
  4942. StandardConversionSequence *SCS = nullptr;
  4943. switch (ICS.getKind()) {
  4944. case ImplicitConversionSequence::StandardConversion:
  4945. SCS = &ICS.Standard;
  4946. break;
  4947. case ImplicitConversionSequence::UserDefinedConversion:
  4948. // We are converting to a non-class type, so the Before sequence
  4949. // must be trivial.
  4950. SCS = &ICS.UserDefined.After;
  4951. break;
  4952. case ImplicitConversionSequence::AmbiguousConversion:
  4953. case ImplicitConversionSequence::BadConversion:
  4954. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4955. return S.Diag(From->getBeginLoc(),
  4956. diag::err_typecheck_converted_constant_expression)
  4957. << From->getType() << From->getSourceRange() << T;
  4958. return ExprError();
  4959. case ImplicitConversionSequence::EllipsisConversion:
  4960. llvm_unreachable("ellipsis conversion in converted constant expression");
  4961. }
  4962. // Check that we would only use permitted conversions.
  4963. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4964. return S.Diag(From->getBeginLoc(),
  4965. diag::err_typecheck_converted_constant_expression_disallowed)
  4966. << From->getType() << From->getSourceRange() << T;
  4967. }
  4968. // [...] and where the reference binding (if any) binds directly.
  4969. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4970. return S.Diag(From->getBeginLoc(),
  4971. diag::err_typecheck_converted_constant_expression_indirect)
  4972. << From->getType() << From->getSourceRange() << T;
  4973. }
  4974. ExprResult Result =
  4975. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4976. if (Result.isInvalid())
  4977. return Result;
  4978. // C++2a [intro.execution]p5:
  4979. // A full-expression is [...] a constant-expression [...]
  4980. Result =
  4981. S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
  4982. /*DiscardedValue=*/false, /*IsConstexpr=*/true);
  4983. if (Result.isInvalid())
  4984. return Result;
  4985. // Check for a narrowing implicit conversion.
  4986. APValue PreNarrowingValue;
  4987. QualType PreNarrowingType;
  4988. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4989. PreNarrowingType)) {
  4990. case NK_Dependent_Narrowing:
  4991. // Implicit conversion to a narrower type, but the expression is
  4992. // value-dependent so we can't tell whether it's actually narrowing.
  4993. case NK_Variable_Narrowing:
  4994. // Implicit conversion to a narrower type, and the value is not a constant
  4995. // expression. We'll diagnose this in a moment.
  4996. case NK_Not_Narrowing:
  4997. break;
  4998. case NK_Constant_Narrowing:
  4999. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  5000. << CCE << /*Constant*/ 1
  5001. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  5002. break;
  5003. case NK_Type_Narrowing:
  5004. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  5005. << CCE << /*Constant*/ 0 << From->getType() << T;
  5006. break;
  5007. }
  5008. if (Result.get()->isValueDependent()) {
  5009. Value = APValue();
  5010. return Result;
  5011. }
  5012. // Check the expression is a constant expression.
  5013. SmallVector<PartialDiagnosticAt, 8> Notes;
  5014. Expr::EvalResult Eval;
  5015. Eval.Diag = &Notes;
  5016. Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
  5017. ? Expr::EvaluateForMangling
  5018. : Expr::EvaluateForCodeGen;
  5019. if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
  5020. (RequireInt && !Eval.Val.isInt())) {
  5021. // The expression can't be folded, so we can't keep it at this position in
  5022. // the AST.
  5023. Result = ExprError();
  5024. } else {
  5025. Value = Eval.Val;
  5026. if (Notes.empty()) {
  5027. // It's a constant expression.
  5028. return ConstantExpr::Create(S.Context, Result.get(), Value);
  5029. }
  5030. }
  5031. // It's not a constant expression. Produce an appropriate diagnostic.
  5032. if (Notes.size() == 1 &&
  5033. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  5034. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  5035. else {
  5036. S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
  5037. << CCE << From->getSourceRange();
  5038. for (unsigned I = 0; I < Notes.size(); ++I)
  5039. S.Diag(Notes[I].first, Notes[I].second);
  5040. }
  5041. return ExprError();
  5042. }
  5043. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  5044. APValue &Value, CCEKind CCE) {
  5045. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  5046. }
  5047. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  5048. llvm::APSInt &Value,
  5049. CCEKind CCE) {
  5050. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  5051. APValue V;
  5052. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  5053. if (!R.isInvalid() && !R.get()->isValueDependent())
  5054. Value = V.getInt();
  5055. return R;
  5056. }
  5057. /// dropPointerConversions - If the given standard conversion sequence
  5058. /// involves any pointer conversions, remove them. This may change
  5059. /// the result type of the conversion sequence.
  5060. static void dropPointerConversion(StandardConversionSequence &SCS) {
  5061. if (SCS.Second == ICK_Pointer_Conversion) {
  5062. SCS.Second = ICK_Identity;
  5063. SCS.Third = ICK_Identity;
  5064. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  5065. }
  5066. }
  5067. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  5068. /// convert the expression From to an Objective-C pointer type.
  5069. static ImplicitConversionSequence
  5070. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  5071. // Do an implicit conversion to 'id'.
  5072. QualType Ty = S.Context.getObjCIdType();
  5073. ImplicitConversionSequence ICS
  5074. = TryImplicitConversion(S, From, Ty,
  5075. // FIXME: Are these flags correct?
  5076. /*SuppressUserConversions=*/false,
  5077. /*AllowExplicit=*/true,
  5078. /*InOverloadResolution=*/false,
  5079. /*CStyle=*/false,
  5080. /*AllowObjCWritebackConversion=*/false,
  5081. /*AllowObjCConversionOnExplicit=*/true);
  5082. // Strip off any final conversions to 'id'.
  5083. switch (ICS.getKind()) {
  5084. case ImplicitConversionSequence::BadConversion:
  5085. case ImplicitConversionSequence::AmbiguousConversion:
  5086. case ImplicitConversionSequence::EllipsisConversion:
  5087. break;
  5088. case ImplicitConversionSequence::UserDefinedConversion:
  5089. dropPointerConversion(ICS.UserDefined.After);
  5090. break;
  5091. case ImplicitConversionSequence::StandardConversion:
  5092. dropPointerConversion(ICS.Standard);
  5093. break;
  5094. }
  5095. return ICS;
  5096. }
  5097. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  5098. /// conversion of the expression From to an Objective-C pointer type.
  5099. /// Returns a valid but null ExprResult if no conversion sequence exists.
  5100. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  5101. if (checkPlaceholderForOverload(*this, From))
  5102. return ExprError();
  5103. QualType Ty = Context.getObjCIdType();
  5104. ImplicitConversionSequence ICS =
  5105. TryContextuallyConvertToObjCPointer(*this, From);
  5106. if (!ICS.isBad())
  5107. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  5108. return ExprResult();
  5109. }
  5110. /// Determine whether the provided type is an integral type, or an enumeration
  5111. /// type of a permitted flavor.
  5112. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  5113. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  5114. : T->isIntegralOrUnscopedEnumerationType();
  5115. }
  5116. static ExprResult
  5117. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  5118. Sema::ContextualImplicitConverter &Converter,
  5119. QualType T, UnresolvedSetImpl &ViableConversions) {
  5120. if (Converter.Suppress)
  5121. return ExprError();
  5122. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  5123. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5124. CXXConversionDecl *Conv =
  5125. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  5126. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  5127. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  5128. }
  5129. return From;
  5130. }
  5131. static bool
  5132. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5133. Sema::ContextualImplicitConverter &Converter,
  5134. QualType T, bool HadMultipleCandidates,
  5135. UnresolvedSetImpl &ExplicitConversions) {
  5136. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  5137. DeclAccessPair Found = ExplicitConversions[0];
  5138. CXXConversionDecl *Conversion =
  5139. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5140. // The user probably meant to invoke the given explicit
  5141. // conversion; use it.
  5142. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  5143. std::string TypeStr;
  5144. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  5145. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  5146. << FixItHint::CreateInsertion(From->getBeginLoc(),
  5147. "static_cast<" + TypeStr + ">(")
  5148. << FixItHint::CreateInsertion(
  5149. SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
  5150. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  5151. // If we aren't in a SFINAE context, build a call to the
  5152. // explicit conversion function.
  5153. if (SemaRef.isSFINAEContext())
  5154. return true;
  5155. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5156. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5157. HadMultipleCandidates);
  5158. if (Result.isInvalid())
  5159. return true;
  5160. // Record usage of conversion in an implicit cast.
  5161. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5162. CK_UserDefinedConversion, Result.get(),
  5163. nullptr, Result.get()->getValueKind());
  5164. }
  5165. return false;
  5166. }
  5167. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5168. Sema::ContextualImplicitConverter &Converter,
  5169. QualType T, bool HadMultipleCandidates,
  5170. DeclAccessPair &Found) {
  5171. CXXConversionDecl *Conversion =
  5172. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5173. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5174. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  5175. if (!Converter.SuppressConversion) {
  5176. if (SemaRef.isSFINAEContext())
  5177. return true;
  5178. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  5179. << From->getSourceRange();
  5180. }
  5181. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5182. HadMultipleCandidates);
  5183. if (Result.isInvalid())
  5184. return true;
  5185. // Record usage of conversion in an implicit cast.
  5186. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5187. CK_UserDefinedConversion, Result.get(),
  5188. nullptr, Result.get()->getValueKind());
  5189. return false;
  5190. }
  5191. static ExprResult finishContextualImplicitConversion(
  5192. Sema &SemaRef, SourceLocation Loc, Expr *From,
  5193. Sema::ContextualImplicitConverter &Converter) {
  5194. if (!Converter.match(From->getType()) && !Converter.Suppress)
  5195. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  5196. << From->getSourceRange();
  5197. return SemaRef.DefaultLvalueConversion(From);
  5198. }
  5199. static void
  5200. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  5201. UnresolvedSetImpl &ViableConversions,
  5202. OverloadCandidateSet &CandidateSet) {
  5203. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5204. DeclAccessPair FoundDecl = ViableConversions[I];
  5205. NamedDecl *D = FoundDecl.getDecl();
  5206. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  5207. if (isa<UsingShadowDecl>(D))
  5208. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  5209. CXXConversionDecl *Conv;
  5210. FunctionTemplateDecl *ConvTemplate;
  5211. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  5212. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5213. else
  5214. Conv = cast<CXXConversionDecl>(D);
  5215. if (ConvTemplate)
  5216. SemaRef.AddTemplateConversionCandidate(
  5217. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  5218. /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
  5219. else
  5220. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  5221. ToType, CandidateSet,
  5222. /*AllowObjCConversionOnExplicit=*/false,
  5223. /*AllowExplicit*/ true);
  5224. }
  5225. }
  5226. /// Attempt to convert the given expression to a type which is accepted
  5227. /// by the given converter.
  5228. ///
  5229. /// This routine will attempt to convert an expression of class type to a
  5230. /// type accepted by the specified converter. In C++11 and before, the class
  5231. /// must have a single non-explicit conversion function converting to a matching
  5232. /// type. In C++1y, there can be multiple such conversion functions, but only
  5233. /// one target type.
  5234. ///
  5235. /// \param Loc The source location of the construct that requires the
  5236. /// conversion.
  5237. ///
  5238. /// \param From The expression we're converting from.
  5239. ///
  5240. /// \param Converter Used to control and diagnose the conversion process.
  5241. ///
  5242. /// \returns The expression, converted to an integral or enumeration type if
  5243. /// successful.
  5244. ExprResult Sema::PerformContextualImplicitConversion(
  5245. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  5246. // We can't perform any more checking for type-dependent expressions.
  5247. if (From->isTypeDependent())
  5248. return From;
  5249. // Process placeholders immediately.
  5250. if (From->hasPlaceholderType()) {
  5251. ExprResult result = CheckPlaceholderExpr(From);
  5252. if (result.isInvalid())
  5253. return result;
  5254. From = result.get();
  5255. }
  5256. // If the expression already has a matching type, we're golden.
  5257. QualType T = From->getType();
  5258. if (Converter.match(T))
  5259. return DefaultLvalueConversion(From);
  5260. // FIXME: Check for missing '()' if T is a function type?
  5261. // We can only perform contextual implicit conversions on objects of class
  5262. // type.
  5263. const RecordType *RecordTy = T->getAs<RecordType>();
  5264. if (!RecordTy || !getLangOpts().CPlusPlus) {
  5265. if (!Converter.Suppress)
  5266. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  5267. return From;
  5268. }
  5269. // We must have a complete class type.
  5270. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  5271. ContextualImplicitConverter &Converter;
  5272. Expr *From;
  5273. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  5274. : Converter(Converter), From(From) {}
  5275. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  5276. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  5277. }
  5278. } IncompleteDiagnoser(Converter, From);
  5279. if (Converter.Suppress ? !isCompleteType(Loc, T)
  5280. : RequireCompleteType(Loc, T, IncompleteDiagnoser))
  5281. return From;
  5282. // Look for a conversion to an integral or enumeration type.
  5283. UnresolvedSet<4>
  5284. ViableConversions; // These are *potentially* viable in C++1y.
  5285. UnresolvedSet<4> ExplicitConversions;
  5286. const auto &Conversions =
  5287. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  5288. bool HadMultipleCandidates =
  5289. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  5290. // To check that there is only one target type, in C++1y:
  5291. QualType ToType;
  5292. bool HasUniqueTargetType = true;
  5293. // Collect explicit or viable (potentially in C++1y) conversions.
  5294. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  5295. NamedDecl *D = (*I)->getUnderlyingDecl();
  5296. CXXConversionDecl *Conversion;
  5297. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  5298. if (ConvTemplate) {
  5299. if (getLangOpts().CPlusPlus14)
  5300. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5301. else
  5302. continue; // C++11 does not consider conversion operator templates(?).
  5303. } else
  5304. Conversion = cast<CXXConversionDecl>(D);
  5305. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  5306. "Conversion operator templates are considered potentially "
  5307. "viable in C++1y");
  5308. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  5309. if (Converter.match(CurToType) || ConvTemplate) {
  5310. if (Conversion->isExplicit()) {
  5311. // FIXME: For C++1y, do we need this restriction?
  5312. // cf. diagnoseNoViableConversion()
  5313. if (!ConvTemplate)
  5314. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  5315. } else {
  5316. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  5317. if (ToType.isNull())
  5318. ToType = CurToType.getUnqualifiedType();
  5319. else if (HasUniqueTargetType &&
  5320. (CurToType.getUnqualifiedType() != ToType))
  5321. HasUniqueTargetType = false;
  5322. }
  5323. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5324. }
  5325. }
  5326. }
  5327. if (getLangOpts().CPlusPlus14) {
  5328. // C++1y [conv]p6:
  5329. // ... An expression e of class type E appearing in such a context
  5330. // is said to be contextually implicitly converted to a specified
  5331. // type T and is well-formed if and only if e can be implicitly
  5332. // converted to a type T that is determined as follows: E is searched
  5333. // for conversion functions whose return type is cv T or reference to
  5334. // cv T such that T is allowed by the context. There shall be
  5335. // exactly one such T.
  5336. // If no unique T is found:
  5337. if (ToType.isNull()) {
  5338. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5339. HadMultipleCandidates,
  5340. ExplicitConversions))
  5341. return ExprError();
  5342. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5343. }
  5344. // If more than one unique Ts are found:
  5345. if (!HasUniqueTargetType)
  5346. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5347. ViableConversions);
  5348. // If one unique T is found:
  5349. // First, build a candidate set from the previously recorded
  5350. // potentially viable conversions.
  5351. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5352. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5353. CandidateSet);
  5354. // Then, perform overload resolution over the candidate set.
  5355. OverloadCandidateSet::iterator Best;
  5356. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5357. case OR_Success: {
  5358. // Apply this conversion.
  5359. DeclAccessPair Found =
  5360. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5361. if (recordConversion(*this, Loc, From, Converter, T,
  5362. HadMultipleCandidates, Found))
  5363. return ExprError();
  5364. break;
  5365. }
  5366. case OR_Ambiguous:
  5367. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5368. ViableConversions);
  5369. case OR_No_Viable_Function:
  5370. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5371. HadMultipleCandidates,
  5372. ExplicitConversions))
  5373. return ExprError();
  5374. LLVM_FALLTHROUGH;
  5375. case OR_Deleted:
  5376. // We'll complain below about a non-integral condition type.
  5377. break;
  5378. }
  5379. } else {
  5380. switch (ViableConversions.size()) {
  5381. case 0: {
  5382. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5383. HadMultipleCandidates,
  5384. ExplicitConversions))
  5385. return ExprError();
  5386. // We'll complain below about a non-integral condition type.
  5387. break;
  5388. }
  5389. case 1: {
  5390. // Apply this conversion.
  5391. DeclAccessPair Found = ViableConversions[0];
  5392. if (recordConversion(*this, Loc, From, Converter, T,
  5393. HadMultipleCandidates, Found))
  5394. return ExprError();
  5395. break;
  5396. }
  5397. default:
  5398. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5399. ViableConversions);
  5400. }
  5401. }
  5402. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5403. }
  5404. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5405. /// an acceptable non-member overloaded operator for a call whose
  5406. /// arguments have types T1 (and, if non-empty, T2). This routine
  5407. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5408. /// enumeration types.
  5409. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5410. FunctionDecl *Fn,
  5411. ArrayRef<Expr *> Args) {
  5412. QualType T1 = Args[0]->getType();
  5413. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5414. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5415. return true;
  5416. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5417. return true;
  5418. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5419. if (Proto->getNumParams() < 1)
  5420. return false;
  5421. if (T1->isEnumeralType()) {
  5422. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5423. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5424. return true;
  5425. }
  5426. if (Proto->getNumParams() < 2)
  5427. return false;
  5428. if (!T2.isNull() && T2->isEnumeralType()) {
  5429. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5430. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5431. return true;
  5432. }
  5433. return false;
  5434. }
  5435. /// AddOverloadCandidate - Adds the given function to the set of
  5436. /// candidate functions, using the given function call arguments. If
  5437. /// @p SuppressUserConversions, then don't allow user-defined
  5438. /// conversions via constructors or conversion operators.
  5439. ///
  5440. /// \param PartialOverloading true if we are performing "partial" overloading
  5441. /// based on an incomplete set of function arguments. This feature is used by
  5442. /// code completion.
  5443. void Sema::AddOverloadCandidate(
  5444. FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
  5445. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  5446. bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
  5447. ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
  5448. OverloadCandidateParamOrder PO) {
  5449. const FunctionProtoType *Proto
  5450. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5451. assert(Proto && "Functions without a prototype cannot be overloaded");
  5452. assert(!Function->getDescribedFunctionTemplate() &&
  5453. "Use AddTemplateOverloadCandidate for function templates");
  5454. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5455. if (!isa<CXXConstructorDecl>(Method)) {
  5456. // If we get here, it's because we're calling a member function
  5457. // that is named without a member access expression (e.g.,
  5458. // "this->f") that was either written explicitly or created
  5459. // implicitly. This can happen with a qualified call to a member
  5460. // function, e.g., X::f(). We use an empty type for the implied
  5461. // object argument (C++ [over.call.func]p3), and the acting context
  5462. // is irrelevant.
  5463. AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
  5464. Expr::Classification::makeSimpleLValue(), Args,
  5465. CandidateSet, SuppressUserConversions,
  5466. PartialOverloading, EarlyConversions, PO);
  5467. return;
  5468. }
  5469. // We treat a constructor like a non-member function, since its object
  5470. // argument doesn't participate in overload resolution.
  5471. }
  5472. if (!CandidateSet.isNewCandidate(Function, PO))
  5473. return;
  5474. // C++11 [class.copy]p11: [DR1402]
  5475. // A defaulted move constructor that is defined as deleted is ignored by
  5476. // overload resolution.
  5477. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5478. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5479. Constructor->isMoveConstructor())
  5480. return;
  5481. // Overload resolution is always an unevaluated context.
  5482. EnterExpressionEvaluationContext Unevaluated(
  5483. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5484. // C++ [over.match.oper]p3:
  5485. // if no operand has a class type, only those non-member functions in the
  5486. // lookup set that have a first parameter of type T1 or "reference to
  5487. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5488. // is a right operand) a second parameter of type T2 or "reference to
  5489. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5490. // candidate functions.
  5491. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5492. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5493. return;
  5494. // Add this candidate
  5495. OverloadCandidate &Candidate =
  5496. CandidateSet.addCandidate(Args.size(), EarlyConversions);
  5497. Candidate.FoundDecl = FoundDecl;
  5498. Candidate.Function = Function;
  5499. Candidate.Viable = true;
  5500. Candidate.RewriteKind =
  5501. CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
  5502. Candidate.IsSurrogate = false;
  5503. Candidate.IsADLCandidate = IsADLCandidate;
  5504. Candidate.IgnoreObjectArgument = false;
  5505. Candidate.ExplicitCallArguments = Args.size();
  5506. if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
  5507. !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
  5508. Candidate.Viable = false;
  5509. Candidate.FailureKind = ovl_non_default_multiversion_function;
  5510. return;
  5511. }
  5512. if (Constructor) {
  5513. // C++ [class.copy]p3:
  5514. // A member function template is never instantiated to perform the copy
  5515. // of a class object to an object of its class type.
  5516. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5517. if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
  5518. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5519. IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
  5520. ClassType))) {
  5521. Candidate.Viable = false;
  5522. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5523. return;
  5524. }
  5525. // C++ [over.match.funcs]p8: (proposed DR resolution)
  5526. // A constructor inherited from class type C that has a first parameter
  5527. // of type "reference to P" (including such a constructor instantiated
  5528. // from a template) is excluded from the set of candidate functions when
  5529. // constructing an object of type cv D if the argument list has exactly
  5530. // one argument and D is reference-related to P and P is reference-related
  5531. // to C.
  5532. auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
  5533. if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
  5534. Constructor->getParamDecl(0)->getType()->isReferenceType()) {
  5535. QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
  5536. QualType C = Context.getRecordType(Constructor->getParent());
  5537. QualType D = Context.getRecordType(Shadow->getParent());
  5538. SourceLocation Loc = Args.front()->getExprLoc();
  5539. if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
  5540. (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
  5541. Candidate.Viable = false;
  5542. Candidate.FailureKind = ovl_fail_inhctor_slice;
  5543. return;
  5544. }
  5545. }
  5546. // Check that the constructor is capable of constructing an object in the
  5547. // destination address space.
  5548. if (!Qualifiers::isAddressSpaceSupersetOf(
  5549. Constructor->getMethodQualifiers().getAddressSpace(),
  5550. CandidateSet.getDestAS())) {
  5551. Candidate.Viable = false;
  5552. Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
  5553. }
  5554. }
  5555. unsigned NumParams = Proto->getNumParams();
  5556. // (C++ 13.3.2p2): A candidate function having fewer than m
  5557. // parameters is viable only if it has an ellipsis in its parameter
  5558. // list (8.3.5).
  5559. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5560. !Proto->isVariadic()) {
  5561. Candidate.Viable = false;
  5562. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5563. return;
  5564. }
  5565. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5566. // is viable only if the (m+1)st parameter has a default argument
  5567. // (8.3.6). For the purposes of overload resolution, the
  5568. // parameter list is truncated on the right, so that there are
  5569. // exactly m parameters.
  5570. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5571. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5572. // Not enough arguments.
  5573. Candidate.Viable = false;
  5574. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5575. return;
  5576. }
  5577. // (CUDA B.1): Check for invalid calls between targets.
  5578. if (getLangOpts().CUDA)
  5579. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5580. // Skip the check for callers that are implicit members, because in this
  5581. // case we may not yet know what the member's target is; the target is
  5582. // inferred for the member automatically, based on the bases and fields of
  5583. // the class.
  5584. if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
  5585. Candidate.Viable = false;
  5586. Candidate.FailureKind = ovl_fail_bad_target;
  5587. return;
  5588. }
  5589. // Determine the implicit conversion sequences for each of the
  5590. // arguments.
  5591. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5592. unsigned ConvIdx =
  5593. PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
  5594. if (Candidate.Conversions[ConvIdx].isInitialized()) {
  5595. // We already formed a conversion sequence for this parameter during
  5596. // template argument deduction.
  5597. } else if (ArgIdx < NumParams) {
  5598. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5599. // exist for each argument an implicit conversion sequence
  5600. // (13.3.3.1) that converts that argument to the corresponding
  5601. // parameter of F.
  5602. QualType ParamType = Proto->getParamType(ArgIdx);
  5603. Candidate.Conversions[ConvIdx] = TryCopyInitialization(
  5604. *this, Args[ArgIdx], ParamType, SuppressUserConversions,
  5605. /*InOverloadResolution=*/true,
  5606. /*AllowObjCWritebackConversion=*/
  5607. getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
  5608. if (Candidate.Conversions[ConvIdx].isBad()) {
  5609. Candidate.Viable = false;
  5610. Candidate.FailureKind = ovl_fail_bad_conversion;
  5611. return;
  5612. }
  5613. } else {
  5614. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5615. // argument for which there is no corresponding parameter is
  5616. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5617. Candidate.Conversions[ConvIdx].setEllipsis();
  5618. }
  5619. }
  5620. if (!AllowExplicit) {
  5621. ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
  5622. if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
  5623. Candidate.Viable = false;
  5624. Candidate.FailureKind = ovl_fail_explicit_resolved;
  5625. return;
  5626. }
  5627. }
  5628. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5629. Candidate.Viable = false;
  5630. Candidate.FailureKind = ovl_fail_enable_if;
  5631. Candidate.DeductionFailure.Data = FailedAttr;
  5632. return;
  5633. }
  5634. if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
  5635. Candidate.Viable = false;
  5636. Candidate.FailureKind = ovl_fail_ext_disabled;
  5637. return;
  5638. }
  5639. }
  5640. ObjCMethodDecl *
  5641. Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
  5642. SmallVectorImpl<ObjCMethodDecl *> &Methods) {
  5643. if (Methods.size() <= 1)
  5644. return nullptr;
  5645. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5646. bool Match = true;
  5647. ObjCMethodDecl *Method = Methods[b];
  5648. unsigned NumNamedArgs = Sel.getNumArgs();
  5649. // Method might have more arguments than selector indicates. This is due
  5650. // to addition of c-style arguments in method.
  5651. if (Method->param_size() > NumNamedArgs)
  5652. NumNamedArgs = Method->param_size();
  5653. if (Args.size() < NumNamedArgs)
  5654. continue;
  5655. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5656. // We can't do any type-checking on a type-dependent argument.
  5657. if (Args[i]->isTypeDependent()) {
  5658. Match = false;
  5659. break;
  5660. }
  5661. ParmVarDecl *param = Method->parameters()[i];
  5662. Expr *argExpr = Args[i];
  5663. assert(argExpr && "SelectBestMethod(): missing expression");
  5664. // Strip the unbridged-cast placeholder expression off unless it's
  5665. // a consumed argument.
  5666. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5667. !param->hasAttr<CFConsumedAttr>())
  5668. argExpr = stripARCUnbridgedCast(argExpr);
  5669. // If the parameter is __unknown_anytype, move on to the next method.
  5670. if (param->getType() == Context.UnknownAnyTy) {
  5671. Match = false;
  5672. break;
  5673. }
  5674. ImplicitConversionSequence ConversionState
  5675. = TryCopyInitialization(*this, argExpr, param->getType(),
  5676. /*SuppressUserConversions*/false,
  5677. /*InOverloadResolution=*/true,
  5678. /*AllowObjCWritebackConversion=*/
  5679. getLangOpts().ObjCAutoRefCount,
  5680. /*AllowExplicit*/false);
  5681. // This function looks for a reasonably-exact match, so we consider
  5682. // incompatible pointer conversions to be a failure here.
  5683. if (ConversionState.isBad() ||
  5684. (ConversionState.isStandard() &&
  5685. ConversionState.Standard.Second ==
  5686. ICK_Incompatible_Pointer_Conversion)) {
  5687. Match = false;
  5688. break;
  5689. }
  5690. }
  5691. // Promote additional arguments to variadic methods.
  5692. if (Match && Method->isVariadic()) {
  5693. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5694. if (Args[i]->isTypeDependent()) {
  5695. Match = false;
  5696. break;
  5697. }
  5698. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5699. nullptr);
  5700. if (Arg.isInvalid()) {
  5701. Match = false;
  5702. break;
  5703. }
  5704. }
  5705. } else {
  5706. // Check for extra arguments to non-variadic methods.
  5707. if (Args.size() != NumNamedArgs)
  5708. Match = false;
  5709. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5710. // Special case when selectors have no argument. In this case, select
  5711. // one with the most general result type of 'id'.
  5712. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5713. QualType ReturnT = Methods[b]->getReturnType();
  5714. if (ReturnT->isObjCIdType())
  5715. return Methods[b];
  5716. }
  5717. }
  5718. }
  5719. if (Match)
  5720. return Method;
  5721. }
  5722. return nullptr;
  5723. }
  5724. static bool
  5725. convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
  5726. ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
  5727. bool MissingImplicitThis, Expr *&ConvertedThis,
  5728. SmallVectorImpl<Expr *> &ConvertedArgs) {
  5729. if (ThisArg) {
  5730. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5731. assert(!isa<CXXConstructorDecl>(Method) &&
  5732. "Shouldn't have `this` for ctors!");
  5733. assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
  5734. ExprResult R = S.PerformObjectArgumentInitialization(
  5735. ThisArg, /*Qualifier=*/nullptr, Method, Method);
  5736. if (R.isInvalid())
  5737. return false;
  5738. ConvertedThis = R.get();
  5739. } else {
  5740. if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
  5741. (void)MD;
  5742. assert((MissingImplicitThis || MD->isStatic() ||
  5743. isa<CXXConstructorDecl>(MD)) &&
  5744. "Expected `this` for non-ctor instance methods");
  5745. }
  5746. ConvertedThis = nullptr;
  5747. }
  5748. // Ignore any variadic arguments. Converting them is pointless, since the
  5749. // user can't refer to them in the function condition.
  5750. unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
  5751. // Convert the arguments.
  5752. for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
  5753. ExprResult R;
  5754. R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5755. S.Context, Function->getParamDecl(I)),
  5756. SourceLocation(), Args[I]);
  5757. if (R.isInvalid())
  5758. return false;
  5759. ConvertedArgs.push_back(R.get());
  5760. }
  5761. if (Trap.hasErrorOccurred())
  5762. return false;
  5763. // Push default arguments if needed.
  5764. if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
  5765. for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
  5766. ParmVarDecl *P = Function->getParamDecl(i);
  5767. Expr *DefArg = P->hasUninstantiatedDefaultArg()
  5768. ? P->getUninstantiatedDefaultArg()
  5769. : P->getDefaultArg();
  5770. // This can only happen in code completion, i.e. when PartialOverloading
  5771. // is true.
  5772. if (!DefArg)
  5773. return false;
  5774. ExprResult R =
  5775. S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5776. S.Context, Function->getParamDecl(i)),
  5777. SourceLocation(), DefArg);
  5778. if (R.isInvalid())
  5779. return false;
  5780. ConvertedArgs.push_back(R.get());
  5781. }
  5782. if (Trap.hasErrorOccurred())
  5783. return false;
  5784. }
  5785. return true;
  5786. }
  5787. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5788. bool MissingImplicitThis) {
  5789. auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
  5790. if (EnableIfAttrs.begin() == EnableIfAttrs.end())
  5791. return nullptr;
  5792. SFINAETrap Trap(*this);
  5793. SmallVector<Expr *, 16> ConvertedArgs;
  5794. // FIXME: We should look into making enable_if late-parsed.
  5795. Expr *DiscardedThis;
  5796. if (!convertArgsForAvailabilityChecks(
  5797. *this, Function, /*ThisArg=*/nullptr, Args, Trap,
  5798. /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
  5799. return *EnableIfAttrs.begin();
  5800. for (auto *EIA : EnableIfAttrs) {
  5801. APValue Result;
  5802. // FIXME: This doesn't consider value-dependent cases, because doing so is
  5803. // very difficult. Ideally, we should handle them more gracefully.
  5804. if (EIA->getCond()->isValueDependent() ||
  5805. !EIA->getCond()->EvaluateWithSubstitution(
  5806. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
  5807. return EIA;
  5808. if (!Result.isInt() || !Result.getInt().getBoolValue())
  5809. return EIA;
  5810. }
  5811. return nullptr;
  5812. }
  5813. template <typename CheckFn>
  5814. static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
  5815. bool ArgDependent, SourceLocation Loc,
  5816. CheckFn &&IsSuccessful) {
  5817. SmallVector<const DiagnoseIfAttr *, 8> Attrs;
  5818. for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
  5819. if (ArgDependent == DIA->getArgDependent())
  5820. Attrs.push_back(DIA);
  5821. }
  5822. // Common case: No diagnose_if attributes, so we can quit early.
  5823. if (Attrs.empty())
  5824. return false;
  5825. auto WarningBegin = std::stable_partition(
  5826. Attrs.begin(), Attrs.end(),
  5827. [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
  5828. // Note that diagnose_if attributes are late-parsed, so they appear in the
  5829. // correct order (unlike enable_if attributes).
  5830. auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
  5831. IsSuccessful);
  5832. if (ErrAttr != WarningBegin) {
  5833. const DiagnoseIfAttr *DIA = *ErrAttr;
  5834. S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
  5835. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  5836. << DIA->getParent() << DIA->getCond()->getSourceRange();
  5837. return true;
  5838. }
  5839. for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
  5840. if (IsSuccessful(DIA)) {
  5841. S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
  5842. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  5843. << DIA->getParent() << DIA->getCond()->getSourceRange();
  5844. }
  5845. return false;
  5846. }
  5847. bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
  5848. const Expr *ThisArg,
  5849. ArrayRef<const Expr *> Args,
  5850. SourceLocation Loc) {
  5851. return diagnoseDiagnoseIfAttrsWith(
  5852. *this, Function, /*ArgDependent=*/true, Loc,
  5853. [&](const DiagnoseIfAttr *DIA) {
  5854. APValue Result;
  5855. // It's sane to use the same Args for any redecl of this function, since
  5856. // EvaluateWithSubstitution only cares about the position of each
  5857. // argument in the arg list, not the ParmVarDecl* it maps to.
  5858. if (!DIA->getCond()->EvaluateWithSubstitution(
  5859. Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
  5860. return false;
  5861. return Result.isInt() && Result.getInt().getBoolValue();
  5862. });
  5863. }
  5864. bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
  5865. SourceLocation Loc) {
  5866. return diagnoseDiagnoseIfAttrsWith(
  5867. *this, ND, /*ArgDependent=*/false, Loc,
  5868. [&](const DiagnoseIfAttr *DIA) {
  5869. bool Result;
  5870. return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
  5871. Result;
  5872. });
  5873. }
  5874. /// Add all of the function declarations in the given function set to
  5875. /// the overload candidate set.
  5876. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5877. ArrayRef<Expr *> Args,
  5878. OverloadCandidateSet &CandidateSet,
  5879. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5880. bool SuppressUserConversions,
  5881. bool PartialOverloading,
  5882. bool FirstArgumentIsBase) {
  5883. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5884. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5885. ArrayRef<Expr *> FunctionArgs = Args;
  5886. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  5887. FunctionDecl *FD =
  5888. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  5889. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
  5890. QualType ObjectType;
  5891. Expr::Classification ObjectClassification;
  5892. if (Args.size() > 0) {
  5893. if (Expr *E = Args[0]) {
  5894. // Use the explicit base to restrict the lookup:
  5895. ObjectType = E->getType();
  5896. // Pointers in the object arguments are implicitly dereferenced, so we
  5897. // always classify them as l-values.
  5898. if (!ObjectType.isNull() && ObjectType->isPointerType())
  5899. ObjectClassification = Expr::Classification::makeSimpleLValue();
  5900. else
  5901. ObjectClassification = E->Classify(Context);
  5902. } // .. else there is an implicit base.
  5903. FunctionArgs = Args.slice(1);
  5904. }
  5905. if (FunTmpl) {
  5906. AddMethodTemplateCandidate(
  5907. FunTmpl, F.getPair(),
  5908. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5909. ExplicitTemplateArgs, ObjectType, ObjectClassification,
  5910. FunctionArgs, CandidateSet, SuppressUserConversions,
  5911. PartialOverloading);
  5912. } else {
  5913. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5914. cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
  5915. ObjectClassification, FunctionArgs, CandidateSet,
  5916. SuppressUserConversions, PartialOverloading);
  5917. }
  5918. } else {
  5919. // This branch handles both standalone functions and static methods.
  5920. // Slice the first argument (which is the base) when we access
  5921. // static method as non-static.
  5922. if (Args.size() > 0 &&
  5923. (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
  5924. !isa<CXXConstructorDecl>(FD)))) {
  5925. assert(cast<CXXMethodDecl>(FD)->isStatic());
  5926. FunctionArgs = Args.slice(1);
  5927. }
  5928. if (FunTmpl) {
  5929. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  5930. ExplicitTemplateArgs, FunctionArgs,
  5931. CandidateSet, SuppressUserConversions,
  5932. PartialOverloading);
  5933. } else {
  5934. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
  5935. SuppressUserConversions, PartialOverloading);
  5936. }
  5937. }
  5938. }
  5939. }
  5940. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5941. /// method) as a method candidate to the given overload set.
  5942. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
  5943. Expr::Classification ObjectClassification,
  5944. ArrayRef<Expr *> Args,
  5945. OverloadCandidateSet &CandidateSet,
  5946. bool SuppressUserConversions,
  5947. OverloadCandidateParamOrder PO) {
  5948. NamedDecl *Decl = FoundDecl.getDecl();
  5949. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5950. if (isa<UsingShadowDecl>(Decl))
  5951. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5952. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5953. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5954. "Expected a member function template");
  5955. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5956. /*ExplicitArgs*/ nullptr, ObjectType,
  5957. ObjectClassification, Args, CandidateSet,
  5958. SuppressUserConversions, false, PO);
  5959. } else {
  5960. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5961. ObjectType, ObjectClassification, Args, CandidateSet,
  5962. SuppressUserConversions, false, None, PO);
  5963. }
  5964. }
  5965. /// AddMethodCandidate - Adds the given C++ member function to the set
  5966. /// of candidate functions, using the given function call arguments
  5967. /// and the object argument (@c Object). For example, in a call
  5968. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5969. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5970. /// allow user-defined conversions via constructors or conversion
  5971. /// operators.
  5972. void
  5973. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5974. CXXRecordDecl *ActingContext, QualType ObjectType,
  5975. Expr::Classification ObjectClassification,
  5976. ArrayRef<Expr *> Args,
  5977. OverloadCandidateSet &CandidateSet,
  5978. bool SuppressUserConversions,
  5979. bool PartialOverloading,
  5980. ConversionSequenceList EarlyConversions,
  5981. OverloadCandidateParamOrder PO) {
  5982. const FunctionProtoType *Proto
  5983. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5984. assert(Proto && "Methods without a prototype cannot be overloaded");
  5985. assert(!isa<CXXConstructorDecl>(Method) &&
  5986. "Use AddOverloadCandidate for constructors");
  5987. if (!CandidateSet.isNewCandidate(Method, PO))
  5988. return;
  5989. // C++11 [class.copy]p23: [DR1402]
  5990. // A defaulted move assignment operator that is defined as deleted is
  5991. // ignored by overload resolution.
  5992. if (Method->isDefaulted() && Method->isDeleted() &&
  5993. Method->isMoveAssignmentOperator())
  5994. return;
  5995. // Overload resolution is always an unevaluated context.
  5996. EnterExpressionEvaluationContext Unevaluated(
  5997. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5998. // Add this candidate
  5999. OverloadCandidate &Candidate =
  6000. CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
  6001. Candidate.FoundDecl = FoundDecl;
  6002. Candidate.Function = Method;
  6003. Candidate.RewriteKind =
  6004. CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
  6005. Candidate.IsSurrogate = false;
  6006. Candidate.IgnoreObjectArgument = false;
  6007. Candidate.ExplicitCallArguments = Args.size();
  6008. unsigned NumParams = Proto->getNumParams();
  6009. // (C++ 13.3.2p2): A candidate function having fewer than m
  6010. // parameters is viable only if it has an ellipsis in its parameter
  6011. // list (8.3.5).
  6012. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  6013. !Proto->isVariadic()) {
  6014. Candidate.Viable = false;
  6015. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6016. return;
  6017. }
  6018. // (C++ 13.3.2p2): A candidate function having more than m parameters
  6019. // is viable only if the (m+1)st parameter has a default argument
  6020. // (8.3.6). For the purposes of overload resolution, the
  6021. // parameter list is truncated on the right, so that there are
  6022. // exactly m parameters.
  6023. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  6024. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  6025. // Not enough arguments.
  6026. Candidate.Viable = false;
  6027. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6028. return;
  6029. }
  6030. Candidate.Viable = true;
  6031. if (Method->isStatic() || ObjectType.isNull())
  6032. // The implicit object argument is ignored.
  6033. Candidate.IgnoreObjectArgument = true;
  6034. else {
  6035. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
  6036. // Determine the implicit conversion sequence for the object
  6037. // parameter.
  6038. Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
  6039. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6040. Method, ActingContext);
  6041. if (Candidate.Conversions[ConvIdx].isBad()) {
  6042. Candidate.Viable = false;
  6043. Candidate.FailureKind = ovl_fail_bad_conversion;
  6044. return;
  6045. }
  6046. }
  6047. // (CUDA B.1): Check for invalid calls between targets.
  6048. if (getLangOpts().CUDA)
  6049. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  6050. if (!IsAllowedCUDACall(Caller, Method)) {
  6051. Candidate.Viable = false;
  6052. Candidate.FailureKind = ovl_fail_bad_target;
  6053. return;
  6054. }
  6055. // Determine the implicit conversion sequences for each of the
  6056. // arguments.
  6057. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  6058. unsigned ConvIdx =
  6059. PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
  6060. if (Candidate.Conversions[ConvIdx].isInitialized()) {
  6061. // We already formed a conversion sequence for this parameter during
  6062. // template argument deduction.
  6063. } else if (ArgIdx < NumParams) {
  6064. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6065. // exist for each argument an implicit conversion sequence
  6066. // (13.3.3.1) that converts that argument to the corresponding
  6067. // parameter of F.
  6068. QualType ParamType = Proto->getParamType(ArgIdx);
  6069. Candidate.Conversions[ConvIdx]
  6070. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6071. SuppressUserConversions,
  6072. /*InOverloadResolution=*/true,
  6073. /*AllowObjCWritebackConversion=*/
  6074. getLangOpts().ObjCAutoRefCount);
  6075. if (Candidate.Conversions[ConvIdx].isBad()) {
  6076. Candidate.Viable = false;
  6077. Candidate.FailureKind = ovl_fail_bad_conversion;
  6078. return;
  6079. }
  6080. } else {
  6081. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6082. // argument for which there is no corresponding parameter is
  6083. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  6084. Candidate.Conversions[ConvIdx].setEllipsis();
  6085. }
  6086. }
  6087. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  6088. Candidate.Viable = false;
  6089. Candidate.FailureKind = ovl_fail_enable_if;
  6090. Candidate.DeductionFailure.Data = FailedAttr;
  6091. return;
  6092. }
  6093. if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
  6094. !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
  6095. Candidate.Viable = false;
  6096. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6097. }
  6098. }
  6099. /// Add a C++ member function template as a candidate to the candidate
  6100. /// set, using template argument deduction to produce an appropriate member
  6101. /// function template specialization.
  6102. void Sema::AddMethodTemplateCandidate(
  6103. FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
  6104. CXXRecordDecl *ActingContext,
  6105. TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
  6106. Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
  6107. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6108. bool PartialOverloading, OverloadCandidateParamOrder PO) {
  6109. if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
  6110. return;
  6111. // C++ [over.match.funcs]p7:
  6112. // In each case where a candidate is a function template, candidate
  6113. // function template specializations are generated using template argument
  6114. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6115. // candidate functions in the usual way.113) A given name can refer to one
  6116. // or more function templates and also to a set of overloaded non-template
  6117. // functions. In such a case, the candidate functions generated from each
  6118. // function template are combined with the set of non-template candidate
  6119. // functions.
  6120. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6121. FunctionDecl *Specialization = nullptr;
  6122. ConversionSequenceList Conversions;
  6123. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6124. MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
  6125. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6126. return CheckNonDependentConversions(
  6127. MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
  6128. SuppressUserConversions, ActingContext, ObjectType,
  6129. ObjectClassification, PO);
  6130. })) {
  6131. OverloadCandidate &Candidate =
  6132. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6133. Candidate.FoundDecl = FoundDecl;
  6134. Candidate.Function = MethodTmpl->getTemplatedDecl();
  6135. Candidate.Viable = false;
  6136. Candidate.RewriteKind =
  6137. CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
  6138. Candidate.IsSurrogate = false;
  6139. Candidate.IgnoreObjectArgument =
  6140. cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
  6141. ObjectType.isNull();
  6142. Candidate.ExplicitCallArguments = Args.size();
  6143. if (Result == TDK_NonDependentConversionFailure)
  6144. Candidate.FailureKind = ovl_fail_bad_conversion;
  6145. else {
  6146. Candidate.FailureKind = ovl_fail_bad_deduction;
  6147. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6148. Info);
  6149. }
  6150. return;
  6151. }
  6152. // Add the function template specialization produced by template argument
  6153. // deduction as a candidate.
  6154. assert(Specialization && "Missing member function template specialization?");
  6155. assert(isa<CXXMethodDecl>(Specialization) &&
  6156. "Specialization is not a member function?");
  6157. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  6158. ActingContext, ObjectType, ObjectClassification, Args,
  6159. CandidateSet, SuppressUserConversions, PartialOverloading,
  6160. Conversions, PO);
  6161. }
  6162. /// Add a C++ function template specialization as a candidate
  6163. /// in the candidate set, using template argument deduction to produce
  6164. /// an appropriate function template specialization.
  6165. void Sema::AddTemplateOverloadCandidate(
  6166. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6167. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  6168. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6169. bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
  6170. OverloadCandidateParamOrder PO) {
  6171. if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
  6172. return;
  6173. // C++ [over.match.funcs]p7:
  6174. // In each case where a candidate is a function template, candidate
  6175. // function template specializations are generated using template argument
  6176. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6177. // candidate functions in the usual way.113) A given name can refer to one
  6178. // or more function templates and also to a set of overloaded non-template
  6179. // functions. In such a case, the candidate functions generated from each
  6180. // function template are combined with the set of non-template candidate
  6181. // functions.
  6182. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6183. FunctionDecl *Specialization = nullptr;
  6184. ConversionSequenceList Conversions;
  6185. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6186. FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
  6187. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6188. return CheckNonDependentConversions(
  6189. FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
  6190. SuppressUserConversions, nullptr, QualType(), {}, PO);
  6191. })) {
  6192. OverloadCandidate &Candidate =
  6193. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6194. Candidate.FoundDecl = FoundDecl;
  6195. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6196. Candidate.Viable = false;
  6197. Candidate.RewriteKind =
  6198. CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
  6199. Candidate.IsSurrogate = false;
  6200. Candidate.IsADLCandidate = IsADLCandidate;
  6201. // Ignore the object argument if there is one, since we don't have an object
  6202. // type.
  6203. Candidate.IgnoreObjectArgument =
  6204. isa<CXXMethodDecl>(Candidate.Function) &&
  6205. !isa<CXXConstructorDecl>(Candidate.Function);
  6206. Candidate.ExplicitCallArguments = Args.size();
  6207. if (Result == TDK_NonDependentConversionFailure)
  6208. Candidate.FailureKind = ovl_fail_bad_conversion;
  6209. else {
  6210. Candidate.FailureKind = ovl_fail_bad_deduction;
  6211. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6212. Info);
  6213. }
  6214. return;
  6215. }
  6216. // Add the function template specialization produced by template argument
  6217. // deduction as a candidate.
  6218. assert(Specialization && "Missing function template specialization?");
  6219. AddOverloadCandidate(
  6220. Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
  6221. PartialOverloading, AllowExplicit,
  6222. /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
  6223. }
  6224. /// Check that implicit conversion sequences can be formed for each argument
  6225. /// whose corresponding parameter has a non-dependent type, per DR1391's
  6226. /// [temp.deduct.call]p10.
  6227. bool Sema::CheckNonDependentConversions(
  6228. FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
  6229. ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
  6230. ConversionSequenceList &Conversions, bool SuppressUserConversions,
  6231. CXXRecordDecl *ActingContext, QualType ObjectType,
  6232. Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
  6233. // FIXME: The cases in which we allow explicit conversions for constructor
  6234. // arguments never consider calling a constructor template. It's not clear
  6235. // that is correct.
  6236. const bool AllowExplicit = false;
  6237. auto *FD = FunctionTemplate->getTemplatedDecl();
  6238. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  6239. bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
  6240. unsigned ThisConversions = HasThisConversion ? 1 : 0;
  6241. Conversions =
  6242. CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
  6243. // Overload resolution is always an unevaluated context.
  6244. EnterExpressionEvaluationContext Unevaluated(
  6245. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6246. // For a method call, check the 'this' conversion here too. DR1391 doesn't
  6247. // require that, but this check should never result in a hard error, and
  6248. // overload resolution is permitted to sidestep instantiations.
  6249. if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
  6250. !ObjectType.isNull()) {
  6251. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
  6252. Conversions[ConvIdx] = TryObjectArgumentInitialization(
  6253. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6254. Method, ActingContext);
  6255. if (Conversions[ConvIdx].isBad())
  6256. return true;
  6257. }
  6258. for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
  6259. ++I) {
  6260. QualType ParamType = ParamTypes[I];
  6261. if (!ParamType->isDependentType()) {
  6262. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
  6263. ? 0
  6264. : (ThisConversions + I);
  6265. Conversions[ConvIdx]
  6266. = TryCopyInitialization(*this, Args[I], ParamType,
  6267. SuppressUserConversions,
  6268. /*InOverloadResolution=*/true,
  6269. /*AllowObjCWritebackConversion=*/
  6270. getLangOpts().ObjCAutoRefCount,
  6271. AllowExplicit);
  6272. if (Conversions[ConvIdx].isBad())
  6273. return true;
  6274. }
  6275. }
  6276. return false;
  6277. }
  6278. /// Determine whether this is an allowable conversion from the result
  6279. /// of an explicit conversion operator to the expected type, per C++
  6280. /// [over.match.conv]p1 and [over.match.ref]p1.
  6281. ///
  6282. /// \param ConvType The return type of the conversion function.
  6283. ///
  6284. /// \param ToType The type we are converting to.
  6285. ///
  6286. /// \param AllowObjCPointerConversion Allow a conversion from one
  6287. /// Objective-C pointer to another.
  6288. ///
  6289. /// \returns true if the conversion is allowable, false otherwise.
  6290. static bool isAllowableExplicitConversion(Sema &S,
  6291. QualType ConvType, QualType ToType,
  6292. bool AllowObjCPointerConversion) {
  6293. QualType ToNonRefType = ToType.getNonReferenceType();
  6294. // Easy case: the types are the same.
  6295. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  6296. return true;
  6297. // Allow qualification conversions.
  6298. bool ObjCLifetimeConversion;
  6299. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  6300. ObjCLifetimeConversion))
  6301. return true;
  6302. // If we're not allowed to consider Objective-C pointer conversions,
  6303. // we're done.
  6304. if (!AllowObjCPointerConversion)
  6305. return false;
  6306. // Is this an Objective-C pointer conversion?
  6307. bool IncompatibleObjC = false;
  6308. QualType ConvertedType;
  6309. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  6310. IncompatibleObjC);
  6311. }
  6312. /// AddConversionCandidate - Add a C++ conversion function as a
  6313. /// candidate in the candidate set (C++ [over.match.conv],
  6314. /// C++ [over.match.copy]). From is the expression we're converting from,
  6315. /// and ToType is the type that we're eventually trying to convert to
  6316. /// (which may or may not be the same type as the type that the
  6317. /// conversion function produces).
  6318. void Sema::AddConversionCandidate(
  6319. CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
  6320. CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
  6321. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6322. bool AllowExplicit, bool AllowResultConversion) {
  6323. assert(!Conversion->getDescribedFunctionTemplate() &&
  6324. "Conversion function templates use AddTemplateConversionCandidate");
  6325. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  6326. if (!CandidateSet.isNewCandidate(Conversion))
  6327. return;
  6328. // If the conversion function has an undeduced return type, trigger its
  6329. // deduction now.
  6330. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  6331. if (DeduceReturnType(Conversion, From->getExprLoc()))
  6332. return;
  6333. ConvType = Conversion->getConversionType().getNonReferenceType();
  6334. }
  6335. // If we don't allow any conversion of the result type, ignore conversion
  6336. // functions that don't convert to exactly (possibly cv-qualified) T.
  6337. if (!AllowResultConversion &&
  6338. !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
  6339. return;
  6340. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  6341. // operator is only a candidate if its return type is the target type or
  6342. // can be converted to the target type with a qualification conversion.
  6343. if (Conversion->isExplicit() &&
  6344. !isAllowableExplicitConversion(*this, ConvType, ToType,
  6345. AllowObjCConversionOnExplicit))
  6346. return;
  6347. // Overload resolution is always an unevaluated context.
  6348. EnterExpressionEvaluationContext Unevaluated(
  6349. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6350. // Add this candidate
  6351. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  6352. Candidate.FoundDecl = FoundDecl;
  6353. Candidate.Function = Conversion;
  6354. Candidate.IsSurrogate = false;
  6355. Candidate.IgnoreObjectArgument = false;
  6356. Candidate.FinalConversion.setAsIdentityConversion();
  6357. Candidate.FinalConversion.setFromType(ConvType);
  6358. Candidate.FinalConversion.setAllToTypes(ToType);
  6359. Candidate.Viable = true;
  6360. Candidate.ExplicitCallArguments = 1;
  6361. // C++ [over.match.funcs]p4:
  6362. // For conversion functions, the function is considered to be a member of
  6363. // the class of the implicit implied object argument for the purpose of
  6364. // defining the type of the implicit object parameter.
  6365. //
  6366. // Determine the implicit conversion sequence for the implicit
  6367. // object parameter.
  6368. QualType ImplicitParamType = From->getType();
  6369. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  6370. ImplicitParamType = FromPtrType->getPointeeType();
  6371. CXXRecordDecl *ConversionContext
  6372. = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
  6373. Candidate.Conversions[0] = TryObjectArgumentInitialization(
  6374. *this, CandidateSet.getLocation(), From->getType(),
  6375. From->Classify(Context), Conversion, ConversionContext);
  6376. if (Candidate.Conversions[0].isBad()) {
  6377. Candidate.Viable = false;
  6378. Candidate.FailureKind = ovl_fail_bad_conversion;
  6379. return;
  6380. }
  6381. // We won't go through a user-defined type conversion function to convert a
  6382. // derived to base as such conversions are given Conversion Rank. They only
  6383. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  6384. QualType FromCanon
  6385. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  6386. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  6387. if (FromCanon == ToCanon ||
  6388. IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
  6389. Candidate.Viable = false;
  6390. Candidate.FailureKind = ovl_fail_trivial_conversion;
  6391. return;
  6392. }
  6393. // To determine what the conversion from the result of calling the
  6394. // conversion function to the type we're eventually trying to
  6395. // convert to (ToType), we need to synthesize a call to the
  6396. // conversion function and attempt copy initialization from it. This
  6397. // makes sure that we get the right semantics with respect to
  6398. // lvalues/rvalues and the type. Fortunately, we can allocate this
  6399. // call on the stack and we don't need its arguments to be
  6400. // well-formed.
  6401. DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
  6402. VK_LValue, From->getBeginLoc());
  6403. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  6404. Context.getPointerType(Conversion->getType()),
  6405. CK_FunctionToPointerDecay,
  6406. &ConversionRef, VK_RValue);
  6407. QualType ConversionType = Conversion->getConversionType();
  6408. if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
  6409. Candidate.Viable = false;
  6410. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6411. return;
  6412. }
  6413. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  6414. // Note that it is safe to allocate CallExpr on the stack here because
  6415. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  6416. // allocator).
  6417. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  6418. alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
  6419. CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
  6420. Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
  6421. ImplicitConversionSequence ICS =
  6422. TryCopyInitialization(*this, TheTemporaryCall, ToType,
  6423. /*SuppressUserConversions=*/true,
  6424. /*InOverloadResolution=*/false,
  6425. /*AllowObjCWritebackConversion=*/false);
  6426. switch (ICS.getKind()) {
  6427. case ImplicitConversionSequence::StandardConversion:
  6428. Candidate.FinalConversion = ICS.Standard;
  6429. // C++ [over.ics.user]p3:
  6430. // If the user-defined conversion is specified by a specialization of a
  6431. // conversion function template, the second standard conversion sequence
  6432. // shall have exact match rank.
  6433. if (Conversion->getPrimaryTemplate() &&
  6434. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  6435. Candidate.Viable = false;
  6436. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  6437. return;
  6438. }
  6439. // C++0x [dcl.init.ref]p5:
  6440. // In the second case, if the reference is an rvalue reference and
  6441. // the second standard conversion sequence of the user-defined
  6442. // conversion sequence includes an lvalue-to-rvalue conversion, the
  6443. // program is ill-formed.
  6444. if (ToType->isRValueReferenceType() &&
  6445. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  6446. Candidate.Viable = false;
  6447. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6448. return;
  6449. }
  6450. break;
  6451. case ImplicitConversionSequence::BadConversion:
  6452. Candidate.Viable = false;
  6453. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6454. return;
  6455. default:
  6456. llvm_unreachable(
  6457. "Can only end up with a standard conversion sequence or failure");
  6458. }
  6459. if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
  6460. ExplicitSpecKind::ResolvedFalse) {
  6461. Candidate.Viable = false;
  6462. Candidate.FailureKind = ovl_fail_explicit_resolved;
  6463. return;
  6464. }
  6465. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6466. Candidate.Viable = false;
  6467. Candidate.FailureKind = ovl_fail_enable_if;
  6468. Candidate.DeductionFailure.Data = FailedAttr;
  6469. return;
  6470. }
  6471. if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
  6472. !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
  6473. Candidate.Viable = false;
  6474. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6475. }
  6476. }
  6477. /// Adds a conversion function template specialization
  6478. /// candidate to the overload set, using template argument deduction
  6479. /// to deduce the template arguments of the conversion function
  6480. /// template from the type that we are converting to (C++
  6481. /// [temp.deduct.conv]).
  6482. void Sema::AddTemplateConversionCandidate(
  6483. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6484. CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
  6485. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6486. bool AllowExplicit, bool AllowResultConversion) {
  6487. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  6488. "Only conversion function templates permitted here");
  6489. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  6490. return;
  6491. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6492. CXXConversionDecl *Specialization = nullptr;
  6493. if (TemplateDeductionResult Result
  6494. = DeduceTemplateArguments(FunctionTemplate, ToType,
  6495. Specialization, Info)) {
  6496. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  6497. Candidate.FoundDecl = FoundDecl;
  6498. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6499. Candidate.Viable = false;
  6500. Candidate.FailureKind = ovl_fail_bad_deduction;
  6501. Candidate.IsSurrogate = false;
  6502. Candidate.IgnoreObjectArgument = false;
  6503. Candidate.ExplicitCallArguments = 1;
  6504. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6505. Info);
  6506. return;
  6507. }
  6508. // Add the conversion function template specialization produced by
  6509. // template argument deduction as a candidate.
  6510. assert(Specialization && "Missing function template specialization?");
  6511. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  6512. CandidateSet, AllowObjCConversionOnExplicit,
  6513. AllowExplicit, AllowResultConversion);
  6514. }
  6515. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  6516. /// converts the given @c Object to a function pointer via the
  6517. /// conversion function @c Conversion, and then attempts to call it
  6518. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  6519. /// the type of function that we'll eventually be calling.
  6520. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  6521. DeclAccessPair FoundDecl,
  6522. CXXRecordDecl *ActingContext,
  6523. const FunctionProtoType *Proto,
  6524. Expr *Object,
  6525. ArrayRef<Expr *> Args,
  6526. OverloadCandidateSet& CandidateSet) {
  6527. if (!CandidateSet.isNewCandidate(Conversion))
  6528. return;
  6529. // Overload resolution is always an unevaluated context.
  6530. EnterExpressionEvaluationContext Unevaluated(
  6531. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6532. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  6533. Candidate.FoundDecl = FoundDecl;
  6534. Candidate.Function = nullptr;
  6535. Candidate.Surrogate = Conversion;
  6536. Candidate.Viable = true;
  6537. Candidate.IsSurrogate = true;
  6538. Candidate.IgnoreObjectArgument = false;
  6539. Candidate.ExplicitCallArguments = Args.size();
  6540. // Determine the implicit conversion sequence for the implicit
  6541. // object parameter.
  6542. ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
  6543. *this, CandidateSet.getLocation(), Object->getType(),
  6544. Object->Classify(Context), Conversion, ActingContext);
  6545. if (ObjectInit.isBad()) {
  6546. Candidate.Viable = false;
  6547. Candidate.FailureKind = ovl_fail_bad_conversion;
  6548. Candidate.Conversions[0] = ObjectInit;
  6549. return;
  6550. }
  6551. // The first conversion is actually a user-defined conversion whose
  6552. // first conversion is ObjectInit's standard conversion (which is
  6553. // effectively a reference binding). Record it as such.
  6554. Candidate.Conversions[0].setUserDefined();
  6555. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  6556. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  6557. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  6558. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  6559. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  6560. Candidate.Conversions[0].UserDefined.After
  6561. = Candidate.Conversions[0].UserDefined.Before;
  6562. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  6563. // Find the
  6564. unsigned NumParams = Proto->getNumParams();
  6565. // (C++ 13.3.2p2): A candidate function having fewer than m
  6566. // parameters is viable only if it has an ellipsis in its parameter
  6567. // list (8.3.5).
  6568. if (Args.size() > NumParams && !Proto->isVariadic()) {
  6569. Candidate.Viable = false;
  6570. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6571. return;
  6572. }
  6573. // Function types don't have any default arguments, so just check if
  6574. // we have enough arguments.
  6575. if (Args.size() < NumParams) {
  6576. // Not enough arguments.
  6577. Candidate.Viable = false;
  6578. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6579. return;
  6580. }
  6581. // Determine the implicit conversion sequences for each of the
  6582. // arguments.
  6583. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6584. if (ArgIdx < NumParams) {
  6585. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6586. // exist for each argument an implicit conversion sequence
  6587. // (13.3.3.1) that converts that argument to the corresponding
  6588. // parameter of F.
  6589. QualType ParamType = Proto->getParamType(ArgIdx);
  6590. Candidate.Conversions[ArgIdx + 1]
  6591. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6592. /*SuppressUserConversions=*/false,
  6593. /*InOverloadResolution=*/false,
  6594. /*AllowObjCWritebackConversion=*/
  6595. getLangOpts().ObjCAutoRefCount);
  6596. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6597. Candidate.Viable = false;
  6598. Candidate.FailureKind = ovl_fail_bad_conversion;
  6599. return;
  6600. }
  6601. } else {
  6602. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6603. // argument for which there is no corresponding parameter is
  6604. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6605. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6606. }
  6607. }
  6608. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6609. Candidate.Viable = false;
  6610. Candidate.FailureKind = ovl_fail_enable_if;
  6611. Candidate.DeductionFailure.Data = FailedAttr;
  6612. return;
  6613. }
  6614. }
  6615. /// Add all of the non-member operator function declarations in the given
  6616. /// function set to the overload candidate set.
  6617. void Sema::AddNonMemberOperatorCandidates(
  6618. const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
  6619. OverloadCandidateSet &CandidateSet,
  6620. TemplateArgumentListInfo *ExplicitTemplateArgs) {
  6621. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  6622. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  6623. ArrayRef<Expr *> FunctionArgs = Args;
  6624. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  6625. FunctionDecl *FD =
  6626. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  6627. // Don't consider rewritten functions if we're not rewriting.
  6628. if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
  6629. continue;
  6630. assert(!isa<CXXMethodDecl>(FD) &&
  6631. "unqualified operator lookup found a member function");
  6632. if (FunTmpl) {
  6633. AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
  6634. FunctionArgs, CandidateSet);
  6635. if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
  6636. AddTemplateOverloadCandidate(
  6637. FunTmpl, F.getPair(), ExplicitTemplateArgs,
  6638. {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
  6639. true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
  6640. } else {
  6641. if (ExplicitTemplateArgs)
  6642. continue;
  6643. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
  6644. if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
  6645. AddOverloadCandidate(FD, F.getPair(),
  6646. {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
  6647. false, false, true, false, ADLCallKind::NotADL,
  6648. None, OverloadCandidateParamOrder::Reversed);
  6649. }
  6650. }
  6651. }
  6652. /// Add overload candidates for overloaded operators that are
  6653. /// member functions.
  6654. ///
  6655. /// Add the overloaded operator candidates that are member functions
  6656. /// for the operator Op that was used in an operator expression such
  6657. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6658. /// CandidateSet will store the added overload candidates. (C++
  6659. /// [over.match.oper]).
  6660. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6661. SourceLocation OpLoc,
  6662. ArrayRef<Expr *> Args,
  6663. OverloadCandidateSet &CandidateSet,
  6664. OverloadCandidateParamOrder PO) {
  6665. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6666. // C++ [over.match.oper]p3:
  6667. // For a unary operator @ with an operand of a type whose
  6668. // cv-unqualified version is T1, and for a binary operator @ with
  6669. // a left operand of a type whose cv-unqualified version is T1 and
  6670. // a right operand of a type whose cv-unqualified version is T2,
  6671. // three sets of candidate functions, designated member
  6672. // candidates, non-member candidates and built-in candidates, are
  6673. // constructed as follows:
  6674. QualType T1 = Args[0]->getType();
  6675. // -- If T1 is a complete class type or a class currently being
  6676. // defined, the set of member candidates is the result of the
  6677. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6678. // the set of member candidates is empty.
  6679. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6680. // Complete the type if it can be completed.
  6681. if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
  6682. return;
  6683. // If the type is neither complete nor being defined, bail out now.
  6684. if (!T1Rec->getDecl()->getDefinition())
  6685. return;
  6686. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6687. LookupQualifiedName(Operators, T1Rec->getDecl());
  6688. Operators.suppressDiagnostics();
  6689. for (LookupResult::iterator Oper = Operators.begin(),
  6690. OperEnd = Operators.end();
  6691. Oper != OperEnd;
  6692. ++Oper)
  6693. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6694. Args[0]->Classify(Context), Args.slice(1),
  6695. CandidateSet, /*SuppressUserConversion=*/false, PO);
  6696. }
  6697. }
  6698. /// AddBuiltinCandidate - Add a candidate for a built-in
  6699. /// operator. ResultTy and ParamTys are the result and parameter types
  6700. /// of the built-in candidate, respectively. Args and NumArgs are the
  6701. /// arguments being passed to the candidate. IsAssignmentOperator
  6702. /// should be true when this built-in candidate is an assignment
  6703. /// operator. NumContextualBoolArguments is the number of arguments
  6704. /// (at the beginning of the argument list) that will be contextually
  6705. /// converted to bool.
  6706. void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
  6707. OverloadCandidateSet& CandidateSet,
  6708. bool IsAssignmentOperator,
  6709. unsigned NumContextualBoolArguments) {
  6710. // Overload resolution is always an unevaluated context.
  6711. EnterExpressionEvaluationContext Unevaluated(
  6712. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6713. // Add this candidate
  6714. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6715. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6716. Candidate.Function = nullptr;
  6717. Candidate.IsSurrogate = false;
  6718. Candidate.IgnoreObjectArgument = false;
  6719. std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
  6720. // Determine the implicit conversion sequences for each of the
  6721. // arguments.
  6722. Candidate.Viable = true;
  6723. Candidate.ExplicitCallArguments = Args.size();
  6724. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6725. // C++ [over.match.oper]p4:
  6726. // For the built-in assignment operators, conversions of the
  6727. // left operand are restricted as follows:
  6728. // -- no temporaries are introduced to hold the left operand, and
  6729. // -- no user-defined conversions are applied to the left
  6730. // operand to achieve a type match with the left-most
  6731. // parameter of a built-in candidate.
  6732. //
  6733. // We block these conversions by turning off user-defined
  6734. // conversions, since that is the only way that initialization of
  6735. // a reference to a non-class type can occur from something that
  6736. // is not of the same type.
  6737. if (ArgIdx < NumContextualBoolArguments) {
  6738. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6739. "Contextual conversion to bool requires bool type");
  6740. Candidate.Conversions[ArgIdx]
  6741. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6742. } else {
  6743. Candidate.Conversions[ArgIdx]
  6744. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6745. ArgIdx == 0 && IsAssignmentOperator,
  6746. /*InOverloadResolution=*/false,
  6747. /*AllowObjCWritebackConversion=*/
  6748. getLangOpts().ObjCAutoRefCount);
  6749. }
  6750. if (Candidate.Conversions[ArgIdx].isBad()) {
  6751. Candidate.Viable = false;
  6752. Candidate.FailureKind = ovl_fail_bad_conversion;
  6753. break;
  6754. }
  6755. }
  6756. }
  6757. namespace {
  6758. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6759. /// candidate operator functions for built-in operators (C++
  6760. /// [over.built]). The types are separated into pointer types and
  6761. /// enumeration types.
  6762. class BuiltinCandidateTypeSet {
  6763. /// TypeSet - A set of types.
  6764. typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
  6765. llvm::SmallPtrSet<QualType, 8>> TypeSet;
  6766. /// PointerTypes - The set of pointer types that will be used in the
  6767. /// built-in candidates.
  6768. TypeSet PointerTypes;
  6769. /// MemberPointerTypes - The set of member pointer types that will be
  6770. /// used in the built-in candidates.
  6771. TypeSet MemberPointerTypes;
  6772. /// EnumerationTypes - The set of enumeration types that will be
  6773. /// used in the built-in candidates.
  6774. TypeSet EnumerationTypes;
  6775. /// The set of vector types that will be used in the built-in
  6776. /// candidates.
  6777. TypeSet VectorTypes;
  6778. /// A flag indicating non-record types are viable candidates
  6779. bool HasNonRecordTypes;
  6780. /// A flag indicating whether either arithmetic or enumeration types
  6781. /// were present in the candidate set.
  6782. bool HasArithmeticOrEnumeralTypes;
  6783. /// A flag indicating whether the nullptr type was present in the
  6784. /// candidate set.
  6785. bool HasNullPtrType;
  6786. /// Sema - The semantic analysis instance where we are building the
  6787. /// candidate type set.
  6788. Sema &SemaRef;
  6789. /// Context - The AST context in which we will build the type sets.
  6790. ASTContext &Context;
  6791. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6792. const Qualifiers &VisibleQuals);
  6793. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6794. public:
  6795. /// iterator - Iterates through the types that are part of the set.
  6796. typedef TypeSet::iterator iterator;
  6797. BuiltinCandidateTypeSet(Sema &SemaRef)
  6798. : HasNonRecordTypes(false),
  6799. HasArithmeticOrEnumeralTypes(false),
  6800. HasNullPtrType(false),
  6801. SemaRef(SemaRef),
  6802. Context(SemaRef.Context) { }
  6803. void AddTypesConvertedFrom(QualType Ty,
  6804. SourceLocation Loc,
  6805. bool AllowUserConversions,
  6806. bool AllowExplicitConversions,
  6807. const Qualifiers &VisibleTypeConversionsQuals);
  6808. /// pointer_begin - First pointer type found;
  6809. iterator pointer_begin() { return PointerTypes.begin(); }
  6810. /// pointer_end - Past the last pointer type found;
  6811. iterator pointer_end() { return PointerTypes.end(); }
  6812. /// member_pointer_begin - First member pointer type found;
  6813. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6814. /// member_pointer_end - Past the last member pointer type found;
  6815. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6816. /// enumeration_begin - First enumeration type found;
  6817. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6818. /// enumeration_end - Past the last enumeration type found;
  6819. iterator enumeration_end() { return EnumerationTypes.end(); }
  6820. iterator vector_begin() { return VectorTypes.begin(); }
  6821. iterator vector_end() { return VectorTypes.end(); }
  6822. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6823. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6824. bool hasNullPtrType() const { return HasNullPtrType; }
  6825. };
  6826. } // end anonymous namespace
  6827. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6828. /// the set of pointer types along with any more-qualified variants of
  6829. /// that type. For example, if @p Ty is "int const *", this routine
  6830. /// will add "int const *", "int const volatile *", "int const
  6831. /// restrict *", and "int const volatile restrict *" to the set of
  6832. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6833. /// false otherwise.
  6834. ///
  6835. /// FIXME: what to do about extended qualifiers?
  6836. bool
  6837. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6838. const Qualifiers &VisibleQuals) {
  6839. // Insert this type.
  6840. if (!PointerTypes.insert(Ty))
  6841. return false;
  6842. QualType PointeeTy;
  6843. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6844. bool buildObjCPtr = false;
  6845. if (!PointerTy) {
  6846. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6847. PointeeTy = PTy->getPointeeType();
  6848. buildObjCPtr = true;
  6849. } else {
  6850. PointeeTy = PointerTy->getPointeeType();
  6851. }
  6852. // Don't add qualified variants of arrays. For one, they're not allowed
  6853. // (the qualifier would sink to the element type), and for another, the
  6854. // only overload situation where it matters is subscript or pointer +- int,
  6855. // and those shouldn't have qualifier variants anyway.
  6856. if (PointeeTy->isArrayType())
  6857. return true;
  6858. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6859. bool hasVolatile = VisibleQuals.hasVolatile();
  6860. bool hasRestrict = VisibleQuals.hasRestrict();
  6861. // Iterate through all strict supersets of BaseCVR.
  6862. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6863. if ((CVR | BaseCVR) != CVR) continue;
  6864. // Skip over volatile if no volatile found anywhere in the types.
  6865. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6866. // Skip over restrict if no restrict found anywhere in the types, or if
  6867. // the type cannot be restrict-qualified.
  6868. if ((CVR & Qualifiers::Restrict) &&
  6869. (!hasRestrict ||
  6870. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6871. continue;
  6872. // Build qualified pointee type.
  6873. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6874. // Build qualified pointer type.
  6875. QualType QPointerTy;
  6876. if (!buildObjCPtr)
  6877. QPointerTy = Context.getPointerType(QPointeeTy);
  6878. else
  6879. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6880. // Insert qualified pointer type.
  6881. PointerTypes.insert(QPointerTy);
  6882. }
  6883. return true;
  6884. }
  6885. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6886. /// to the set of pointer types along with any more-qualified variants of
  6887. /// that type. For example, if @p Ty is "int const *", this routine
  6888. /// will add "int const *", "int const volatile *", "int const
  6889. /// restrict *", and "int const volatile restrict *" to the set of
  6890. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6891. /// false otherwise.
  6892. ///
  6893. /// FIXME: what to do about extended qualifiers?
  6894. bool
  6895. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6896. QualType Ty) {
  6897. // Insert this type.
  6898. if (!MemberPointerTypes.insert(Ty))
  6899. return false;
  6900. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6901. assert(PointerTy && "type was not a member pointer type!");
  6902. QualType PointeeTy = PointerTy->getPointeeType();
  6903. // Don't add qualified variants of arrays. For one, they're not allowed
  6904. // (the qualifier would sink to the element type), and for another, the
  6905. // only overload situation where it matters is subscript or pointer +- int,
  6906. // and those shouldn't have qualifier variants anyway.
  6907. if (PointeeTy->isArrayType())
  6908. return true;
  6909. const Type *ClassTy = PointerTy->getClass();
  6910. // Iterate through all strict supersets of the pointee type's CVR
  6911. // qualifiers.
  6912. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6913. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6914. if ((CVR | BaseCVR) != CVR) continue;
  6915. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6916. MemberPointerTypes.insert(
  6917. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6918. }
  6919. return true;
  6920. }
  6921. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6922. /// Ty can be implicit converted to the given set of @p Types. We're
  6923. /// primarily interested in pointer types and enumeration types. We also
  6924. /// take member pointer types, for the conditional operator.
  6925. /// AllowUserConversions is true if we should look at the conversion
  6926. /// functions of a class type, and AllowExplicitConversions if we
  6927. /// should also include the explicit conversion functions of a class
  6928. /// type.
  6929. void
  6930. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6931. SourceLocation Loc,
  6932. bool AllowUserConversions,
  6933. bool AllowExplicitConversions,
  6934. const Qualifiers &VisibleQuals) {
  6935. // Only deal with canonical types.
  6936. Ty = Context.getCanonicalType(Ty);
  6937. // Look through reference types; they aren't part of the type of an
  6938. // expression for the purposes of conversions.
  6939. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6940. Ty = RefTy->getPointeeType();
  6941. // If we're dealing with an array type, decay to the pointer.
  6942. if (Ty->isArrayType())
  6943. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6944. // Otherwise, we don't care about qualifiers on the type.
  6945. Ty = Ty.getLocalUnqualifiedType();
  6946. // Flag if we ever add a non-record type.
  6947. const RecordType *TyRec = Ty->getAs<RecordType>();
  6948. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6949. // Flag if we encounter an arithmetic type.
  6950. HasArithmeticOrEnumeralTypes =
  6951. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6952. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6953. PointerTypes.insert(Ty);
  6954. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6955. // Insert our type, and its more-qualified variants, into the set
  6956. // of types.
  6957. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6958. return;
  6959. } else if (Ty->isMemberPointerType()) {
  6960. // Member pointers are far easier, since the pointee can't be converted.
  6961. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6962. return;
  6963. } else if (Ty->isEnumeralType()) {
  6964. HasArithmeticOrEnumeralTypes = true;
  6965. EnumerationTypes.insert(Ty);
  6966. } else if (Ty->isVectorType()) {
  6967. // We treat vector types as arithmetic types in many contexts as an
  6968. // extension.
  6969. HasArithmeticOrEnumeralTypes = true;
  6970. VectorTypes.insert(Ty);
  6971. } else if (Ty->isNullPtrType()) {
  6972. HasNullPtrType = true;
  6973. } else if (AllowUserConversions && TyRec) {
  6974. // No conversion functions in incomplete types.
  6975. if (!SemaRef.isCompleteType(Loc, Ty))
  6976. return;
  6977. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6978. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6979. if (isa<UsingShadowDecl>(D))
  6980. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6981. // Skip conversion function templates; they don't tell us anything
  6982. // about which builtin types we can convert to.
  6983. if (isa<FunctionTemplateDecl>(D))
  6984. continue;
  6985. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6986. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6987. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6988. VisibleQuals);
  6989. }
  6990. }
  6991. }
  6992. }
  6993. /// Helper function for adjusting address spaces for the pointer or reference
  6994. /// operands of builtin operators depending on the argument.
  6995. static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
  6996. Expr *Arg) {
  6997. return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
  6998. }
  6999. /// Helper function for AddBuiltinOperatorCandidates() that adds
  7000. /// the volatile- and non-volatile-qualified assignment operators for the
  7001. /// given type to the candidate set.
  7002. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  7003. QualType T,
  7004. ArrayRef<Expr *> Args,
  7005. OverloadCandidateSet &CandidateSet) {
  7006. QualType ParamTypes[2];
  7007. // T& operator=(T&, T)
  7008. ParamTypes[0] = S.Context.getLValueReferenceType(
  7009. AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
  7010. ParamTypes[1] = T;
  7011. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7012. /*IsAssignmentOperator=*/true);
  7013. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  7014. // volatile T& operator=(volatile T&, T)
  7015. ParamTypes[0] = S.Context.getLValueReferenceType(
  7016. AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
  7017. Args[0]));
  7018. ParamTypes[1] = T;
  7019. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7020. /*IsAssignmentOperator=*/true);
  7021. }
  7022. }
  7023. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  7024. /// if any, found in visible type conversion functions found in ArgExpr's type.
  7025. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  7026. Qualifiers VRQuals;
  7027. const RecordType *TyRec;
  7028. if (const MemberPointerType *RHSMPType =
  7029. ArgExpr->getType()->getAs<MemberPointerType>())
  7030. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  7031. else
  7032. TyRec = ArgExpr->getType()->getAs<RecordType>();
  7033. if (!TyRec) {
  7034. // Just to be safe, assume the worst case.
  7035. VRQuals.addVolatile();
  7036. VRQuals.addRestrict();
  7037. return VRQuals;
  7038. }
  7039. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  7040. if (!ClassDecl->hasDefinition())
  7041. return VRQuals;
  7042. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  7043. if (isa<UsingShadowDecl>(D))
  7044. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  7045. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  7046. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  7047. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  7048. CanTy = ResTypeRef->getPointeeType();
  7049. // Need to go down the pointer/mempointer chain and add qualifiers
  7050. // as see them.
  7051. bool done = false;
  7052. while (!done) {
  7053. if (CanTy.isRestrictQualified())
  7054. VRQuals.addRestrict();
  7055. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  7056. CanTy = ResTypePtr->getPointeeType();
  7057. else if (const MemberPointerType *ResTypeMPtr =
  7058. CanTy->getAs<MemberPointerType>())
  7059. CanTy = ResTypeMPtr->getPointeeType();
  7060. else
  7061. done = true;
  7062. if (CanTy.isVolatileQualified())
  7063. VRQuals.addVolatile();
  7064. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  7065. return VRQuals;
  7066. }
  7067. }
  7068. }
  7069. return VRQuals;
  7070. }
  7071. namespace {
  7072. /// Helper class to manage the addition of builtin operator overload
  7073. /// candidates. It provides shared state and utility methods used throughout
  7074. /// the process, as well as a helper method to add each group of builtin
  7075. /// operator overloads from the standard to a candidate set.
  7076. class BuiltinOperatorOverloadBuilder {
  7077. // Common instance state available to all overload candidate addition methods.
  7078. Sema &S;
  7079. ArrayRef<Expr *> Args;
  7080. Qualifiers VisibleTypeConversionsQuals;
  7081. bool HasArithmeticOrEnumeralCandidateType;
  7082. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  7083. OverloadCandidateSet &CandidateSet;
  7084. static constexpr int ArithmeticTypesCap = 24;
  7085. SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
  7086. // Define some indices used to iterate over the arithmetic types in
  7087. // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
  7088. // types are that preserved by promotion (C++ [over.built]p2).
  7089. unsigned FirstIntegralType,
  7090. LastIntegralType;
  7091. unsigned FirstPromotedIntegralType,
  7092. LastPromotedIntegralType;
  7093. unsigned FirstPromotedArithmeticType,
  7094. LastPromotedArithmeticType;
  7095. unsigned NumArithmeticTypes;
  7096. void InitArithmeticTypes() {
  7097. // Start of promoted types.
  7098. FirstPromotedArithmeticType = 0;
  7099. ArithmeticTypes.push_back(S.Context.FloatTy);
  7100. ArithmeticTypes.push_back(S.Context.DoubleTy);
  7101. ArithmeticTypes.push_back(S.Context.LongDoubleTy);
  7102. if (S.Context.getTargetInfo().hasFloat128Type())
  7103. ArithmeticTypes.push_back(S.Context.Float128Ty);
  7104. // Start of integral types.
  7105. FirstIntegralType = ArithmeticTypes.size();
  7106. FirstPromotedIntegralType = ArithmeticTypes.size();
  7107. ArithmeticTypes.push_back(S.Context.IntTy);
  7108. ArithmeticTypes.push_back(S.Context.LongTy);
  7109. ArithmeticTypes.push_back(S.Context.LongLongTy);
  7110. if (S.Context.getTargetInfo().hasInt128Type())
  7111. ArithmeticTypes.push_back(S.Context.Int128Ty);
  7112. ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
  7113. ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
  7114. ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
  7115. if (S.Context.getTargetInfo().hasInt128Type())
  7116. ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
  7117. LastPromotedIntegralType = ArithmeticTypes.size();
  7118. LastPromotedArithmeticType = ArithmeticTypes.size();
  7119. // End of promoted types.
  7120. ArithmeticTypes.push_back(S.Context.BoolTy);
  7121. ArithmeticTypes.push_back(S.Context.CharTy);
  7122. ArithmeticTypes.push_back(S.Context.WCharTy);
  7123. if (S.Context.getLangOpts().Char8)
  7124. ArithmeticTypes.push_back(S.Context.Char8Ty);
  7125. ArithmeticTypes.push_back(S.Context.Char16Ty);
  7126. ArithmeticTypes.push_back(S.Context.Char32Ty);
  7127. ArithmeticTypes.push_back(S.Context.SignedCharTy);
  7128. ArithmeticTypes.push_back(S.Context.ShortTy);
  7129. ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
  7130. ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
  7131. LastIntegralType = ArithmeticTypes.size();
  7132. NumArithmeticTypes = ArithmeticTypes.size();
  7133. // End of integral types.
  7134. // FIXME: What about complex? What about half?
  7135. assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
  7136. "Enough inline storage for all arithmetic types.");
  7137. }
  7138. /// Helper method to factor out the common pattern of adding overloads
  7139. /// for '++' and '--' builtin operators.
  7140. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  7141. bool HasVolatile,
  7142. bool HasRestrict) {
  7143. QualType ParamTypes[2] = {
  7144. S.Context.getLValueReferenceType(CandidateTy),
  7145. S.Context.IntTy
  7146. };
  7147. // Non-volatile version.
  7148. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7149. // Use a heuristic to reduce number of builtin candidates in the set:
  7150. // add volatile version only if there are conversions to a volatile type.
  7151. if (HasVolatile) {
  7152. ParamTypes[0] =
  7153. S.Context.getLValueReferenceType(
  7154. S.Context.getVolatileType(CandidateTy));
  7155. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7156. }
  7157. // Add restrict version only if there are conversions to a restrict type
  7158. // and our candidate type is a non-restrict-qualified pointer.
  7159. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  7160. !CandidateTy.isRestrictQualified()) {
  7161. ParamTypes[0]
  7162. = S.Context.getLValueReferenceType(
  7163. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  7164. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7165. if (HasVolatile) {
  7166. ParamTypes[0]
  7167. = S.Context.getLValueReferenceType(
  7168. S.Context.getCVRQualifiedType(CandidateTy,
  7169. (Qualifiers::Volatile |
  7170. Qualifiers::Restrict)));
  7171. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7172. }
  7173. }
  7174. }
  7175. public:
  7176. BuiltinOperatorOverloadBuilder(
  7177. Sema &S, ArrayRef<Expr *> Args,
  7178. Qualifiers VisibleTypeConversionsQuals,
  7179. bool HasArithmeticOrEnumeralCandidateType,
  7180. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  7181. OverloadCandidateSet &CandidateSet)
  7182. : S(S), Args(Args),
  7183. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  7184. HasArithmeticOrEnumeralCandidateType(
  7185. HasArithmeticOrEnumeralCandidateType),
  7186. CandidateTypes(CandidateTypes),
  7187. CandidateSet(CandidateSet) {
  7188. InitArithmeticTypes();
  7189. }
  7190. // Increment is deprecated for bool since C++17.
  7191. //
  7192. // C++ [over.built]p3:
  7193. //
  7194. // For every pair (T, VQ), where T is an arithmetic type other
  7195. // than bool, and VQ is either volatile or empty, there exist
  7196. // candidate operator functions of the form
  7197. //
  7198. // VQ T& operator++(VQ T&);
  7199. // T operator++(VQ T&, int);
  7200. //
  7201. // C++ [over.built]p4:
  7202. //
  7203. // For every pair (T, VQ), where T is an arithmetic type other
  7204. // than bool, and VQ is either volatile or empty, there exist
  7205. // candidate operator functions of the form
  7206. //
  7207. // VQ T& operator--(VQ T&);
  7208. // T operator--(VQ T&, int);
  7209. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  7210. if (!HasArithmeticOrEnumeralCandidateType)
  7211. return;
  7212. for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
  7213. const auto TypeOfT = ArithmeticTypes[Arith];
  7214. if (TypeOfT == S.Context.BoolTy) {
  7215. if (Op == OO_MinusMinus)
  7216. continue;
  7217. if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
  7218. continue;
  7219. }
  7220. addPlusPlusMinusMinusStyleOverloads(
  7221. TypeOfT,
  7222. VisibleTypeConversionsQuals.hasVolatile(),
  7223. VisibleTypeConversionsQuals.hasRestrict());
  7224. }
  7225. }
  7226. // C++ [over.built]p5:
  7227. //
  7228. // For every pair (T, VQ), where T is a cv-qualified or
  7229. // cv-unqualified object type, and VQ is either volatile or
  7230. // empty, there exist candidate operator functions of the form
  7231. //
  7232. // T*VQ& operator++(T*VQ&);
  7233. // T*VQ& operator--(T*VQ&);
  7234. // T* operator++(T*VQ&, int);
  7235. // T* operator--(T*VQ&, int);
  7236. void addPlusPlusMinusMinusPointerOverloads() {
  7237. for (BuiltinCandidateTypeSet::iterator
  7238. Ptr = CandidateTypes[0].pointer_begin(),
  7239. PtrEnd = CandidateTypes[0].pointer_end();
  7240. Ptr != PtrEnd; ++Ptr) {
  7241. // Skip pointer types that aren't pointers to object types.
  7242. if (!(*Ptr)->getPointeeType()->isObjectType())
  7243. continue;
  7244. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  7245. (!(*Ptr).isVolatileQualified() &&
  7246. VisibleTypeConversionsQuals.hasVolatile()),
  7247. (!(*Ptr).isRestrictQualified() &&
  7248. VisibleTypeConversionsQuals.hasRestrict()));
  7249. }
  7250. }
  7251. // C++ [over.built]p6:
  7252. // For every cv-qualified or cv-unqualified object type T, there
  7253. // exist candidate operator functions of the form
  7254. //
  7255. // T& operator*(T*);
  7256. //
  7257. // C++ [over.built]p7:
  7258. // For every function type T that does not have cv-qualifiers or a
  7259. // ref-qualifier, there exist candidate operator functions of the form
  7260. // T& operator*(T*);
  7261. void addUnaryStarPointerOverloads() {
  7262. for (BuiltinCandidateTypeSet::iterator
  7263. Ptr = CandidateTypes[0].pointer_begin(),
  7264. PtrEnd = CandidateTypes[0].pointer_end();
  7265. Ptr != PtrEnd; ++Ptr) {
  7266. QualType ParamTy = *Ptr;
  7267. QualType PointeeTy = ParamTy->getPointeeType();
  7268. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  7269. continue;
  7270. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  7271. if (Proto->getMethodQuals() || Proto->getRefQualifier())
  7272. continue;
  7273. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7274. }
  7275. }
  7276. // C++ [over.built]p9:
  7277. // For every promoted arithmetic type T, there exist candidate
  7278. // operator functions of the form
  7279. //
  7280. // T operator+(T);
  7281. // T operator-(T);
  7282. void addUnaryPlusOrMinusArithmeticOverloads() {
  7283. if (!HasArithmeticOrEnumeralCandidateType)
  7284. return;
  7285. for (unsigned Arith = FirstPromotedArithmeticType;
  7286. Arith < LastPromotedArithmeticType; ++Arith) {
  7287. QualType ArithTy = ArithmeticTypes[Arith];
  7288. S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
  7289. }
  7290. // Extension: We also add these operators for vector types.
  7291. for (BuiltinCandidateTypeSet::iterator
  7292. Vec = CandidateTypes[0].vector_begin(),
  7293. VecEnd = CandidateTypes[0].vector_end();
  7294. Vec != VecEnd; ++Vec) {
  7295. QualType VecTy = *Vec;
  7296. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7297. }
  7298. }
  7299. // C++ [over.built]p8:
  7300. // For every type T, there exist candidate operator functions of
  7301. // the form
  7302. //
  7303. // T* operator+(T*);
  7304. void addUnaryPlusPointerOverloads() {
  7305. for (BuiltinCandidateTypeSet::iterator
  7306. Ptr = CandidateTypes[0].pointer_begin(),
  7307. PtrEnd = CandidateTypes[0].pointer_end();
  7308. Ptr != PtrEnd; ++Ptr) {
  7309. QualType ParamTy = *Ptr;
  7310. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7311. }
  7312. }
  7313. // C++ [over.built]p10:
  7314. // For every promoted integral type T, there exist candidate
  7315. // operator functions of the form
  7316. //
  7317. // T operator~(T);
  7318. void addUnaryTildePromotedIntegralOverloads() {
  7319. if (!HasArithmeticOrEnumeralCandidateType)
  7320. return;
  7321. for (unsigned Int = FirstPromotedIntegralType;
  7322. Int < LastPromotedIntegralType; ++Int) {
  7323. QualType IntTy = ArithmeticTypes[Int];
  7324. S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
  7325. }
  7326. // Extension: We also add this operator for vector types.
  7327. for (BuiltinCandidateTypeSet::iterator
  7328. Vec = CandidateTypes[0].vector_begin(),
  7329. VecEnd = CandidateTypes[0].vector_end();
  7330. Vec != VecEnd; ++Vec) {
  7331. QualType VecTy = *Vec;
  7332. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7333. }
  7334. }
  7335. // C++ [over.match.oper]p16:
  7336. // For every pointer to member type T or type std::nullptr_t, there
  7337. // exist candidate operator functions of the form
  7338. //
  7339. // bool operator==(T,T);
  7340. // bool operator!=(T,T);
  7341. void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
  7342. /// Set of (canonical) types that we've already handled.
  7343. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7344. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7345. for (BuiltinCandidateTypeSet::iterator
  7346. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7347. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7348. MemPtr != MemPtrEnd;
  7349. ++MemPtr) {
  7350. // Don't add the same builtin candidate twice.
  7351. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7352. continue;
  7353. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7354. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7355. }
  7356. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  7357. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  7358. if (AddedTypes.insert(NullPtrTy).second) {
  7359. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  7360. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7361. }
  7362. }
  7363. }
  7364. }
  7365. // C++ [over.built]p15:
  7366. //
  7367. // For every T, where T is an enumeration type or a pointer type,
  7368. // there exist candidate operator functions of the form
  7369. //
  7370. // bool operator<(T, T);
  7371. // bool operator>(T, T);
  7372. // bool operator<=(T, T);
  7373. // bool operator>=(T, T);
  7374. // bool operator==(T, T);
  7375. // bool operator!=(T, T);
  7376. // R operator<=>(T, T)
  7377. void addGenericBinaryPointerOrEnumeralOverloads() {
  7378. // C++ [over.match.oper]p3:
  7379. // [...]the built-in candidates include all of the candidate operator
  7380. // functions defined in 13.6 that, compared to the given operator, [...]
  7381. // do not have the same parameter-type-list as any non-template non-member
  7382. // candidate.
  7383. //
  7384. // Note that in practice, this only affects enumeration types because there
  7385. // aren't any built-in candidates of record type, and a user-defined operator
  7386. // must have an operand of record or enumeration type. Also, the only other
  7387. // overloaded operator with enumeration arguments, operator=,
  7388. // cannot be overloaded for enumeration types, so this is the only place
  7389. // where we must suppress candidates like this.
  7390. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  7391. UserDefinedBinaryOperators;
  7392. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7393. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  7394. CandidateTypes[ArgIdx].enumeration_end()) {
  7395. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  7396. CEnd = CandidateSet.end();
  7397. C != CEnd; ++C) {
  7398. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  7399. continue;
  7400. if (C->Function->isFunctionTemplateSpecialization())
  7401. continue;
  7402. // We interpret "same parameter-type-list" as applying to the
  7403. // "synthesized candidate, with the order of the two parameters
  7404. // reversed", not to the original function.
  7405. bool Reversed = C->RewriteKind & CRK_Reversed;
  7406. QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
  7407. ->getType()
  7408. .getUnqualifiedType();
  7409. QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
  7410. ->getType()
  7411. .getUnqualifiedType();
  7412. // Skip if either parameter isn't of enumeral type.
  7413. if (!FirstParamType->isEnumeralType() ||
  7414. !SecondParamType->isEnumeralType())
  7415. continue;
  7416. // Add this operator to the set of known user-defined operators.
  7417. UserDefinedBinaryOperators.insert(
  7418. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  7419. S.Context.getCanonicalType(SecondParamType)));
  7420. }
  7421. }
  7422. }
  7423. /// Set of (canonical) types that we've already handled.
  7424. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7425. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7426. for (BuiltinCandidateTypeSet::iterator
  7427. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7428. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7429. Ptr != PtrEnd; ++Ptr) {
  7430. // Don't add the same builtin candidate twice.
  7431. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7432. continue;
  7433. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7434. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7435. }
  7436. for (BuiltinCandidateTypeSet::iterator
  7437. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7438. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7439. Enum != EnumEnd; ++Enum) {
  7440. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  7441. // Don't add the same builtin candidate twice, or if a user defined
  7442. // candidate exists.
  7443. if (!AddedTypes.insert(CanonType).second ||
  7444. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  7445. CanonType)))
  7446. continue;
  7447. QualType ParamTypes[2] = { *Enum, *Enum };
  7448. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7449. }
  7450. }
  7451. }
  7452. // C++ [over.built]p13:
  7453. //
  7454. // For every cv-qualified or cv-unqualified object type T
  7455. // there exist candidate operator functions of the form
  7456. //
  7457. // T* operator+(T*, ptrdiff_t);
  7458. // T& operator[](T*, ptrdiff_t); [BELOW]
  7459. // T* operator-(T*, ptrdiff_t);
  7460. // T* operator+(ptrdiff_t, T*);
  7461. // T& operator[](ptrdiff_t, T*); [BELOW]
  7462. //
  7463. // C++ [over.built]p14:
  7464. //
  7465. // For every T, where T is a pointer to object type, there
  7466. // exist candidate operator functions of the form
  7467. //
  7468. // ptrdiff_t operator-(T, T);
  7469. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  7470. /// Set of (canonical) types that we've already handled.
  7471. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7472. for (int Arg = 0; Arg < 2; ++Arg) {
  7473. QualType AsymmetricParamTypes[2] = {
  7474. S.Context.getPointerDiffType(),
  7475. S.Context.getPointerDiffType(),
  7476. };
  7477. for (BuiltinCandidateTypeSet::iterator
  7478. Ptr = CandidateTypes[Arg].pointer_begin(),
  7479. PtrEnd = CandidateTypes[Arg].pointer_end();
  7480. Ptr != PtrEnd; ++Ptr) {
  7481. QualType PointeeTy = (*Ptr)->getPointeeType();
  7482. if (!PointeeTy->isObjectType())
  7483. continue;
  7484. AsymmetricParamTypes[Arg] = *Ptr;
  7485. if (Arg == 0 || Op == OO_Plus) {
  7486. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  7487. // T* operator+(ptrdiff_t, T*);
  7488. S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
  7489. }
  7490. if (Op == OO_Minus) {
  7491. // ptrdiff_t operator-(T, T);
  7492. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7493. continue;
  7494. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7495. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7496. }
  7497. }
  7498. }
  7499. }
  7500. // C++ [over.built]p12:
  7501. //
  7502. // For every pair of promoted arithmetic types L and R, there
  7503. // exist candidate operator functions of the form
  7504. //
  7505. // LR operator*(L, R);
  7506. // LR operator/(L, R);
  7507. // LR operator+(L, R);
  7508. // LR operator-(L, R);
  7509. // bool operator<(L, R);
  7510. // bool operator>(L, R);
  7511. // bool operator<=(L, R);
  7512. // bool operator>=(L, R);
  7513. // bool operator==(L, R);
  7514. // bool operator!=(L, R);
  7515. //
  7516. // where LR is the result of the usual arithmetic conversions
  7517. // between types L and R.
  7518. //
  7519. // C++ [over.built]p24:
  7520. //
  7521. // For every pair of promoted arithmetic types L and R, there exist
  7522. // candidate operator functions of the form
  7523. //
  7524. // LR operator?(bool, L, R);
  7525. //
  7526. // where LR is the result of the usual arithmetic conversions
  7527. // between types L and R.
  7528. // Our candidates ignore the first parameter.
  7529. void addGenericBinaryArithmeticOverloads() {
  7530. if (!HasArithmeticOrEnumeralCandidateType)
  7531. return;
  7532. for (unsigned Left = FirstPromotedArithmeticType;
  7533. Left < LastPromotedArithmeticType; ++Left) {
  7534. for (unsigned Right = FirstPromotedArithmeticType;
  7535. Right < LastPromotedArithmeticType; ++Right) {
  7536. QualType LandR[2] = { ArithmeticTypes[Left],
  7537. ArithmeticTypes[Right] };
  7538. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7539. }
  7540. }
  7541. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  7542. // conditional operator for vector types.
  7543. for (BuiltinCandidateTypeSet::iterator
  7544. Vec1 = CandidateTypes[0].vector_begin(),
  7545. Vec1End = CandidateTypes[0].vector_end();
  7546. Vec1 != Vec1End; ++Vec1) {
  7547. for (BuiltinCandidateTypeSet::iterator
  7548. Vec2 = CandidateTypes[1].vector_begin(),
  7549. Vec2End = CandidateTypes[1].vector_end();
  7550. Vec2 != Vec2End; ++Vec2) {
  7551. QualType LandR[2] = { *Vec1, *Vec2 };
  7552. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7553. }
  7554. }
  7555. }
  7556. // C++2a [over.built]p14:
  7557. //
  7558. // For every integral type T there exists a candidate operator function
  7559. // of the form
  7560. //
  7561. // std::strong_ordering operator<=>(T, T)
  7562. //
  7563. // C++2a [over.built]p15:
  7564. //
  7565. // For every pair of floating-point types L and R, there exists a candidate
  7566. // operator function of the form
  7567. //
  7568. // std::partial_ordering operator<=>(L, R);
  7569. //
  7570. // FIXME: The current specification for integral types doesn't play nice with
  7571. // the direction of p0946r0, which allows mixed integral and unscoped-enum
  7572. // comparisons. Under the current spec this can lead to ambiguity during
  7573. // overload resolution. For example:
  7574. //
  7575. // enum A : int {a};
  7576. // auto x = (a <=> (long)42);
  7577. //
  7578. // error: call is ambiguous for arguments 'A' and 'long'.
  7579. // note: candidate operator<=>(int, int)
  7580. // note: candidate operator<=>(long, long)
  7581. //
  7582. // To avoid this error, this function deviates from the specification and adds
  7583. // the mixed overloads `operator<=>(L, R)` where L and R are promoted
  7584. // arithmetic types (the same as the generic relational overloads).
  7585. //
  7586. // For now this function acts as a placeholder.
  7587. void addThreeWayArithmeticOverloads() {
  7588. addGenericBinaryArithmeticOverloads();
  7589. }
  7590. // C++ [over.built]p17:
  7591. //
  7592. // For every pair of promoted integral types L and R, there
  7593. // exist candidate operator functions of the form
  7594. //
  7595. // LR operator%(L, R);
  7596. // LR operator&(L, R);
  7597. // LR operator^(L, R);
  7598. // LR operator|(L, R);
  7599. // L operator<<(L, R);
  7600. // L operator>>(L, R);
  7601. //
  7602. // where LR is the result of the usual arithmetic conversions
  7603. // between types L and R.
  7604. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7605. if (!HasArithmeticOrEnumeralCandidateType)
  7606. return;
  7607. for (unsigned Left = FirstPromotedIntegralType;
  7608. Left < LastPromotedIntegralType; ++Left) {
  7609. for (unsigned Right = FirstPromotedIntegralType;
  7610. Right < LastPromotedIntegralType; ++Right) {
  7611. QualType LandR[2] = { ArithmeticTypes[Left],
  7612. ArithmeticTypes[Right] };
  7613. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7614. }
  7615. }
  7616. }
  7617. // C++ [over.built]p20:
  7618. //
  7619. // For every pair (T, VQ), where T is an enumeration or
  7620. // pointer to member type and VQ is either volatile or
  7621. // empty, there exist candidate operator functions of the form
  7622. //
  7623. // VQ T& operator=(VQ T&, T);
  7624. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7625. /// Set of (canonical) types that we've already handled.
  7626. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7627. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7628. for (BuiltinCandidateTypeSet::iterator
  7629. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7630. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7631. Enum != EnumEnd; ++Enum) {
  7632. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7633. continue;
  7634. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7635. }
  7636. for (BuiltinCandidateTypeSet::iterator
  7637. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7638. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7639. MemPtr != MemPtrEnd; ++MemPtr) {
  7640. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7641. continue;
  7642. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7643. }
  7644. }
  7645. }
  7646. // C++ [over.built]p19:
  7647. //
  7648. // For every pair (T, VQ), where T is any type and VQ is either
  7649. // volatile or empty, there exist candidate operator functions
  7650. // of the form
  7651. //
  7652. // T*VQ& operator=(T*VQ&, T*);
  7653. //
  7654. // C++ [over.built]p21:
  7655. //
  7656. // For every pair (T, VQ), where T is a cv-qualified or
  7657. // cv-unqualified object type and VQ is either volatile or
  7658. // empty, there exist candidate operator functions of the form
  7659. //
  7660. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7661. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7662. void addAssignmentPointerOverloads(bool isEqualOp) {
  7663. /// Set of (canonical) types that we've already handled.
  7664. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7665. for (BuiltinCandidateTypeSet::iterator
  7666. Ptr = CandidateTypes[0].pointer_begin(),
  7667. PtrEnd = CandidateTypes[0].pointer_end();
  7668. Ptr != PtrEnd; ++Ptr) {
  7669. // If this is operator=, keep track of the builtin candidates we added.
  7670. if (isEqualOp)
  7671. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7672. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7673. continue;
  7674. // non-volatile version
  7675. QualType ParamTypes[2] = {
  7676. S.Context.getLValueReferenceType(*Ptr),
  7677. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7678. };
  7679. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7680. /*IsAssignmentOperator=*/ isEqualOp);
  7681. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7682. VisibleTypeConversionsQuals.hasVolatile();
  7683. if (NeedVolatile) {
  7684. // volatile version
  7685. ParamTypes[0] =
  7686. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7687. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7688. /*IsAssignmentOperator=*/isEqualOp);
  7689. }
  7690. if (!(*Ptr).isRestrictQualified() &&
  7691. VisibleTypeConversionsQuals.hasRestrict()) {
  7692. // restrict version
  7693. ParamTypes[0]
  7694. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7695. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7696. /*IsAssignmentOperator=*/isEqualOp);
  7697. if (NeedVolatile) {
  7698. // volatile restrict version
  7699. ParamTypes[0]
  7700. = S.Context.getLValueReferenceType(
  7701. S.Context.getCVRQualifiedType(*Ptr,
  7702. (Qualifiers::Volatile |
  7703. Qualifiers::Restrict)));
  7704. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7705. /*IsAssignmentOperator=*/isEqualOp);
  7706. }
  7707. }
  7708. }
  7709. if (isEqualOp) {
  7710. for (BuiltinCandidateTypeSet::iterator
  7711. Ptr = CandidateTypes[1].pointer_begin(),
  7712. PtrEnd = CandidateTypes[1].pointer_end();
  7713. Ptr != PtrEnd; ++Ptr) {
  7714. // Make sure we don't add the same candidate twice.
  7715. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7716. continue;
  7717. QualType ParamTypes[2] = {
  7718. S.Context.getLValueReferenceType(*Ptr),
  7719. *Ptr,
  7720. };
  7721. // non-volatile version
  7722. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7723. /*IsAssignmentOperator=*/true);
  7724. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7725. VisibleTypeConversionsQuals.hasVolatile();
  7726. if (NeedVolatile) {
  7727. // volatile version
  7728. ParamTypes[0] =
  7729. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7730. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7731. /*IsAssignmentOperator=*/true);
  7732. }
  7733. if (!(*Ptr).isRestrictQualified() &&
  7734. VisibleTypeConversionsQuals.hasRestrict()) {
  7735. // restrict version
  7736. ParamTypes[0]
  7737. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7738. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7739. /*IsAssignmentOperator=*/true);
  7740. if (NeedVolatile) {
  7741. // volatile restrict version
  7742. ParamTypes[0]
  7743. = S.Context.getLValueReferenceType(
  7744. S.Context.getCVRQualifiedType(*Ptr,
  7745. (Qualifiers::Volatile |
  7746. Qualifiers::Restrict)));
  7747. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7748. /*IsAssignmentOperator=*/true);
  7749. }
  7750. }
  7751. }
  7752. }
  7753. }
  7754. // C++ [over.built]p18:
  7755. //
  7756. // For every triple (L, VQ, R), where L is an arithmetic type,
  7757. // VQ is either volatile or empty, and R is a promoted
  7758. // arithmetic type, there exist candidate operator functions of
  7759. // the form
  7760. //
  7761. // VQ L& operator=(VQ L&, R);
  7762. // VQ L& operator*=(VQ L&, R);
  7763. // VQ L& operator/=(VQ L&, R);
  7764. // VQ L& operator+=(VQ L&, R);
  7765. // VQ L& operator-=(VQ L&, R);
  7766. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7767. if (!HasArithmeticOrEnumeralCandidateType)
  7768. return;
  7769. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7770. for (unsigned Right = FirstPromotedArithmeticType;
  7771. Right < LastPromotedArithmeticType; ++Right) {
  7772. QualType ParamTypes[2];
  7773. ParamTypes[1] = ArithmeticTypes[Right];
  7774. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  7775. S, ArithmeticTypes[Left], Args[0]);
  7776. // Add this built-in operator as a candidate (VQ is empty).
  7777. ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
  7778. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7779. /*IsAssignmentOperator=*/isEqualOp);
  7780. // Add this built-in operator as a candidate (VQ is 'volatile').
  7781. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7782. ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
  7783. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7784. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7785. /*IsAssignmentOperator=*/isEqualOp);
  7786. }
  7787. }
  7788. }
  7789. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7790. for (BuiltinCandidateTypeSet::iterator
  7791. Vec1 = CandidateTypes[0].vector_begin(),
  7792. Vec1End = CandidateTypes[0].vector_end();
  7793. Vec1 != Vec1End; ++Vec1) {
  7794. for (BuiltinCandidateTypeSet::iterator
  7795. Vec2 = CandidateTypes[1].vector_begin(),
  7796. Vec2End = CandidateTypes[1].vector_end();
  7797. Vec2 != Vec2End; ++Vec2) {
  7798. QualType ParamTypes[2];
  7799. ParamTypes[1] = *Vec2;
  7800. // Add this built-in operator as a candidate (VQ is empty).
  7801. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7802. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7803. /*IsAssignmentOperator=*/isEqualOp);
  7804. // Add this built-in operator as a candidate (VQ is 'volatile').
  7805. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7806. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7807. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7808. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7809. /*IsAssignmentOperator=*/isEqualOp);
  7810. }
  7811. }
  7812. }
  7813. }
  7814. // C++ [over.built]p22:
  7815. //
  7816. // For every triple (L, VQ, R), where L is an integral type, VQ
  7817. // is either volatile or empty, and R is a promoted integral
  7818. // type, there exist candidate operator functions of the form
  7819. //
  7820. // VQ L& operator%=(VQ L&, R);
  7821. // VQ L& operator<<=(VQ L&, R);
  7822. // VQ L& operator>>=(VQ L&, R);
  7823. // VQ L& operator&=(VQ L&, R);
  7824. // VQ L& operator^=(VQ L&, R);
  7825. // VQ L& operator|=(VQ L&, R);
  7826. void addAssignmentIntegralOverloads() {
  7827. if (!HasArithmeticOrEnumeralCandidateType)
  7828. return;
  7829. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7830. for (unsigned Right = FirstPromotedIntegralType;
  7831. Right < LastPromotedIntegralType; ++Right) {
  7832. QualType ParamTypes[2];
  7833. ParamTypes[1] = ArithmeticTypes[Right];
  7834. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  7835. S, ArithmeticTypes[Left], Args[0]);
  7836. // Add this built-in operator as a candidate (VQ is empty).
  7837. ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
  7838. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7839. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7840. // Add this built-in operator as a candidate (VQ is 'volatile').
  7841. ParamTypes[0] = LeftBaseTy;
  7842. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7843. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7844. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7845. }
  7846. }
  7847. }
  7848. }
  7849. // C++ [over.operator]p23:
  7850. //
  7851. // There also exist candidate operator functions of the form
  7852. //
  7853. // bool operator!(bool);
  7854. // bool operator&&(bool, bool);
  7855. // bool operator||(bool, bool);
  7856. void addExclaimOverload() {
  7857. QualType ParamTy = S.Context.BoolTy;
  7858. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
  7859. /*IsAssignmentOperator=*/false,
  7860. /*NumContextualBoolArguments=*/1);
  7861. }
  7862. void addAmpAmpOrPipePipeOverload() {
  7863. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7864. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7865. /*IsAssignmentOperator=*/false,
  7866. /*NumContextualBoolArguments=*/2);
  7867. }
  7868. // C++ [over.built]p13:
  7869. //
  7870. // For every cv-qualified or cv-unqualified object type T there
  7871. // exist candidate operator functions of the form
  7872. //
  7873. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7874. // T& operator[](T*, ptrdiff_t);
  7875. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7876. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7877. // T& operator[](ptrdiff_t, T*);
  7878. void addSubscriptOverloads() {
  7879. for (BuiltinCandidateTypeSet::iterator
  7880. Ptr = CandidateTypes[0].pointer_begin(),
  7881. PtrEnd = CandidateTypes[0].pointer_end();
  7882. Ptr != PtrEnd; ++Ptr) {
  7883. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7884. QualType PointeeType = (*Ptr)->getPointeeType();
  7885. if (!PointeeType->isObjectType())
  7886. continue;
  7887. // T& operator[](T*, ptrdiff_t)
  7888. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7889. }
  7890. for (BuiltinCandidateTypeSet::iterator
  7891. Ptr = CandidateTypes[1].pointer_begin(),
  7892. PtrEnd = CandidateTypes[1].pointer_end();
  7893. Ptr != PtrEnd; ++Ptr) {
  7894. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7895. QualType PointeeType = (*Ptr)->getPointeeType();
  7896. if (!PointeeType->isObjectType())
  7897. continue;
  7898. // T& operator[](ptrdiff_t, T*)
  7899. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7900. }
  7901. }
  7902. // C++ [over.built]p11:
  7903. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7904. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7905. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7906. // there exist candidate operator functions of the form
  7907. //
  7908. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7909. //
  7910. // where CV12 is the union of CV1 and CV2.
  7911. void addArrowStarOverloads() {
  7912. for (BuiltinCandidateTypeSet::iterator
  7913. Ptr = CandidateTypes[0].pointer_begin(),
  7914. PtrEnd = CandidateTypes[0].pointer_end();
  7915. Ptr != PtrEnd; ++Ptr) {
  7916. QualType C1Ty = (*Ptr);
  7917. QualType C1;
  7918. QualifierCollector Q1;
  7919. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7920. if (!isa<RecordType>(C1))
  7921. continue;
  7922. // heuristic to reduce number of builtin candidates in the set.
  7923. // Add volatile/restrict version only if there are conversions to a
  7924. // volatile/restrict type.
  7925. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7926. continue;
  7927. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7928. continue;
  7929. for (BuiltinCandidateTypeSet::iterator
  7930. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7931. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7932. MemPtr != MemPtrEnd; ++MemPtr) {
  7933. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7934. QualType C2 = QualType(mptr->getClass(), 0);
  7935. C2 = C2.getUnqualifiedType();
  7936. if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
  7937. break;
  7938. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7939. // build CV12 T&
  7940. QualType T = mptr->getPointeeType();
  7941. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7942. T.isVolatileQualified())
  7943. continue;
  7944. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7945. T.isRestrictQualified())
  7946. continue;
  7947. T = Q1.apply(S.Context, T);
  7948. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7949. }
  7950. }
  7951. }
  7952. // Note that we don't consider the first argument, since it has been
  7953. // contextually converted to bool long ago. The candidates below are
  7954. // therefore added as binary.
  7955. //
  7956. // C++ [over.built]p25:
  7957. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7958. // enumeration type, there exist candidate operator functions of the form
  7959. //
  7960. // T operator?(bool, T, T);
  7961. //
  7962. void addConditionalOperatorOverloads() {
  7963. /// Set of (canonical) types that we've already handled.
  7964. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7965. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7966. for (BuiltinCandidateTypeSet::iterator
  7967. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7968. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7969. Ptr != PtrEnd; ++Ptr) {
  7970. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7971. continue;
  7972. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7973. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7974. }
  7975. for (BuiltinCandidateTypeSet::iterator
  7976. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7977. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7978. MemPtr != MemPtrEnd; ++MemPtr) {
  7979. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7980. continue;
  7981. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7982. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7983. }
  7984. if (S.getLangOpts().CPlusPlus11) {
  7985. for (BuiltinCandidateTypeSet::iterator
  7986. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7987. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7988. Enum != EnumEnd; ++Enum) {
  7989. if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
  7990. continue;
  7991. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7992. continue;
  7993. QualType ParamTypes[2] = { *Enum, *Enum };
  7994. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7995. }
  7996. }
  7997. }
  7998. }
  7999. };
  8000. } // end anonymous namespace
  8001. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  8002. /// operator overloads to the candidate set (C++ [over.built]), based
  8003. /// on the operator @p Op and the arguments given. For example, if the
  8004. /// operator is a binary '+', this routine might add "int
  8005. /// operator+(int, int)" to cover integer addition.
  8006. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  8007. SourceLocation OpLoc,
  8008. ArrayRef<Expr *> Args,
  8009. OverloadCandidateSet &CandidateSet) {
  8010. // Find all of the types that the arguments can convert to, but only
  8011. // if the operator we're looking at has built-in operator candidates
  8012. // that make use of these types. Also record whether we encounter non-record
  8013. // candidate types or either arithmetic or enumeral candidate types.
  8014. Qualifiers VisibleTypeConversionsQuals;
  8015. VisibleTypeConversionsQuals.addConst();
  8016. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  8017. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  8018. bool HasNonRecordCandidateType = false;
  8019. bool HasArithmeticOrEnumeralCandidateType = false;
  8020. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  8021. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  8022. CandidateTypes.emplace_back(*this);
  8023. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  8024. OpLoc,
  8025. true,
  8026. (Op == OO_Exclaim ||
  8027. Op == OO_AmpAmp ||
  8028. Op == OO_PipePipe),
  8029. VisibleTypeConversionsQuals);
  8030. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  8031. CandidateTypes[ArgIdx].hasNonRecordTypes();
  8032. HasArithmeticOrEnumeralCandidateType =
  8033. HasArithmeticOrEnumeralCandidateType ||
  8034. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  8035. }
  8036. // Exit early when no non-record types have been added to the candidate set
  8037. // for any of the arguments to the operator.
  8038. //
  8039. // We can't exit early for !, ||, or &&, since there we have always have
  8040. // 'bool' overloads.
  8041. if (!HasNonRecordCandidateType &&
  8042. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  8043. return;
  8044. // Setup an object to manage the common state for building overloads.
  8045. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  8046. VisibleTypeConversionsQuals,
  8047. HasArithmeticOrEnumeralCandidateType,
  8048. CandidateTypes, CandidateSet);
  8049. // Dispatch over the operation to add in only those overloads which apply.
  8050. switch (Op) {
  8051. case OO_None:
  8052. case NUM_OVERLOADED_OPERATORS:
  8053. llvm_unreachable("Expected an overloaded operator");
  8054. case OO_New:
  8055. case OO_Delete:
  8056. case OO_Array_New:
  8057. case OO_Array_Delete:
  8058. case OO_Call:
  8059. llvm_unreachable(
  8060. "Special operators don't use AddBuiltinOperatorCandidates");
  8061. case OO_Comma:
  8062. case OO_Arrow:
  8063. case OO_Coawait:
  8064. // C++ [over.match.oper]p3:
  8065. // -- For the operator ',', the unary operator '&', the
  8066. // operator '->', or the operator 'co_await', the
  8067. // built-in candidates set is empty.
  8068. break;
  8069. case OO_Plus: // '+' is either unary or binary
  8070. if (Args.size() == 1)
  8071. OpBuilder.addUnaryPlusPointerOverloads();
  8072. LLVM_FALLTHROUGH;
  8073. case OO_Minus: // '-' is either unary or binary
  8074. if (Args.size() == 1) {
  8075. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  8076. } else {
  8077. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  8078. OpBuilder.addGenericBinaryArithmeticOverloads();
  8079. }
  8080. break;
  8081. case OO_Star: // '*' is either unary or binary
  8082. if (Args.size() == 1)
  8083. OpBuilder.addUnaryStarPointerOverloads();
  8084. else
  8085. OpBuilder.addGenericBinaryArithmeticOverloads();
  8086. break;
  8087. case OO_Slash:
  8088. OpBuilder.addGenericBinaryArithmeticOverloads();
  8089. break;
  8090. case OO_PlusPlus:
  8091. case OO_MinusMinus:
  8092. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  8093. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  8094. break;
  8095. case OO_EqualEqual:
  8096. case OO_ExclaimEqual:
  8097. OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
  8098. LLVM_FALLTHROUGH;
  8099. case OO_Less:
  8100. case OO_Greater:
  8101. case OO_LessEqual:
  8102. case OO_GreaterEqual:
  8103. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
  8104. OpBuilder.addGenericBinaryArithmeticOverloads();
  8105. break;
  8106. case OO_Spaceship:
  8107. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
  8108. OpBuilder.addThreeWayArithmeticOverloads();
  8109. break;
  8110. case OO_Percent:
  8111. case OO_Caret:
  8112. case OO_Pipe:
  8113. case OO_LessLess:
  8114. case OO_GreaterGreater:
  8115. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  8116. break;
  8117. case OO_Amp: // '&' is either unary or binary
  8118. if (Args.size() == 1)
  8119. // C++ [over.match.oper]p3:
  8120. // -- For the operator ',', the unary operator '&', or the
  8121. // operator '->', the built-in candidates set is empty.
  8122. break;
  8123. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  8124. break;
  8125. case OO_Tilde:
  8126. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  8127. break;
  8128. case OO_Equal:
  8129. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  8130. LLVM_FALLTHROUGH;
  8131. case OO_PlusEqual:
  8132. case OO_MinusEqual:
  8133. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  8134. LLVM_FALLTHROUGH;
  8135. case OO_StarEqual:
  8136. case OO_SlashEqual:
  8137. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  8138. break;
  8139. case OO_PercentEqual:
  8140. case OO_LessLessEqual:
  8141. case OO_GreaterGreaterEqual:
  8142. case OO_AmpEqual:
  8143. case OO_CaretEqual:
  8144. case OO_PipeEqual:
  8145. OpBuilder.addAssignmentIntegralOverloads();
  8146. break;
  8147. case OO_Exclaim:
  8148. OpBuilder.addExclaimOverload();
  8149. break;
  8150. case OO_AmpAmp:
  8151. case OO_PipePipe:
  8152. OpBuilder.addAmpAmpOrPipePipeOverload();
  8153. break;
  8154. case OO_Subscript:
  8155. OpBuilder.addSubscriptOverloads();
  8156. break;
  8157. case OO_ArrowStar:
  8158. OpBuilder.addArrowStarOverloads();
  8159. break;
  8160. case OO_Conditional:
  8161. OpBuilder.addConditionalOperatorOverloads();
  8162. OpBuilder.addGenericBinaryArithmeticOverloads();
  8163. break;
  8164. }
  8165. }
  8166. /// Add function candidates found via argument-dependent lookup
  8167. /// to the set of overloading candidates.
  8168. ///
  8169. /// This routine performs argument-dependent name lookup based on the
  8170. /// given function name (which may also be an operator name) and adds
  8171. /// all of the overload candidates found by ADL to the overload
  8172. /// candidate set (C++ [basic.lookup.argdep]).
  8173. void
  8174. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  8175. SourceLocation Loc,
  8176. ArrayRef<Expr *> Args,
  8177. TemplateArgumentListInfo *ExplicitTemplateArgs,
  8178. OverloadCandidateSet& CandidateSet,
  8179. bool PartialOverloading) {
  8180. ADLResult Fns;
  8181. // FIXME: This approach for uniquing ADL results (and removing
  8182. // redundant candidates from the set) relies on pointer-equality,
  8183. // which means we need to key off the canonical decl. However,
  8184. // always going back to the canonical decl might not get us the
  8185. // right set of default arguments. What default arguments are
  8186. // we supposed to consider on ADL candidates, anyway?
  8187. // FIXME: Pass in the explicit template arguments?
  8188. ArgumentDependentLookup(Name, Loc, Args, Fns);
  8189. // Erase all of the candidates we already knew about.
  8190. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  8191. CandEnd = CandidateSet.end();
  8192. Cand != CandEnd; ++Cand)
  8193. if (Cand->Function) {
  8194. Fns.erase(Cand->Function);
  8195. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  8196. Fns.erase(FunTmpl);
  8197. }
  8198. // For each of the ADL candidates we found, add it to the overload
  8199. // set.
  8200. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  8201. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  8202. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  8203. if (ExplicitTemplateArgs)
  8204. continue;
  8205. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
  8206. /*SuppressUserConversions=*/false, PartialOverloading,
  8207. /*AllowExplicit*/ true,
  8208. /*AllowExplicitConversions*/ false,
  8209. ADLCallKind::UsesADL);
  8210. } else {
  8211. AddTemplateOverloadCandidate(
  8212. cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
  8213. CandidateSet,
  8214. /*SuppressUserConversions=*/false, PartialOverloading,
  8215. /*AllowExplicit*/true, ADLCallKind::UsesADL);
  8216. }
  8217. }
  8218. }
  8219. namespace {
  8220. enum class Comparison { Equal, Better, Worse };
  8221. }
  8222. /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
  8223. /// overload resolution.
  8224. ///
  8225. /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
  8226. /// Cand1's first N enable_if attributes have precisely the same conditions as
  8227. /// Cand2's first N enable_if attributes (where N = the number of enable_if
  8228. /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
  8229. ///
  8230. /// Note that you can have a pair of candidates such that Cand1's enable_if
  8231. /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
  8232. /// worse than Cand1's.
  8233. static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
  8234. const FunctionDecl *Cand2) {
  8235. // Common case: One (or both) decls don't have enable_if attrs.
  8236. bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
  8237. bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
  8238. if (!Cand1Attr || !Cand2Attr) {
  8239. if (Cand1Attr == Cand2Attr)
  8240. return Comparison::Equal;
  8241. return Cand1Attr ? Comparison::Better : Comparison::Worse;
  8242. }
  8243. auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
  8244. auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
  8245. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  8246. for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
  8247. Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  8248. Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  8249. // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
  8250. // has fewer enable_if attributes than Cand2, and vice versa.
  8251. if (!Cand1A)
  8252. return Comparison::Worse;
  8253. if (!Cand2A)
  8254. return Comparison::Better;
  8255. Cand1ID.clear();
  8256. Cand2ID.clear();
  8257. (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
  8258. (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
  8259. if (Cand1ID != Cand2ID)
  8260. return Comparison::Worse;
  8261. }
  8262. return Comparison::Equal;
  8263. }
  8264. static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
  8265. const OverloadCandidate &Cand2) {
  8266. if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
  8267. !Cand2.Function->isMultiVersion())
  8268. return false;
  8269. // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
  8270. // is obviously better.
  8271. if (Cand1.Function->isInvalidDecl()) return false;
  8272. if (Cand2.Function->isInvalidDecl()) return true;
  8273. // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
  8274. // cpu_dispatch, else arbitrarily based on the identifiers.
  8275. bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
  8276. bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
  8277. const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
  8278. const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
  8279. if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
  8280. return false;
  8281. if (Cand1CPUDisp && !Cand2CPUDisp)
  8282. return true;
  8283. if (Cand2CPUDisp && !Cand1CPUDisp)
  8284. return false;
  8285. if (Cand1CPUSpec && Cand2CPUSpec) {
  8286. if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
  8287. return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
  8288. std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
  8289. FirstDiff = std::mismatch(
  8290. Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
  8291. Cand2CPUSpec->cpus_begin(),
  8292. [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
  8293. return LHS->getName() == RHS->getName();
  8294. });
  8295. assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
  8296. "Two different cpu-specific versions should not have the same "
  8297. "identifier list, otherwise they'd be the same decl!");
  8298. return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
  8299. }
  8300. llvm_unreachable("No way to get here unless both had cpu_dispatch");
  8301. }
  8302. /// isBetterOverloadCandidate - Determines whether the first overload
  8303. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  8304. bool clang::isBetterOverloadCandidate(
  8305. Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
  8306. SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
  8307. // Define viable functions to be better candidates than non-viable
  8308. // functions.
  8309. if (!Cand2.Viable)
  8310. return Cand1.Viable;
  8311. else if (!Cand1.Viable)
  8312. return false;
  8313. // C++ [over.match.best]p1:
  8314. //
  8315. // -- if F is a static member function, ICS1(F) is defined such
  8316. // that ICS1(F) is neither better nor worse than ICS1(G) for
  8317. // any function G, and, symmetrically, ICS1(G) is neither
  8318. // better nor worse than ICS1(F).
  8319. unsigned StartArg = 0;
  8320. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  8321. StartArg = 1;
  8322. auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
  8323. // We don't allow incompatible pointer conversions in C++.
  8324. if (!S.getLangOpts().CPlusPlus)
  8325. return ICS.isStandard() &&
  8326. ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
  8327. // The only ill-formed conversion we allow in C++ is the string literal to
  8328. // char* conversion, which is only considered ill-formed after C++11.
  8329. return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  8330. hasDeprecatedStringLiteralToCharPtrConversion(ICS);
  8331. };
  8332. // Define functions that don't require ill-formed conversions for a given
  8333. // argument to be better candidates than functions that do.
  8334. unsigned NumArgs = Cand1.Conversions.size();
  8335. assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
  8336. bool HasBetterConversion = false;
  8337. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8338. bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
  8339. bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
  8340. if (Cand1Bad != Cand2Bad) {
  8341. if (Cand1Bad)
  8342. return false;
  8343. HasBetterConversion = true;
  8344. }
  8345. }
  8346. if (HasBetterConversion)
  8347. return true;
  8348. // C++ [over.match.best]p1:
  8349. // A viable function F1 is defined to be a better function than another
  8350. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  8351. // conversion sequence than ICSi(F2), and then...
  8352. bool HasWorseConversion = false;
  8353. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8354. switch (CompareImplicitConversionSequences(S, Loc,
  8355. Cand1.Conversions[ArgIdx],
  8356. Cand2.Conversions[ArgIdx])) {
  8357. case ImplicitConversionSequence::Better:
  8358. // Cand1 has a better conversion sequence.
  8359. HasBetterConversion = true;
  8360. break;
  8361. case ImplicitConversionSequence::Worse:
  8362. if (Cand1.Function && Cand1.Function == Cand2.Function &&
  8363. (Cand2.RewriteKind & CRK_Reversed) != 0) {
  8364. // Work around large-scale breakage caused by considering reversed
  8365. // forms of operator== in C++20:
  8366. //
  8367. // When comparing a function against its reversed form, if we have a
  8368. // better conversion for one argument and a worse conversion for the
  8369. // other, we prefer the non-reversed form.
  8370. //
  8371. // This prevents a conversion function from being considered ambiguous
  8372. // with its own reversed form in various where it's only incidentally
  8373. // heterogeneous.
  8374. //
  8375. // We diagnose this as an extension from CreateOverloadedBinOp.
  8376. HasWorseConversion = true;
  8377. break;
  8378. }
  8379. // Cand1 can't be better than Cand2.
  8380. return false;
  8381. case ImplicitConversionSequence::Indistinguishable:
  8382. // Do nothing.
  8383. break;
  8384. }
  8385. }
  8386. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  8387. // ICSj(F2), or, if not that,
  8388. if (HasBetterConversion)
  8389. return true;
  8390. if (HasWorseConversion)
  8391. return false;
  8392. // -- the context is an initialization by user-defined conversion
  8393. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  8394. // from the return type of F1 to the destination type (i.e.,
  8395. // the type of the entity being initialized) is a better
  8396. // conversion sequence than the standard conversion sequence
  8397. // from the return type of F2 to the destination type.
  8398. if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
  8399. Cand1.Function && Cand2.Function &&
  8400. isa<CXXConversionDecl>(Cand1.Function) &&
  8401. isa<CXXConversionDecl>(Cand2.Function)) {
  8402. // First check whether we prefer one of the conversion functions over the
  8403. // other. This only distinguishes the results in non-standard, extension
  8404. // cases such as the conversion from a lambda closure type to a function
  8405. // pointer or block.
  8406. ImplicitConversionSequence::CompareKind Result =
  8407. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  8408. if (Result == ImplicitConversionSequence::Indistinguishable)
  8409. Result = CompareStandardConversionSequences(S, Loc,
  8410. Cand1.FinalConversion,
  8411. Cand2.FinalConversion);
  8412. if (Result != ImplicitConversionSequence::Indistinguishable)
  8413. return Result == ImplicitConversionSequence::Better;
  8414. // FIXME: Compare kind of reference binding if conversion functions
  8415. // convert to a reference type used in direct reference binding, per
  8416. // C++14 [over.match.best]p1 section 2 bullet 3.
  8417. }
  8418. // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
  8419. // as combined with the resolution to CWG issue 243.
  8420. //
  8421. // When the context is initialization by constructor ([over.match.ctor] or
  8422. // either phase of [over.match.list]), a constructor is preferred over
  8423. // a conversion function.
  8424. if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
  8425. Cand1.Function && Cand2.Function &&
  8426. isa<CXXConstructorDecl>(Cand1.Function) !=
  8427. isa<CXXConstructorDecl>(Cand2.Function))
  8428. return isa<CXXConstructorDecl>(Cand1.Function);
  8429. // -- F1 is a non-template function and F2 is a function template
  8430. // specialization, or, if not that,
  8431. bool Cand1IsSpecialization = Cand1.Function &&
  8432. Cand1.Function->getPrimaryTemplate();
  8433. bool Cand2IsSpecialization = Cand2.Function &&
  8434. Cand2.Function->getPrimaryTemplate();
  8435. if (Cand1IsSpecialization != Cand2IsSpecialization)
  8436. return Cand2IsSpecialization;
  8437. // -- F1 and F2 are function template specializations, and the function
  8438. // template for F1 is more specialized than the template for F2
  8439. // according to the partial ordering rules described in 14.5.5.2, or,
  8440. // if not that,
  8441. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  8442. if (FunctionTemplateDecl *BetterTemplate
  8443. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  8444. Cand2.Function->getPrimaryTemplate(),
  8445. Loc,
  8446. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  8447. : TPOC_Call,
  8448. Cand1.ExplicitCallArguments,
  8449. Cand2.ExplicitCallArguments))
  8450. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  8451. }
  8452. // -- F1 is a constructor for a class D, F2 is a constructor for a base
  8453. // class B of D, and for all arguments the corresponding parameters of
  8454. // F1 and F2 have the same type.
  8455. // FIXME: Implement the "all parameters have the same type" check.
  8456. bool Cand1IsInherited =
  8457. dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
  8458. bool Cand2IsInherited =
  8459. dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
  8460. if (Cand1IsInherited != Cand2IsInherited)
  8461. return Cand2IsInherited;
  8462. else if (Cand1IsInherited) {
  8463. assert(Cand2IsInherited);
  8464. auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
  8465. auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
  8466. if (Cand1Class->isDerivedFrom(Cand2Class))
  8467. return true;
  8468. if (Cand2Class->isDerivedFrom(Cand1Class))
  8469. return false;
  8470. // Inherited from sibling base classes: still ambiguous.
  8471. }
  8472. // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
  8473. // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
  8474. // with reversed order of parameters and F1 is not
  8475. //
  8476. // We rank reversed + different operator as worse than just reversed, but
  8477. // that comparison can never happen, because we only consider reversing for
  8478. // the maximally-rewritten operator (== or <=>).
  8479. if (Cand1.RewriteKind != Cand2.RewriteKind)
  8480. return Cand1.RewriteKind < Cand2.RewriteKind;
  8481. // Check C++17 tie-breakers for deduction guides.
  8482. {
  8483. auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
  8484. auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
  8485. if (Guide1 && Guide2) {
  8486. // -- F1 is generated from a deduction-guide and F2 is not
  8487. if (Guide1->isImplicit() != Guide2->isImplicit())
  8488. return Guide2->isImplicit();
  8489. // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
  8490. if (Guide1->isCopyDeductionCandidate())
  8491. return true;
  8492. }
  8493. }
  8494. // Check for enable_if value-based overload resolution.
  8495. if (Cand1.Function && Cand2.Function) {
  8496. Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
  8497. if (Cmp != Comparison::Equal)
  8498. return Cmp == Comparison::Better;
  8499. }
  8500. if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
  8501. FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
  8502. return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
  8503. S.IdentifyCUDAPreference(Caller, Cand2.Function);
  8504. }
  8505. bool HasPS1 = Cand1.Function != nullptr &&
  8506. functionHasPassObjectSizeParams(Cand1.Function);
  8507. bool HasPS2 = Cand2.Function != nullptr &&
  8508. functionHasPassObjectSizeParams(Cand2.Function);
  8509. if (HasPS1 != HasPS2 && HasPS1)
  8510. return true;
  8511. return isBetterMultiversionCandidate(Cand1, Cand2);
  8512. }
  8513. /// Determine whether two declarations are "equivalent" for the purposes of
  8514. /// name lookup and overload resolution. This applies when the same internal/no
  8515. /// linkage entity is defined by two modules (probably by textually including
  8516. /// the same header). In such a case, we don't consider the declarations to
  8517. /// declare the same entity, but we also don't want lookups with both
  8518. /// declarations visible to be ambiguous in some cases (this happens when using
  8519. /// a modularized libstdc++).
  8520. bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
  8521. const NamedDecl *B) {
  8522. auto *VA = dyn_cast_or_null<ValueDecl>(A);
  8523. auto *VB = dyn_cast_or_null<ValueDecl>(B);
  8524. if (!VA || !VB)
  8525. return false;
  8526. // The declarations must be declaring the same name as an internal linkage
  8527. // entity in different modules.
  8528. if (!VA->getDeclContext()->getRedeclContext()->Equals(
  8529. VB->getDeclContext()->getRedeclContext()) ||
  8530. getOwningModule(const_cast<ValueDecl *>(VA)) ==
  8531. getOwningModule(const_cast<ValueDecl *>(VB)) ||
  8532. VA->isExternallyVisible() || VB->isExternallyVisible())
  8533. return false;
  8534. // Check that the declarations appear to be equivalent.
  8535. //
  8536. // FIXME: Checking the type isn't really enough to resolve the ambiguity.
  8537. // For constants and functions, we should check the initializer or body is
  8538. // the same. For non-constant variables, we shouldn't allow it at all.
  8539. if (Context.hasSameType(VA->getType(), VB->getType()))
  8540. return true;
  8541. // Enum constants within unnamed enumerations will have different types, but
  8542. // may still be similar enough to be interchangeable for our purposes.
  8543. if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
  8544. if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
  8545. // Only handle anonymous enums. If the enumerations were named and
  8546. // equivalent, they would have been merged to the same type.
  8547. auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
  8548. auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
  8549. if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
  8550. !Context.hasSameType(EnumA->getIntegerType(),
  8551. EnumB->getIntegerType()))
  8552. return false;
  8553. // Allow this only if the value is the same for both enumerators.
  8554. return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
  8555. }
  8556. }
  8557. // Nothing else is sufficiently similar.
  8558. return false;
  8559. }
  8560. void Sema::diagnoseEquivalentInternalLinkageDeclarations(
  8561. SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
  8562. Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
  8563. Module *M = getOwningModule(const_cast<NamedDecl*>(D));
  8564. Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
  8565. << !M << (M ? M->getFullModuleName() : "");
  8566. for (auto *E : Equiv) {
  8567. Module *M = getOwningModule(const_cast<NamedDecl*>(E));
  8568. Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
  8569. << !M << (M ? M->getFullModuleName() : "");
  8570. }
  8571. }
  8572. /// Computes the best viable function (C++ 13.3.3)
  8573. /// within an overload candidate set.
  8574. ///
  8575. /// \param Loc The location of the function name (or operator symbol) for
  8576. /// which overload resolution occurs.
  8577. ///
  8578. /// \param Best If overload resolution was successful or found a deleted
  8579. /// function, \p Best points to the candidate function found.
  8580. ///
  8581. /// \returns The result of overload resolution.
  8582. OverloadingResult
  8583. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  8584. iterator &Best) {
  8585. llvm::SmallVector<OverloadCandidate *, 16> Candidates;
  8586. std::transform(begin(), end(), std::back_inserter(Candidates),
  8587. [](OverloadCandidate &Cand) { return &Cand; });
  8588. // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
  8589. // are accepted by both clang and NVCC. However, during a particular
  8590. // compilation mode only one call variant is viable. We need to
  8591. // exclude non-viable overload candidates from consideration based
  8592. // only on their host/device attributes. Specifically, if one
  8593. // candidate call is WrongSide and the other is SameSide, we ignore
  8594. // the WrongSide candidate.
  8595. if (S.getLangOpts().CUDA) {
  8596. const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
  8597. bool ContainsSameSideCandidate =
  8598. llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
  8599. // Check viable function only.
  8600. return Cand->Viable && Cand->Function &&
  8601. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  8602. Sema::CFP_SameSide;
  8603. });
  8604. if (ContainsSameSideCandidate) {
  8605. auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
  8606. // Check viable function only to avoid unnecessary data copying/moving.
  8607. return Cand->Viable && Cand->Function &&
  8608. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  8609. Sema::CFP_WrongSide;
  8610. };
  8611. llvm::erase_if(Candidates, IsWrongSideCandidate);
  8612. }
  8613. }
  8614. // Find the best viable function.
  8615. Best = end();
  8616. for (auto *Cand : Candidates)
  8617. if (Cand->Viable)
  8618. if (Best == end() ||
  8619. isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
  8620. Best = Cand;
  8621. // If we didn't find any viable functions, abort.
  8622. if (Best == end())
  8623. return OR_No_Viable_Function;
  8624. llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
  8625. // Make sure that this function is better than every other viable
  8626. // function. If not, we have an ambiguity.
  8627. for (auto *Cand : Candidates) {
  8628. if (Cand->Viable && Cand != Best &&
  8629. !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
  8630. if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
  8631. Cand->Function)) {
  8632. EquivalentCands.push_back(Cand->Function);
  8633. continue;
  8634. }
  8635. Best = end();
  8636. return OR_Ambiguous;
  8637. }
  8638. }
  8639. // Best is the best viable function.
  8640. if (Best->Function && Best->Function->isDeleted())
  8641. return OR_Deleted;
  8642. if (!EquivalentCands.empty())
  8643. S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
  8644. EquivalentCands);
  8645. return OR_Success;
  8646. }
  8647. namespace {
  8648. enum OverloadCandidateKind {
  8649. oc_function,
  8650. oc_method,
  8651. oc_reversed_binary_operator,
  8652. oc_constructor,
  8653. oc_implicit_default_constructor,
  8654. oc_implicit_copy_constructor,
  8655. oc_implicit_move_constructor,
  8656. oc_implicit_copy_assignment,
  8657. oc_implicit_move_assignment,
  8658. oc_inherited_constructor
  8659. };
  8660. enum OverloadCandidateSelect {
  8661. ocs_non_template,
  8662. ocs_template,
  8663. ocs_described_template,
  8664. };
  8665. static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
  8666. ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
  8667. OverloadCandidateRewriteKind CRK,
  8668. std::string &Description) {
  8669. bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
  8670. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  8671. isTemplate = true;
  8672. Description = S.getTemplateArgumentBindingsText(
  8673. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  8674. }
  8675. OverloadCandidateSelect Select = [&]() {
  8676. if (!Description.empty())
  8677. return ocs_described_template;
  8678. return isTemplate ? ocs_template : ocs_non_template;
  8679. }();
  8680. OverloadCandidateKind Kind = [&]() {
  8681. if (CRK & CRK_Reversed)
  8682. return oc_reversed_binary_operator;
  8683. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  8684. if (!Ctor->isImplicit()) {
  8685. if (isa<ConstructorUsingShadowDecl>(Found))
  8686. return oc_inherited_constructor;
  8687. else
  8688. return oc_constructor;
  8689. }
  8690. if (Ctor->isDefaultConstructor())
  8691. return oc_implicit_default_constructor;
  8692. if (Ctor->isMoveConstructor())
  8693. return oc_implicit_move_constructor;
  8694. assert(Ctor->isCopyConstructor() &&
  8695. "unexpected sort of implicit constructor");
  8696. return oc_implicit_copy_constructor;
  8697. }
  8698. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  8699. // This actually gets spelled 'candidate function' for now, but
  8700. // it doesn't hurt to split it out.
  8701. if (!Meth->isImplicit())
  8702. return oc_method;
  8703. if (Meth->isMoveAssignmentOperator())
  8704. return oc_implicit_move_assignment;
  8705. if (Meth->isCopyAssignmentOperator())
  8706. return oc_implicit_copy_assignment;
  8707. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  8708. return oc_method;
  8709. }
  8710. return oc_function;
  8711. }();
  8712. return std::make_pair(Kind, Select);
  8713. }
  8714. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
  8715. // FIXME: It'd be nice to only emit a note once per using-decl per overload
  8716. // set.
  8717. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
  8718. S.Diag(FoundDecl->getLocation(),
  8719. diag::note_ovl_candidate_inherited_constructor)
  8720. << Shadow->getNominatedBaseClass();
  8721. }
  8722. } // end anonymous namespace
  8723. static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
  8724. const FunctionDecl *FD) {
  8725. for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
  8726. bool AlwaysTrue;
  8727. if (EnableIf->getCond()->isValueDependent() ||
  8728. !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
  8729. return false;
  8730. if (!AlwaysTrue)
  8731. return false;
  8732. }
  8733. return true;
  8734. }
  8735. /// Returns true if we can take the address of the function.
  8736. ///
  8737. /// \param Complain - If true, we'll emit a diagnostic
  8738. /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
  8739. /// we in overload resolution?
  8740. /// \param Loc - The location of the statement we're complaining about. Ignored
  8741. /// if we're not complaining, or if we're in overload resolution.
  8742. static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
  8743. bool Complain,
  8744. bool InOverloadResolution,
  8745. SourceLocation Loc) {
  8746. if (!isFunctionAlwaysEnabled(S.Context, FD)) {
  8747. if (Complain) {
  8748. if (InOverloadResolution)
  8749. S.Diag(FD->getBeginLoc(),
  8750. diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
  8751. else
  8752. S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
  8753. }
  8754. return false;
  8755. }
  8756. auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
  8757. return P->hasAttr<PassObjectSizeAttr>();
  8758. });
  8759. if (I == FD->param_end())
  8760. return true;
  8761. if (Complain) {
  8762. // Add one to ParamNo because it's user-facing
  8763. unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
  8764. if (InOverloadResolution)
  8765. S.Diag(FD->getLocation(),
  8766. diag::note_ovl_candidate_has_pass_object_size_params)
  8767. << ParamNo;
  8768. else
  8769. S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
  8770. << FD << ParamNo;
  8771. }
  8772. return false;
  8773. }
  8774. static bool checkAddressOfCandidateIsAvailable(Sema &S,
  8775. const FunctionDecl *FD) {
  8776. return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
  8777. /*InOverloadResolution=*/true,
  8778. /*Loc=*/SourceLocation());
  8779. }
  8780. bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
  8781. bool Complain,
  8782. SourceLocation Loc) {
  8783. return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
  8784. /*InOverloadResolution=*/false,
  8785. Loc);
  8786. }
  8787. // Notes the location of an overload candidate.
  8788. void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
  8789. OverloadCandidateRewriteKind RewriteKind,
  8790. QualType DestType, bool TakingAddress) {
  8791. if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
  8792. return;
  8793. if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
  8794. !Fn->getAttr<TargetAttr>()->isDefaultVersion())
  8795. return;
  8796. std::string FnDesc;
  8797. std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
  8798. ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
  8799. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  8800. << (unsigned)KSPair.first << (unsigned)KSPair.second
  8801. << Fn << FnDesc;
  8802. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  8803. Diag(Fn->getLocation(), PD);
  8804. MaybeEmitInheritedConstructorNote(*this, Found);
  8805. }
  8806. // Notes the location of all overload candidates designated through
  8807. // OverloadedExpr
  8808. void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
  8809. bool TakingAddress) {
  8810. assert(OverloadedExpr->getType() == Context.OverloadTy);
  8811. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  8812. OverloadExpr *OvlExpr = Ovl.Expression;
  8813. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  8814. IEnd = OvlExpr->decls_end();
  8815. I != IEnd; ++I) {
  8816. if (FunctionTemplateDecl *FunTmpl =
  8817. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  8818. NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
  8819. TakingAddress);
  8820. } else if (FunctionDecl *Fun
  8821. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  8822. NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
  8823. }
  8824. }
  8825. }
  8826. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  8827. /// "lead" diagnostic; it will be given two arguments, the source and
  8828. /// target types of the conversion.
  8829. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  8830. Sema &S,
  8831. SourceLocation CaretLoc,
  8832. const PartialDiagnostic &PDiag) const {
  8833. S.Diag(CaretLoc, PDiag)
  8834. << Ambiguous.getFromType() << Ambiguous.getToType();
  8835. // FIXME: The note limiting machinery is borrowed from
  8836. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  8837. // refactoring here.
  8838. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8839. unsigned CandsShown = 0;
  8840. AmbiguousConversionSequence::const_iterator I, E;
  8841. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  8842. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8843. break;
  8844. ++CandsShown;
  8845. S.NoteOverloadCandidate(I->first, I->second);
  8846. }
  8847. if (I != E)
  8848. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  8849. }
  8850. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  8851. unsigned I, bool TakingCandidateAddress) {
  8852. const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  8853. assert(Conv.isBad());
  8854. assert(Cand->Function && "for now, candidate must be a function");
  8855. FunctionDecl *Fn = Cand->Function;
  8856. // There's a conversion slot for the object argument if this is a
  8857. // non-constructor method. Note that 'I' corresponds the
  8858. // conversion-slot index.
  8859. bool isObjectArgument = false;
  8860. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  8861. if (I == 0)
  8862. isObjectArgument = true;
  8863. else
  8864. I--;
  8865. }
  8866. std::string FnDesc;
  8867. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  8868. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind,
  8869. FnDesc);
  8870. Expr *FromExpr = Conv.Bad.FromExpr;
  8871. QualType FromTy = Conv.Bad.getFromType();
  8872. QualType ToTy = Conv.Bad.getToType();
  8873. if (FromTy == S.Context.OverloadTy) {
  8874. assert(FromExpr && "overload set argument came from implicit argument?");
  8875. Expr *E = FromExpr->IgnoreParens();
  8876. if (isa<UnaryOperator>(E))
  8877. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  8878. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  8879. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
  8880. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8881. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
  8882. << Name << I + 1;
  8883. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8884. return;
  8885. }
  8886. // Do some hand-waving analysis to see if the non-viability is due
  8887. // to a qualifier mismatch.
  8888. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  8889. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  8890. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  8891. CToTy = RT->getPointeeType();
  8892. else {
  8893. // TODO: detect and diagnose the full richness of const mismatches.
  8894. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  8895. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
  8896. CFromTy = FromPT->getPointeeType();
  8897. CToTy = ToPT->getPointeeType();
  8898. }
  8899. }
  8900. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  8901. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  8902. Qualifiers FromQs = CFromTy.getQualifiers();
  8903. Qualifiers ToQs = CToTy.getQualifiers();
  8904. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  8905. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
  8906. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8907. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8908. << ToTy << (unsigned)isObjectArgument << I + 1;
  8909. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8910. return;
  8911. }
  8912. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8913. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
  8914. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8915. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8916. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  8917. << (unsigned)isObjectArgument << I + 1;
  8918. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8919. return;
  8920. }
  8921. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  8922. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
  8923. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8924. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8925. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  8926. << (unsigned)isObjectArgument << I + 1;
  8927. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8928. return;
  8929. }
  8930. if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
  8931. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
  8932. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8933. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8934. << FromQs.hasUnaligned() << I + 1;
  8935. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8936. return;
  8937. }
  8938. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  8939. assert(CVR && "unexpected qualifiers mismatch");
  8940. if (isObjectArgument) {
  8941. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
  8942. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8943. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8944. << (CVR - 1);
  8945. } else {
  8946. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
  8947. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8948. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8949. << (CVR - 1) << I + 1;
  8950. }
  8951. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8952. return;
  8953. }
  8954. // Special diagnostic for failure to convert an initializer list, since
  8955. // telling the user that it has type void is not useful.
  8956. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8957. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
  8958. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8959. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8960. << ToTy << (unsigned)isObjectArgument << I + 1;
  8961. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8962. return;
  8963. }
  8964. // Diagnose references or pointers to incomplete types differently,
  8965. // since it's far from impossible that the incompleteness triggered
  8966. // the failure.
  8967. QualType TempFromTy = FromTy.getNonReferenceType();
  8968. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8969. TempFromTy = PTy->getPointeeType();
  8970. if (TempFromTy->isIncompleteType()) {
  8971. // Emit the generic diagnostic and, optionally, add the hints to it.
  8972. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
  8973. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8974. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8975. << ToTy << (unsigned)isObjectArgument << I + 1
  8976. << (unsigned)(Cand->Fix.Kind);
  8977. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8978. return;
  8979. }
  8980. // Diagnose base -> derived pointer conversions.
  8981. unsigned BaseToDerivedConversion = 0;
  8982. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8983. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8984. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8985. FromPtrTy->getPointeeType()) &&
  8986. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8987. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8988. S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
  8989. FromPtrTy->getPointeeType()))
  8990. BaseToDerivedConversion = 1;
  8991. }
  8992. } else if (const ObjCObjectPointerType *FromPtrTy
  8993. = FromTy->getAs<ObjCObjectPointerType>()) {
  8994. if (const ObjCObjectPointerType *ToPtrTy
  8995. = ToTy->getAs<ObjCObjectPointerType>())
  8996. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8997. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8998. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8999. FromPtrTy->getPointeeType()) &&
  9000. FromIface->isSuperClassOf(ToIface))
  9001. BaseToDerivedConversion = 2;
  9002. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  9003. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  9004. !FromTy->isIncompleteType() &&
  9005. !ToRefTy->getPointeeType()->isIncompleteType() &&
  9006. S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
  9007. BaseToDerivedConversion = 3;
  9008. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  9009. ToTy.getNonReferenceType().getCanonicalType() ==
  9010. FromTy.getNonReferenceType().getCanonicalType()) {
  9011. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
  9012. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9013. << (unsigned)isObjectArgument << I + 1
  9014. << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
  9015. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9016. return;
  9017. }
  9018. }
  9019. if (BaseToDerivedConversion) {
  9020. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
  9021. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9022. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9023. << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
  9024. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9025. return;
  9026. }
  9027. if (isa<ObjCObjectPointerType>(CFromTy) &&
  9028. isa<PointerType>(CToTy)) {
  9029. Qualifiers FromQs = CFromTy.getQualifiers();
  9030. Qualifiers ToQs = CToTy.getQualifiers();
  9031. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  9032. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
  9033. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9034. << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9035. << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
  9036. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9037. return;
  9038. }
  9039. }
  9040. if (TakingCandidateAddress &&
  9041. !checkAddressOfCandidateIsAvailable(S, Cand->Function))
  9042. return;
  9043. // Emit the generic diagnostic and, optionally, add the hints to it.
  9044. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  9045. FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9046. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9047. << ToTy << (unsigned)isObjectArgument << I + 1
  9048. << (unsigned)(Cand->Fix.Kind);
  9049. // If we can fix the conversion, suggest the FixIts.
  9050. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  9051. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  9052. FDiag << *HI;
  9053. S.Diag(Fn->getLocation(), FDiag);
  9054. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9055. }
  9056. /// Additional arity mismatch diagnosis specific to a function overload
  9057. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  9058. /// over a candidate in any candidate set.
  9059. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  9060. unsigned NumArgs) {
  9061. FunctionDecl *Fn = Cand->Function;
  9062. unsigned MinParams = Fn->getMinRequiredArguments();
  9063. // With invalid overloaded operators, it's possible that we think we
  9064. // have an arity mismatch when in fact it looks like we have the
  9065. // right number of arguments, because only overloaded operators have
  9066. // the weird behavior of overloading member and non-member functions.
  9067. // Just don't report anything.
  9068. if (Fn->isInvalidDecl() &&
  9069. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  9070. return true;
  9071. if (NumArgs < MinParams) {
  9072. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  9073. (Cand->FailureKind == ovl_fail_bad_deduction &&
  9074. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  9075. } else {
  9076. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  9077. (Cand->FailureKind == ovl_fail_bad_deduction &&
  9078. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  9079. }
  9080. return false;
  9081. }
  9082. /// General arity mismatch diagnosis over a candidate in a candidate set.
  9083. static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
  9084. unsigned NumFormalArgs) {
  9085. assert(isa<FunctionDecl>(D) &&
  9086. "The templated declaration should at least be a function"
  9087. " when diagnosing bad template argument deduction due to too many"
  9088. " or too few arguments");
  9089. FunctionDecl *Fn = cast<FunctionDecl>(D);
  9090. // TODO: treat calls to a missing default constructor as a special case
  9091. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  9092. unsigned MinParams = Fn->getMinRequiredArguments();
  9093. // at least / at most / exactly
  9094. unsigned mode, modeCount;
  9095. if (NumFormalArgs < MinParams) {
  9096. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  9097. FnTy->isTemplateVariadic())
  9098. mode = 0; // "at least"
  9099. else
  9100. mode = 2; // "exactly"
  9101. modeCount = MinParams;
  9102. } else {
  9103. if (MinParams != FnTy->getNumParams())
  9104. mode = 1; // "at most"
  9105. else
  9106. mode = 2; // "exactly"
  9107. modeCount = FnTy->getNumParams();
  9108. }
  9109. std::string Description;
  9110. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9111. ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
  9112. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  9113. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
  9114. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9115. << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
  9116. else
  9117. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
  9118. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9119. << Description << mode << modeCount << NumFormalArgs;
  9120. MaybeEmitInheritedConstructorNote(S, Found);
  9121. }
  9122. /// Arity mismatch diagnosis specific to a function overload candidate.
  9123. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  9124. unsigned NumFormalArgs) {
  9125. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  9126. DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
  9127. }
  9128. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  9129. if (TemplateDecl *TD = Templated->getDescribedTemplate())
  9130. return TD;
  9131. llvm_unreachable("Unsupported: Getting the described template declaration"
  9132. " for bad deduction diagnosis");
  9133. }
  9134. /// Diagnose a failed template-argument deduction.
  9135. static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
  9136. DeductionFailureInfo &DeductionFailure,
  9137. unsigned NumArgs,
  9138. bool TakingCandidateAddress) {
  9139. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  9140. NamedDecl *ParamD;
  9141. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  9142. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  9143. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  9144. switch (DeductionFailure.Result) {
  9145. case Sema::TDK_Success:
  9146. llvm_unreachable("TDK_success while diagnosing bad deduction");
  9147. case Sema::TDK_Incomplete: {
  9148. assert(ParamD && "no parameter found for incomplete deduction result");
  9149. S.Diag(Templated->getLocation(),
  9150. diag::note_ovl_candidate_incomplete_deduction)
  9151. << ParamD->getDeclName();
  9152. MaybeEmitInheritedConstructorNote(S, Found);
  9153. return;
  9154. }
  9155. case Sema::TDK_IncompletePack: {
  9156. assert(ParamD && "no parameter found for incomplete deduction result");
  9157. S.Diag(Templated->getLocation(),
  9158. diag::note_ovl_candidate_incomplete_deduction_pack)
  9159. << ParamD->getDeclName()
  9160. << (DeductionFailure.getFirstArg()->pack_size() + 1)
  9161. << *DeductionFailure.getFirstArg();
  9162. MaybeEmitInheritedConstructorNote(S, Found);
  9163. return;
  9164. }
  9165. case Sema::TDK_Underqualified: {
  9166. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  9167. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  9168. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  9169. // Param will have been canonicalized, but it should just be a
  9170. // qualified version of ParamD, so move the qualifiers to that.
  9171. QualifierCollector Qs;
  9172. Qs.strip(Param);
  9173. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  9174. assert(S.Context.hasSameType(Param, NonCanonParam));
  9175. // Arg has also been canonicalized, but there's nothing we can do
  9176. // about that. It also doesn't matter as much, because it won't
  9177. // have any template parameters in it (because deduction isn't
  9178. // done on dependent types).
  9179. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  9180. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  9181. << ParamD->getDeclName() << Arg << NonCanonParam;
  9182. MaybeEmitInheritedConstructorNote(S, Found);
  9183. return;
  9184. }
  9185. case Sema::TDK_Inconsistent: {
  9186. assert(ParamD && "no parameter found for inconsistent deduction result");
  9187. int which = 0;
  9188. if (isa<TemplateTypeParmDecl>(ParamD))
  9189. which = 0;
  9190. else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
  9191. // Deduction might have failed because we deduced arguments of two
  9192. // different types for a non-type template parameter.
  9193. // FIXME: Use a different TDK value for this.
  9194. QualType T1 =
  9195. DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
  9196. QualType T2 =
  9197. DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
  9198. if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
  9199. S.Diag(Templated->getLocation(),
  9200. diag::note_ovl_candidate_inconsistent_deduction_types)
  9201. << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
  9202. << *DeductionFailure.getSecondArg() << T2;
  9203. MaybeEmitInheritedConstructorNote(S, Found);
  9204. return;
  9205. }
  9206. which = 1;
  9207. } else {
  9208. which = 2;
  9209. }
  9210. S.Diag(Templated->getLocation(),
  9211. diag::note_ovl_candidate_inconsistent_deduction)
  9212. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  9213. << *DeductionFailure.getSecondArg();
  9214. MaybeEmitInheritedConstructorNote(S, Found);
  9215. return;
  9216. }
  9217. case Sema::TDK_InvalidExplicitArguments:
  9218. assert(ParamD && "no parameter found for invalid explicit arguments");
  9219. if (ParamD->getDeclName())
  9220. S.Diag(Templated->getLocation(),
  9221. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  9222. << ParamD->getDeclName();
  9223. else {
  9224. int index = 0;
  9225. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  9226. index = TTP->getIndex();
  9227. else if (NonTypeTemplateParmDecl *NTTP
  9228. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  9229. index = NTTP->getIndex();
  9230. else
  9231. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  9232. S.Diag(Templated->getLocation(),
  9233. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  9234. << (index + 1);
  9235. }
  9236. MaybeEmitInheritedConstructorNote(S, Found);
  9237. return;
  9238. case Sema::TDK_TooManyArguments:
  9239. case Sema::TDK_TooFewArguments:
  9240. DiagnoseArityMismatch(S, Found, Templated, NumArgs);
  9241. return;
  9242. case Sema::TDK_InstantiationDepth:
  9243. S.Diag(Templated->getLocation(),
  9244. diag::note_ovl_candidate_instantiation_depth);
  9245. MaybeEmitInheritedConstructorNote(S, Found);
  9246. return;
  9247. case Sema::TDK_SubstitutionFailure: {
  9248. // Format the template argument list into the argument string.
  9249. SmallString<128> TemplateArgString;
  9250. if (TemplateArgumentList *Args =
  9251. DeductionFailure.getTemplateArgumentList()) {
  9252. TemplateArgString = " ";
  9253. TemplateArgString += S.getTemplateArgumentBindingsText(
  9254. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9255. }
  9256. // If this candidate was disabled by enable_if, say so.
  9257. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  9258. if (PDiag && PDiag->second.getDiagID() ==
  9259. diag::err_typename_nested_not_found_enable_if) {
  9260. // FIXME: Use the source range of the condition, and the fully-qualified
  9261. // name of the enable_if template. These are both present in PDiag.
  9262. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  9263. << "'enable_if'" << TemplateArgString;
  9264. return;
  9265. }
  9266. // We found a specific requirement that disabled the enable_if.
  9267. if (PDiag && PDiag->second.getDiagID() ==
  9268. diag::err_typename_nested_not_found_requirement) {
  9269. S.Diag(Templated->getLocation(),
  9270. diag::note_ovl_candidate_disabled_by_requirement)
  9271. << PDiag->second.getStringArg(0) << TemplateArgString;
  9272. return;
  9273. }
  9274. // Format the SFINAE diagnostic into the argument string.
  9275. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  9276. // formatted message in another diagnostic.
  9277. SmallString<128> SFINAEArgString;
  9278. SourceRange R;
  9279. if (PDiag) {
  9280. SFINAEArgString = ": ";
  9281. R = SourceRange(PDiag->first, PDiag->first);
  9282. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  9283. }
  9284. S.Diag(Templated->getLocation(),
  9285. diag::note_ovl_candidate_substitution_failure)
  9286. << TemplateArgString << SFINAEArgString << R;
  9287. MaybeEmitInheritedConstructorNote(S, Found);
  9288. return;
  9289. }
  9290. case Sema::TDK_DeducedMismatch:
  9291. case Sema::TDK_DeducedMismatchNested: {
  9292. // Format the template argument list into the argument string.
  9293. SmallString<128> TemplateArgString;
  9294. if (TemplateArgumentList *Args =
  9295. DeductionFailure.getTemplateArgumentList()) {
  9296. TemplateArgString = " ";
  9297. TemplateArgString += S.getTemplateArgumentBindingsText(
  9298. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9299. }
  9300. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
  9301. << (*DeductionFailure.getCallArgIndex() + 1)
  9302. << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
  9303. << TemplateArgString
  9304. << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
  9305. break;
  9306. }
  9307. case Sema::TDK_NonDeducedMismatch: {
  9308. // FIXME: Provide a source location to indicate what we couldn't match.
  9309. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  9310. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  9311. if (FirstTA.getKind() == TemplateArgument::Template &&
  9312. SecondTA.getKind() == TemplateArgument::Template) {
  9313. TemplateName FirstTN = FirstTA.getAsTemplate();
  9314. TemplateName SecondTN = SecondTA.getAsTemplate();
  9315. if (FirstTN.getKind() == TemplateName::Template &&
  9316. SecondTN.getKind() == TemplateName::Template) {
  9317. if (FirstTN.getAsTemplateDecl()->getName() ==
  9318. SecondTN.getAsTemplateDecl()->getName()) {
  9319. // FIXME: This fixes a bad diagnostic where both templates are named
  9320. // the same. This particular case is a bit difficult since:
  9321. // 1) It is passed as a string to the diagnostic printer.
  9322. // 2) The diagnostic printer only attempts to find a better
  9323. // name for types, not decls.
  9324. // Ideally, this should folded into the diagnostic printer.
  9325. S.Diag(Templated->getLocation(),
  9326. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  9327. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  9328. return;
  9329. }
  9330. }
  9331. }
  9332. if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
  9333. !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
  9334. return;
  9335. // FIXME: For generic lambda parameters, check if the function is a lambda
  9336. // call operator, and if so, emit a prettier and more informative
  9337. // diagnostic that mentions 'auto' and lambda in addition to
  9338. // (or instead of?) the canonical template type parameters.
  9339. S.Diag(Templated->getLocation(),
  9340. diag::note_ovl_candidate_non_deduced_mismatch)
  9341. << FirstTA << SecondTA;
  9342. return;
  9343. }
  9344. // TODO: diagnose these individually, then kill off
  9345. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  9346. case Sema::TDK_MiscellaneousDeductionFailure:
  9347. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  9348. MaybeEmitInheritedConstructorNote(S, Found);
  9349. return;
  9350. case Sema::TDK_CUDATargetMismatch:
  9351. S.Diag(Templated->getLocation(),
  9352. diag::note_cuda_ovl_candidate_target_mismatch);
  9353. return;
  9354. }
  9355. }
  9356. /// Diagnose a failed template-argument deduction, for function calls.
  9357. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  9358. unsigned NumArgs,
  9359. bool TakingCandidateAddress) {
  9360. unsigned TDK = Cand->DeductionFailure.Result;
  9361. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  9362. if (CheckArityMismatch(S, Cand, NumArgs))
  9363. return;
  9364. }
  9365. DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
  9366. Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
  9367. }
  9368. /// CUDA: diagnose an invalid call across targets.
  9369. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  9370. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  9371. FunctionDecl *Callee = Cand->Function;
  9372. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  9373. CalleeTarget = S.IdentifyCUDATarget(Callee);
  9374. std::string FnDesc;
  9375. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9376. ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, Cand->RewriteKind,
  9377. FnDesc);
  9378. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  9379. << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
  9380. << FnDesc /* Ignored */
  9381. << CalleeTarget << CallerTarget;
  9382. // This could be an implicit constructor for which we could not infer the
  9383. // target due to a collsion. Diagnose that case.
  9384. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  9385. if (Meth != nullptr && Meth->isImplicit()) {
  9386. CXXRecordDecl *ParentClass = Meth->getParent();
  9387. Sema::CXXSpecialMember CSM;
  9388. switch (FnKindPair.first) {
  9389. default:
  9390. return;
  9391. case oc_implicit_default_constructor:
  9392. CSM = Sema::CXXDefaultConstructor;
  9393. break;
  9394. case oc_implicit_copy_constructor:
  9395. CSM = Sema::CXXCopyConstructor;
  9396. break;
  9397. case oc_implicit_move_constructor:
  9398. CSM = Sema::CXXMoveConstructor;
  9399. break;
  9400. case oc_implicit_copy_assignment:
  9401. CSM = Sema::CXXCopyAssignment;
  9402. break;
  9403. case oc_implicit_move_assignment:
  9404. CSM = Sema::CXXMoveAssignment;
  9405. break;
  9406. };
  9407. bool ConstRHS = false;
  9408. if (Meth->getNumParams()) {
  9409. if (const ReferenceType *RT =
  9410. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  9411. ConstRHS = RT->getPointeeType().isConstQualified();
  9412. }
  9413. }
  9414. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  9415. /* ConstRHS */ ConstRHS,
  9416. /* Diagnose */ true);
  9417. }
  9418. }
  9419. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  9420. FunctionDecl *Callee = Cand->Function;
  9421. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  9422. S.Diag(Callee->getLocation(),
  9423. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  9424. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  9425. }
  9426. static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
  9427. ExplicitSpecifier ES;
  9428. const char *DeclName;
  9429. switch (Cand->Function->getDeclKind()) {
  9430. case Decl::Kind::CXXConstructor:
  9431. ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
  9432. DeclName = "constructor";
  9433. break;
  9434. case Decl::Kind::CXXConversion:
  9435. ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
  9436. DeclName = "conversion operator";
  9437. break;
  9438. case Decl::Kind::CXXDeductionGuide:
  9439. ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
  9440. DeclName = "deductiong guide";
  9441. break;
  9442. default:
  9443. llvm_unreachable("invalid Decl");
  9444. }
  9445. assert(ES.getExpr() && "null expression should be handled before");
  9446. S.Diag(Cand->Function->getLocation(),
  9447. diag::note_ovl_candidate_explicit_forbidden)
  9448. << DeclName;
  9449. S.Diag(ES.getExpr()->getBeginLoc(),
  9450. diag::note_explicit_bool_resolved_to_true);
  9451. }
  9452. static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
  9453. FunctionDecl *Callee = Cand->Function;
  9454. S.Diag(Callee->getLocation(),
  9455. diag::note_ovl_candidate_disabled_by_extension)
  9456. << S.getOpenCLExtensionsFromDeclExtMap(Callee);
  9457. }
  9458. /// Generates a 'note' diagnostic for an overload candidate. We've
  9459. /// already generated a primary error at the call site.
  9460. ///
  9461. /// It really does need to be a single diagnostic with its caret
  9462. /// pointed at the candidate declaration. Yes, this creates some
  9463. /// major challenges of technical writing. Yes, this makes pointing
  9464. /// out problems with specific arguments quite awkward. It's still
  9465. /// better than generating twenty screens of text for every failed
  9466. /// overload.
  9467. ///
  9468. /// It would be great to be able to express per-candidate problems
  9469. /// more richly for those diagnostic clients that cared, but we'd
  9470. /// still have to be just as careful with the default diagnostics.
  9471. /// \param CtorDestAS Addr space of object being constructed (for ctor
  9472. /// candidates only).
  9473. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  9474. unsigned NumArgs,
  9475. bool TakingCandidateAddress,
  9476. LangAS CtorDestAS = LangAS::Default) {
  9477. FunctionDecl *Fn = Cand->Function;
  9478. // Note deleted candidates, but only if they're viable.
  9479. if (Cand->Viable) {
  9480. if (Fn->isDeleted()) {
  9481. std::string FnDesc;
  9482. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9483. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind,
  9484. FnDesc);
  9485. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  9486. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9487. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  9488. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9489. return;
  9490. }
  9491. // We don't really have anything else to say about viable candidates.
  9492. S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind);
  9493. return;
  9494. }
  9495. switch (Cand->FailureKind) {
  9496. case ovl_fail_too_many_arguments:
  9497. case ovl_fail_too_few_arguments:
  9498. return DiagnoseArityMismatch(S, Cand, NumArgs);
  9499. case ovl_fail_bad_deduction:
  9500. return DiagnoseBadDeduction(S, Cand, NumArgs,
  9501. TakingCandidateAddress);
  9502. case ovl_fail_illegal_constructor: {
  9503. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  9504. << (Fn->getPrimaryTemplate() ? 1 : 0);
  9505. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9506. return;
  9507. }
  9508. case ovl_fail_object_addrspace_mismatch: {
  9509. Qualifiers QualsForPrinting;
  9510. QualsForPrinting.setAddressSpace(CtorDestAS);
  9511. S.Diag(Fn->getLocation(),
  9512. diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
  9513. << QualsForPrinting;
  9514. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9515. return;
  9516. }
  9517. case ovl_fail_trivial_conversion:
  9518. case ovl_fail_bad_final_conversion:
  9519. case ovl_fail_final_conversion_not_exact:
  9520. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind);
  9521. case ovl_fail_bad_conversion: {
  9522. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  9523. for (unsigned N = Cand->Conversions.size(); I != N; ++I)
  9524. if (Cand->Conversions[I].isBad())
  9525. return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
  9526. // FIXME: this currently happens when we're called from SemaInit
  9527. // when user-conversion overload fails. Figure out how to handle
  9528. // those conditions and diagnose them well.
  9529. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind);
  9530. }
  9531. case ovl_fail_bad_target:
  9532. return DiagnoseBadTarget(S, Cand);
  9533. case ovl_fail_enable_if:
  9534. return DiagnoseFailedEnableIfAttr(S, Cand);
  9535. case ovl_fail_explicit_resolved:
  9536. return DiagnoseFailedExplicitSpec(S, Cand);
  9537. case ovl_fail_ext_disabled:
  9538. return DiagnoseOpenCLExtensionDisabled(S, Cand);
  9539. case ovl_fail_inhctor_slice:
  9540. // It's generally not interesting to note copy/move constructors here.
  9541. if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
  9542. return;
  9543. S.Diag(Fn->getLocation(),
  9544. diag::note_ovl_candidate_inherited_constructor_slice)
  9545. << (Fn->getPrimaryTemplate() ? 1 : 0)
  9546. << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
  9547. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9548. return;
  9549. case ovl_fail_addr_not_available: {
  9550. bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
  9551. (void)Available;
  9552. assert(!Available);
  9553. break;
  9554. }
  9555. case ovl_non_default_multiversion_function:
  9556. // Do nothing, these should simply be ignored.
  9557. break;
  9558. }
  9559. }
  9560. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  9561. // Desugar the type of the surrogate down to a function type,
  9562. // retaining as many typedefs as possible while still showing
  9563. // the function type (and, therefore, its parameter types).
  9564. QualType FnType = Cand->Surrogate->getConversionType();
  9565. bool isLValueReference = false;
  9566. bool isRValueReference = false;
  9567. bool isPointer = false;
  9568. if (const LValueReferenceType *FnTypeRef =
  9569. FnType->getAs<LValueReferenceType>()) {
  9570. FnType = FnTypeRef->getPointeeType();
  9571. isLValueReference = true;
  9572. } else if (const RValueReferenceType *FnTypeRef =
  9573. FnType->getAs<RValueReferenceType>()) {
  9574. FnType = FnTypeRef->getPointeeType();
  9575. isRValueReference = true;
  9576. }
  9577. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  9578. FnType = FnTypePtr->getPointeeType();
  9579. isPointer = true;
  9580. }
  9581. // Desugar down to a function type.
  9582. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  9583. // Reconstruct the pointer/reference as appropriate.
  9584. if (isPointer) FnType = S.Context.getPointerType(FnType);
  9585. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  9586. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  9587. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  9588. << FnType;
  9589. }
  9590. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  9591. SourceLocation OpLoc,
  9592. OverloadCandidate *Cand) {
  9593. assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
  9594. std::string TypeStr("operator");
  9595. TypeStr += Opc;
  9596. TypeStr += "(";
  9597. TypeStr += Cand->BuiltinParamTypes[0].getAsString();
  9598. if (Cand->Conversions.size() == 1) {
  9599. TypeStr += ")";
  9600. S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
  9601. } else {
  9602. TypeStr += ", ";
  9603. TypeStr += Cand->BuiltinParamTypes[1].getAsString();
  9604. TypeStr += ")";
  9605. S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
  9606. }
  9607. }
  9608. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  9609. OverloadCandidate *Cand) {
  9610. for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
  9611. if (ICS.isBad()) break; // all meaningless after first invalid
  9612. if (!ICS.isAmbiguous()) continue;
  9613. ICS.DiagnoseAmbiguousConversion(
  9614. S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
  9615. }
  9616. }
  9617. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  9618. if (Cand->Function)
  9619. return Cand->Function->getLocation();
  9620. if (Cand->IsSurrogate)
  9621. return Cand->Surrogate->getLocation();
  9622. return SourceLocation();
  9623. }
  9624. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  9625. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  9626. case Sema::TDK_Success:
  9627. case Sema::TDK_NonDependentConversionFailure:
  9628. llvm_unreachable("non-deduction failure while diagnosing bad deduction");
  9629. case Sema::TDK_Invalid:
  9630. case Sema::TDK_Incomplete:
  9631. case Sema::TDK_IncompletePack:
  9632. return 1;
  9633. case Sema::TDK_Underqualified:
  9634. case Sema::TDK_Inconsistent:
  9635. return 2;
  9636. case Sema::TDK_SubstitutionFailure:
  9637. case Sema::TDK_DeducedMismatch:
  9638. case Sema::TDK_DeducedMismatchNested:
  9639. case Sema::TDK_NonDeducedMismatch:
  9640. case Sema::TDK_MiscellaneousDeductionFailure:
  9641. case Sema::TDK_CUDATargetMismatch:
  9642. return 3;
  9643. case Sema::TDK_InstantiationDepth:
  9644. return 4;
  9645. case Sema::TDK_InvalidExplicitArguments:
  9646. return 5;
  9647. case Sema::TDK_TooManyArguments:
  9648. case Sema::TDK_TooFewArguments:
  9649. return 6;
  9650. }
  9651. llvm_unreachable("Unhandled deduction result");
  9652. }
  9653. namespace {
  9654. struct CompareOverloadCandidatesForDisplay {
  9655. Sema &S;
  9656. SourceLocation Loc;
  9657. size_t NumArgs;
  9658. OverloadCandidateSet::CandidateSetKind CSK;
  9659. CompareOverloadCandidatesForDisplay(
  9660. Sema &S, SourceLocation Loc, size_t NArgs,
  9661. OverloadCandidateSet::CandidateSetKind CSK)
  9662. : S(S), NumArgs(NArgs), CSK(CSK) {}
  9663. bool operator()(const OverloadCandidate *L,
  9664. const OverloadCandidate *R) {
  9665. // Fast-path this check.
  9666. if (L == R) return false;
  9667. // Order first by viability.
  9668. if (L->Viable) {
  9669. if (!R->Viable) return true;
  9670. // TODO: introduce a tri-valued comparison for overload
  9671. // candidates. Would be more worthwhile if we had a sort
  9672. // that could exploit it.
  9673. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
  9674. return true;
  9675. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
  9676. return false;
  9677. } else if (R->Viable)
  9678. return false;
  9679. assert(L->Viable == R->Viable);
  9680. // Criteria by which we can sort non-viable candidates:
  9681. if (!L->Viable) {
  9682. // 1. Arity mismatches come after other candidates.
  9683. if (L->FailureKind == ovl_fail_too_many_arguments ||
  9684. L->FailureKind == ovl_fail_too_few_arguments) {
  9685. if (R->FailureKind == ovl_fail_too_many_arguments ||
  9686. R->FailureKind == ovl_fail_too_few_arguments) {
  9687. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  9688. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  9689. if (LDist == RDist) {
  9690. if (L->FailureKind == R->FailureKind)
  9691. // Sort non-surrogates before surrogates.
  9692. return !L->IsSurrogate && R->IsSurrogate;
  9693. // Sort candidates requiring fewer parameters than there were
  9694. // arguments given after candidates requiring more parameters
  9695. // than there were arguments given.
  9696. return L->FailureKind == ovl_fail_too_many_arguments;
  9697. }
  9698. return LDist < RDist;
  9699. }
  9700. return false;
  9701. }
  9702. if (R->FailureKind == ovl_fail_too_many_arguments ||
  9703. R->FailureKind == ovl_fail_too_few_arguments)
  9704. return true;
  9705. // 2. Bad conversions come first and are ordered by the number
  9706. // of bad conversions and quality of good conversions.
  9707. if (L->FailureKind == ovl_fail_bad_conversion) {
  9708. if (R->FailureKind != ovl_fail_bad_conversion)
  9709. return true;
  9710. // The conversion that can be fixed with a smaller number of changes,
  9711. // comes first.
  9712. unsigned numLFixes = L->Fix.NumConversionsFixed;
  9713. unsigned numRFixes = R->Fix.NumConversionsFixed;
  9714. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  9715. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  9716. if (numLFixes != numRFixes) {
  9717. return numLFixes < numRFixes;
  9718. }
  9719. // If there's any ordering between the defined conversions...
  9720. // FIXME: this might not be transitive.
  9721. assert(L->Conversions.size() == R->Conversions.size());
  9722. int leftBetter = 0;
  9723. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  9724. for (unsigned E = L->Conversions.size(); I != E; ++I) {
  9725. switch (CompareImplicitConversionSequences(S, Loc,
  9726. L->Conversions[I],
  9727. R->Conversions[I])) {
  9728. case ImplicitConversionSequence::Better:
  9729. leftBetter++;
  9730. break;
  9731. case ImplicitConversionSequence::Worse:
  9732. leftBetter--;
  9733. break;
  9734. case ImplicitConversionSequence::Indistinguishable:
  9735. break;
  9736. }
  9737. }
  9738. if (leftBetter > 0) return true;
  9739. if (leftBetter < 0) return false;
  9740. } else if (R->FailureKind == ovl_fail_bad_conversion)
  9741. return false;
  9742. if (L->FailureKind == ovl_fail_bad_deduction) {
  9743. if (R->FailureKind != ovl_fail_bad_deduction)
  9744. return true;
  9745. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  9746. return RankDeductionFailure(L->DeductionFailure)
  9747. < RankDeductionFailure(R->DeductionFailure);
  9748. } else if (R->FailureKind == ovl_fail_bad_deduction)
  9749. return false;
  9750. // TODO: others?
  9751. }
  9752. // Sort everything else by location.
  9753. SourceLocation LLoc = GetLocationForCandidate(L);
  9754. SourceLocation RLoc = GetLocationForCandidate(R);
  9755. // Put candidates without locations (e.g. builtins) at the end.
  9756. if (LLoc.isInvalid()) return false;
  9757. if (RLoc.isInvalid()) return true;
  9758. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  9759. }
  9760. };
  9761. }
  9762. /// CompleteNonViableCandidate - Normally, overload resolution only
  9763. /// computes up to the first bad conversion. Produces the FixIt set if
  9764. /// possible.
  9765. static void
  9766. CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  9767. ArrayRef<Expr *> Args,
  9768. OverloadCandidateSet::CandidateSetKind CSK) {
  9769. assert(!Cand->Viable);
  9770. // Don't do anything on failures other than bad conversion.
  9771. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  9772. // We only want the FixIts if all the arguments can be corrected.
  9773. bool Unfixable = false;
  9774. // Use a implicit copy initialization to check conversion fixes.
  9775. Cand->Fix.setConversionChecker(TryCopyInitialization);
  9776. // Attempt to fix the bad conversion.
  9777. unsigned ConvCount = Cand->Conversions.size();
  9778. for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
  9779. ++ConvIdx) {
  9780. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  9781. if (Cand->Conversions[ConvIdx].isInitialized() &&
  9782. Cand->Conversions[ConvIdx].isBad()) {
  9783. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  9784. break;
  9785. }
  9786. }
  9787. // FIXME: this should probably be preserved from the overload
  9788. // operation somehow.
  9789. bool SuppressUserConversions = false;
  9790. unsigned ConvIdx = 0;
  9791. unsigned ArgIdx = 0;
  9792. ArrayRef<QualType> ParamTypes;
  9793. if (Cand->IsSurrogate) {
  9794. QualType ConvType
  9795. = Cand->Surrogate->getConversionType().getNonReferenceType();
  9796. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  9797. ConvType = ConvPtrType->getPointeeType();
  9798. ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
  9799. // Conversion 0 is 'this', which doesn't have a corresponding parameter.
  9800. ConvIdx = 1;
  9801. } else if (Cand->Function) {
  9802. ParamTypes =
  9803. Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
  9804. if (isa<CXXMethodDecl>(Cand->Function) &&
  9805. !isa<CXXConstructorDecl>(Cand->Function)) {
  9806. // Conversion 0 is 'this', which doesn't have a corresponding parameter.
  9807. ConvIdx = 1;
  9808. if (CSK == OverloadCandidateSet::CSK_Operator)
  9809. // Argument 0 is 'this', which doesn't have a corresponding parameter.
  9810. ArgIdx = 1;
  9811. }
  9812. } else {
  9813. // Builtin operator.
  9814. assert(ConvCount <= 3);
  9815. ParamTypes = Cand->BuiltinParamTypes;
  9816. }
  9817. // Fill in the rest of the conversions.
  9818. bool Reversed = Cand->RewriteKind & CRK_Reversed;
  9819. for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
  9820. ConvIdx != ConvCount;
  9821. ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
  9822. if (Cand->Conversions[ConvIdx].isInitialized()) {
  9823. // We've already checked this conversion.
  9824. } else if (ArgIdx < ParamTypes.size()) {
  9825. if (ParamTypes[ParamIdx]->isDependentType())
  9826. Cand->Conversions[ConvIdx].setAsIdentityConversion(
  9827. Args[ArgIdx]->getType());
  9828. else {
  9829. Cand->Conversions[ConvIdx] =
  9830. TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
  9831. SuppressUserConversions,
  9832. /*InOverloadResolution=*/true,
  9833. /*AllowObjCWritebackConversion=*/
  9834. S.getLangOpts().ObjCAutoRefCount);
  9835. // Store the FixIt in the candidate if it exists.
  9836. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  9837. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  9838. }
  9839. } else
  9840. Cand->Conversions[ConvIdx].setEllipsis();
  9841. }
  9842. }
  9843. SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
  9844. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  9845. SourceLocation OpLoc,
  9846. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  9847. // Sort the candidates by viability and position. Sorting directly would
  9848. // be prohibitive, so we make a set of pointers and sort those.
  9849. SmallVector<OverloadCandidate*, 32> Cands;
  9850. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  9851. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  9852. if (!Filter(*Cand))
  9853. continue;
  9854. if (Cand->Viable)
  9855. Cands.push_back(Cand);
  9856. else if (OCD == OCD_AllCandidates) {
  9857. CompleteNonViableCandidate(S, Cand, Args, Kind);
  9858. if (Cand->Function || Cand->IsSurrogate)
  9859. Cands.push_back(Cand);
  9860. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  9861. // want to list every possible builtin candidate.
  9862. }
  9863. }
  9864. llvm::stable_sort(
  9865. Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
  9866. return Cands;
  9867. }
  9868. /// When overload resolution fails, prints diagnostic messages containing the
  9869. /// candidates in the candidate set.
  9870. void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
  9871. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  9872. StringRef Opc, SourceLocation OpLoc,
  9873. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  9874. auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
  9875. S.Diag(PD.first, PD.second);
  9876. NoteCandidates(S, Args, Cands, Opc, OpLoc);
  9877. }
  9878. void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
  9879. ArrayRef<OverloadCandidate *> Cands,
  9880. StringRef Opc, SourceLocation OpLoc) {
  9881. bool ReportedAmbiguousConversions = false;
  9882. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  9883. unsigned CandsShown = 0;
  9884. auto I = Cands.begin(), E = Cands.end();
  9885. for (; I != E; ++I) {
  9886. OverloadCandidate *Cand = *I;
  9887. // Set an arbitrary limit on the number of candidate functions we'll spam
  9888. // the user with. FIXME: This limit should depend on details of the
  9889. // candidate list.
  9890. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  9891. break;
  9892. }
  9893. ++CandsShown;
  9894. if (Cand->Function)
  9895. NoteFunctionCandidate(S, Cand, Args.size(),
  9896. /*TakingCandidateAddress=*/false, DestAS);
  9897. else if (Cand->IsSurrogate)
  9898. NoteSurrogateCandidate(S, Cand);
  9899. else {
  9900. assert(Cand->Viable &&
  9901. "Non-viable built-in candidates are not added to Cands.");
  9902. // Generally we only see ambiguities including viable builtin
  9903. // operators if overload resolution got screwed up by an
  9904. // ambiguous user-defined conversion.
  9905. //
  9906. // FIXME: It's quite possible for different conversions to see
  9907. // different ambiguities, though.
  9908. if (!ReportedAmbiguousConversions) {
  9909. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  9910. ReportedAmbiguousConversions = true;
  9911. }
  9912. // If this is a viable builtin, print it.
  9913. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  9914. }
  9915. }
  9916. if (I != E)
  9917. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  9918. }
  9919. static SourceLocation
  9920. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  9921. return Cand->Specialization ? Cand->Specialization->getLocation()
  9922. : SourceLocation();
  9923. }
  9924. namespace {
  9925. struct CompareTemplateSpecCandidatesForDisplay {
  9926. Sema &S;
  9927. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  9928. bool operator()(const TemplateSpecCandidate *L,
  9929. const TemplateSpecCandidate *R) {
  9930. // Fast-path this check.
  9931. if (L == R)
  9932. return false;
  9933. // Assuming that both candidates are not matches...
  9934. // Sort by the ranking of deduction failures.
  9935. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  9936. return RankDeductionFailure(L->DeductionFailure) <
  9937. RankDeductionFailure(R->DeductionFailure);
  9938. // Sort everything else by location.
  9939. SourceLocation LLoc = GetLocationForCandidate(L);
  9940. SourceLocation RLoc = GetLocationForCandidate(R);
  9941. // Put candidates without locations (e.g. builtins) at the end.
  9942. if (LLoc.isInvalid())
  9943. return false;
  9944. if (RLoc.isInvalid())
  9945. return true;
  9946. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  9947. }
  9948. };
  9949. }
  9950. /// Diagnose a template argument deduction failure.
  9951. /// We are treating these failures as overload failures due to bad
  9952. /// deductions.
  9953. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
  9954. bool ForTakingAddress) {
  9955. DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
  9956. DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
  9957. }
  9958. void TemplateSpecCandidateSet::destroyCandidates() {
  9959. for (iterator i = begin(), e = end(); i != e; ++i) {
  9960. i->DeductionFailure.Destroy();
  9961. }
  9962. }
  9963. void TemplateSpecCandidateSet::clear() {
  9964. destroyCandidates();
  9965. Candidates.clear();
  9966. }
  9967. /// NoteCandidates - When no template specialization match is found, prints
  9968. /// diagnostic messages containing the non-matching specializations that form
  9969. /// the candidate set.
  9970. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  9971. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  9972. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  9973. // Sort the candidates by position (assuming no candidate is a match).
  9974. // Sorting directly would be prohibitive, so we make a set of pointers
  9975. // and sort those.
  9976. SmallVector<TemplateSpecCandidate *, 32> Cands;
  9977. Cands.reserve(size());
  9978. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  9979. if (Cand->Specialization)
  9980. Cands.push_back(Cand);
  9981. // Otherwise, this is a non-matching builtin candidate. We do not,
  9982. // in general, want to list every possible builtin candidate.
  9983. }
  9984. llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
  9985. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  9986. // for generalization purposes (?).
  9987. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  9988. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  9989. unsigned CandsShown = 0;
  9990. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  9991. TemplateSpecCandidate *Cand = *I;
  9992. // Set an arbitrary limit on the number of candidates we'll spam
  9993. // the user with. FIXME: This limit should depend on details of the
  9994. // candidate list.
  9995. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  9996. break;
  9997. ++CandsShown;
  9998. assert(Cand->Specialization &&
  9999. "Non-matching built-in candidates are not added to Cands.");
  10000. Cand->NoteDeductionFailure(S, ForTakingAddress);
  10001. }
  10002. if (I != E)
  10003. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  10004. }
  10005. // [PossiblyAFunctionType] --> [Return]
  10006. // NonFunctionType --> NonFunctionType
  10007. // R (A) --> R(A)
  10008. // R (*)(A) --> R (A)
  10009. // R (&)(A) --> R (A)
  10010. // R (S::*)(A) --> R (A)
  10011. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  10012. QualType Ret = PossiblyAFunctionType;
  10013. if (const PointerType *ToTypePtr =
  10014. PossiblyAFunctionType->getAs<PointerType>())
  10015. Ret = ToTypePtr->getPointeeType();
  10016. else if (const ReferenceType *ToTypeRef =
  10017. PossiblyAFunctionType->getAs<ReferenceType>())
  10018. Ret = ToTypeRef->getPointeeType();
  10019. else if (const MemberPointerType *MemTypePtr =
  10020. PossiblyAFunctionType->getAs<MemberPointerType>())
  10021. Ret = MemTypePtr->getPointeeType();
  10022. Ret =
  10023. Context.getCanonicalType(Ret).getUnqualifiedType();
  10024. return Ret;
  10025. }
  10026. static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
  10027. bool Complain = true) {
  10028. if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  10029. S.DeduceReturnType(FD, Loc, Complain))
  10030. return true;
  10031. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  10032. if (S.getLangOpts().CPlusPlus17 &&
  10033. isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  10034. !S.ResolveExceptionSpec(Loc, FPT))
  10035. return true;
  10036. return false;
  10037. }
  10038. namespace {
  10039. // A helper class to help with address of function resolution
  10040. // - allows us to avoid passing around all those ugly parameters
  10041. class AddressOfFunctionResolver {
  10042. Sema& S;
  10043. Expr* SourceExpr;
  10044. const QualType& TargetType;
  10045. QualType TargetFunctionType; // Extracted function type from target type
  10046. bool Complain;
  10047. //DeclAccessPair& ResultFunctionAccessPair;
  10048. ASTContext& Context;
  10049. bool TargetTypeIsNonStaticMemberFunction;
  10050. bool FoundNonTemplateFunction;
  10051. bool StaticMemberFunctionFromBoundPointer;
  10052. bool HasComplained;
  10053. OverloadExpr::FindResult OvlExprInfo;
  10054. OverloadExpr *OvlExpr;
  10055. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  10056. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  10057. TemplateSpecCandidateSet FailedCandidates;
  10058. public:
  10059. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  10060. const QualType &TargetType, bool Complain)
  10061. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  10062. Complain(Complain), Context(S.getASTContext()),
  10063. TargetTypeIsNonStaticMemberFunction(
  10064. !!TargetType->getAs<MemberPointerType>()),
  10065. FoundNonTemplateFunction(false),
  10066. StaticMemberFunctionFromBoundPointer(false),
  10067. HasComplained(false),
  10068. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  10069. OvlExpr(OvlExprInfo.Expression),
  10070. FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
  10071. ExtractUnqualifiedFunctionTypeFromTargetType();
  10072. if (TargetFunctionType->isFunctionType()) {
  10073. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  10074. if (!UME->isImplicitAccess() &&
  10075. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  10076. StaticMemberFunctionFromBoundPointer = true;
  10077. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  10078. DeclAccessPair dap;
  10079. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  10080. OvlExpr, false, &dap)) {
  10081. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  10082. if (!Method->isStatic()) {
  10083. // If the target type is a non-function type and the function found
  10084. // is a non-static member function, pretend as if that was the
  10085. // target, it's the only possible type to end up with.
  10086. TargetTypeIsNonStaticMemberFunction = true;
  10087. // And skip adding the function if its not in the proper form.
  10088. // We'll diagnose this due to an empty set of functions.
  10089. if (!OvlExprInfo.HasFormOfMemberPointer)
  10090. return;
  10091. }
  10092. Matches.push_back(std::make_pair(dap, Fn));
  10093. }
  10094. return;
  10095. }
  10096. if (OvlExpr->hasExplicitTemplateArgs())
  10097. OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
  10098. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  10099. // C++ [over.over]p4:
  10100. // If more than one function is selected, [...]
  10101. if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
  10102. if (FoundNonTemplateFunction)
  10103. EliminateAllTemplateMatches();
  10104. else
  10105. EliminateAllExceptMostSpecializedTemplate();
  10106. }
  10107. }
  10108. if (S.getLangOpts().CUDA && Matches.size() > 1)
  10109. EliminateSuboptimalCudaMatches();
  10110. }
  10111. bool hasComplained() const { return HasComplained; }
  10112. private:
  10113. bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
  10114. QualType Discard;
  10115. return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
  10116. S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
  10117. }
  10118. /// \return true if A is considered a better overload candidate for the
  10119. /// desired type than B.
  10120. bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
  10121. // If A doesn't have exactly the correct type, we don't want to classify it
  10122. // as "better" than anything else. This way, the user is required to
  10123. // disambiguate for us if there are multiple candidates and no exact match.
  10124. return candidateHasExactlyCorrectType(A) &&
  10125. (!candidateHasExactlyCorrectType(B) ||
  10126. compareEnableIfAttrs(S, A, B) == Comparison::Better);
  10127. }
  10128. /// \return true if we were able to eliminate all but one overload candidate,
  10129. /// false otherwise.
  10130. bool eliminiateSuboptimalOverloadCandidates() {
  10131. // Same algorithm as overload resolution -- one pass to pick the "best",
  10132. // another pass to be sure that nothing is better than the best.
  10133. auto Best = Matches.begin();
  10134. for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
  10135. if (isBetterCandidate(I->second, Best->second))
  10136. Best = I;
  10137. const FunctionDecl *BestFn = Best->second;
  10138. auto IsBestOrInferiorToBest = [this, BestFn](
  10139. const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
  10140. return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
  10141. };
  10142. // Note: We explicitly leave Matches unmodified if there isn't a clear best
  10143. // option, so we can potentially give the user a better error
  10144. if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
  10145. return false;
  10146. Matches[0] = *Best;
  10147. Matches.resize(1);
  10148. return true;
  10149. }
  10150. bool isTargetTypeAFunction() const {
  10151. return TargetFunctionType->isFunctionType();
  10152. }
  10153. // [ToType] [Return]
  10154. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  10155. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  10156. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  10157. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  10158. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  10159. }
  10160. // return true if any matching specializations were found
  10161. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  10162. const DeclAccessPair& CurAccessFunPair) {
  10163. if (CXXMethodDecl *Method
  10164. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  10165. // Skip non-static function templates when converting to pointer, and
  10166. // static when converting to member pointer.
  10167. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  10168. return false;
  10169. }
  10170. else if (TargetTypeIsNonStaticMemberFunction)
  10171. return false;
  10172. // C++ [over.over]p2:
  10173. // If the name is a function template, template argument deduction is
  10174. // done (14.8.2.2), and if the argument deduction succeeds, the
  10175. // resulting template argument list is used to generate a single
  10176. // function template specialization, which is added to the set of
  10177. // overloaded functions considered.
  10178. FunctionDecl *Specialization = nullptr;
  10179. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  10180. if (Sema::TemplateDeductionResult Result
  10181. = S.DeduceTemplateArguments(FunctionTemplate,
  10182. &OvlExplicitTemplateArgs,
  10183. TargetFunctionType, Specialization,
  10184. Info, /*IsAddressOfFunction*/true)) {
  10185. // Make a note of the failed deduction for diagnostics.
  10186. FailedCandidates.addCandidate()
  10187. .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
  10188. MakeDeductionFailureInfo(Context, Result, Info));
  10189. return false;
  10190. }
  10191. // Template argument deduction ensures that we have an exact match or
  10192. // compatible pointer-to-function arguments that would be adjusted by ICS.
  10193. // This function template specicalization works.
  10194. assert(S.isSameOrCompatibleFunctionType(
  10195. Context.getCanonicalType(Specialization->getType()),
  10196. Context.getCanonicalType(TargetFunctionType)));
  10197. if (!S.checkAddressOfFunctionIsAvailable(Specialization))
  10198. return false;
  10199. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  10200. return true;
  10201. }
  10202. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  10203. const DeclAccessPair& CurAccessFunPair) {
  10204. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  10205. // Skip non-static functions when converting to pointer, and static
  10206. // when converting to member pointer.
  10207. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  10208. return false;
  10209. }
  10210. else if (TargetTypeIsNonStaticMemberFunction)
  10211. return false;
  10212. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  10213. if (S.getLangOpts().CUDA)
  10214. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  10215. if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
  10216. return false;
  10217. if (FunDecl->isMultiVersion()) {
  10218. const auto *TA = FunDecl->getAttr<TargetAttr>();
  10219. if (TA && !TA->isDefaultVersion())
  10220. return false;
  10221. }
  10222. // If any candidate has a placeholder return type, trigger its deduction
  10223. // now.
  10224. if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
  10225. Complain)) {
  10226. HasComplained |= Complain;
  10227. return false;
  10228. }
  10229. if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
  10230. return false;
  10231. // If we're in C, we need to support types that aren't exactly identical.
  10232. if (!S.getLangOpts().CPlusPlus ||
  10233. candidateHasExactlyCorrectType(FunDecl)) {
  10234. Matches.push_back(std::make_pair(
  10235. CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  10236. FoundNonTemplateFunction = true;
  10237. return true;
  10238. }
  10239. }
  10240. return false;
  10241. }
  10242. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  10243. bool Ret = false;
  10244. // If the overload expression doesn't have the form of a pointer to
  10245. // member, don't try to convert it to a pointer-to-member type.
  10246. if (IsInvalidFormOfPointerToMemberFunction())
  10247. return false;
  10248. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  10249. E = OvlExpr->decls_end();
  10250. I != E; ++I) {
  10251. // Look through any using declarations to find the underlying function.
  10252. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  10253. // C++ [over.over]p3:
  10254. // Non-member functions and static member functions match
  10255. // targets of type "pointer-to-function" or "reference-to-function."
  10256. // Nonstatic member functions match targets of
  10257. // type "pointer-to-member-function."
  10258. // Note that according to DR 247, the containing class does not matter.
  10259. if (FunctionTemplateDecl *FunctionTemplate
  10260. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  10261. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  10262. Ret = true;
  10263. }
  10264. // If we have explicit template arguments supplied, skip non-templates.
  10265. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  10266. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  10267. Ret = true;
  10268. }
  10269. assert(Ret || Matches.empty());
  10270. return Ret;
  10271. }
  10272. void EliminateAllExceptMostSpecializedTemplate() {
  10273. // [...] and any given function template specialization F1 is
  10274. // eliminated if the set contains a second function template
  10275. // specialization whose function template is more specialized
  10276. // than the function template of F1 according to the partial
  10277. // ordering rules of 14.5.5.2.
  10278. // The algorithm specified above is quadratic. We instead use a
  10279. // two-pass algorithm (similar to the one used to identify the
  10280. // best viable function in an overload set) that identifies the
  10281. // best function template (if it exists).
  10282. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  10283. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  10284. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  10285. // TODO: It looks like FailedCandidates does not serve much purpose
  10286. // here, since the no_viable diagnostic has index 0.
  10287. UnresolvedSetIterator Result = S.getMostSpecialized(
  10288. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  10289. SourceExpr->getBeginLoc(), S.PDiag(),
  10290. S.PDiag(diag::err_addr_ovl_ambiguous)
  10291. << Matches[0].second->getDeclName(),
  10292. S.PDiag(diag::note_ovl_candidate)
  10293. << (unsigned)oc_function << (unsigned)ocs_described_template,
  10294. Complain, TargetFunctionType);
  10295. if (Result != MatchesCopy.end()) {
  10296. // Make it the first and only element
  10297. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  10298. Matches[0].second = cast<FunctionDecl>(*Result);
  10299. Matches.resize(1);
  10300. } else
  10301. HasComplained |= Complain;
  10302. }
  10303. void EliminateAllTemplateMatches() {
  10304. // [...] any function template specializations in the set are
  10305. // eliminated if the set also contains a non-template function, [...]
  10306. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  10307. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  10308. ++I;
  10309. else {
  10310. Matches[I] = Matches[--N];
  10311. Matches.resize(N);
  10312. }
  10313. }
  10314. }
  10315. void EliminateSuboptimalCudaMatches() {
  10316. S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
  10317. }
  10318. public:
  10319. void ComplainNoMatchesFound() const {
  10320. assert(Matches.empty());
  10321. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
  10322. << OvlExpr->getName() << TargetFunctionType
  10323. << OvlExpr->getSourceRange();
  10324. if (FailedCandidates.empty())
  10325. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  10326. /*TakingAddress=*/true);
  10327. else {
  10328. // We have some deduction failure messages. Use them to diagnose
  10329. // the function templates, and diagnose the non-template candidates
  10330. // normally.
  10331. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  10332. IEnd = OvlExpr->decls_end();
  10333. I != IEnd; ++I)
  10334. if (FunctionDecl *Fun =
  10335. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  10336. if (!functionHasPassObjectSizeParams(Fun))
  10337. S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
  10338. /*TakingAddress=*/true);
  10339. FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
  10340. }
  10341. }
  10342. bool IsInvalidFormOfPointerToMemberFunction() const {
  10343. return TargetTypeIsNonStaticMemberFunction &&
  10344. !OvlExprInfo.HasFormOfMemberPointer;
  10345. }
  10346. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  10347. // TODO: Should we condition this on whether any functions might
  10348. // have matched, or is it more appropriate to do that in callers?
  10349. // TODO: a fixit wouldn't hurt.
  10350. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  10351. << TargetType << OvlExpr->getSourceRange();
  10352. }
  10353. bool IsStaticMemberFunctionFromBoundPointer() const {
  10354. return StaticMemberFunctionFromBoundPointer;
  10355. }
  10356. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  10357. S.Diag(OvlExpr->getBeginLoc(),
  10358. diag::err_invalid_form_pointer_member_function)
  10359. << OvlExpr->getSourceRange();
  10360. }
  10361. void ComplainOfInvalidConversion() const {
  10362. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
  10363. << OvlExpr->getName() << TargetType;
  10364. }
  10365. void ComplainMultipleMatchesFound() const {
  10366. assert(Matches.size() > 1);
  10367. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
  10368. << OvlExpr->getName() << OvlExpr->getSourceRange();
  10369. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  10370. /*TakingAddress=*/true);
  10371. }
  10372. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  10373. int getNumMatches() const { return Matches.size(); }
  10374. FunctionDecl* getMatchingFunctionDecl() const {
  10375. if (Matches.size() != 1) return nullptr;
  10376. return Matches[0].second;
  10377. }
  10378. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  10379. if (Matches.size() != 1) return nullptr;
  10380. return &Matches[0].first;
  10381. }
  10382. };
  10383. }
  10384. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  10385. /// an overloaded function (C++ [over.over]), where @p From is an
  10386. /// expression with overloaded function type and @p ToType is the type
  10387. /// we're trying to resolve to. For example:
  10388. ///
  10389. /// @code
  10390. /// int f(double);
  10391. /// int f(int);
  10392. ///
  10393. /// int (*pfd)(double) = f; // selects f(double)
  10394. /// @endcode
  10395. ///
  10396. /// This routine returns the resulting FunctionDecl if it could be
  10397. /// resolved, and NULL otherwise. When @p Complain is true, this
  10398. /// routine will emit diagnostics if there is an error.
  10399. FunctionDecl *
  10400. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  10401. QualType TargetType,
  10402. bool Complain,
  10403. DeclAccessPair &FoundResult,
  10404. bool *pHadMultipleCandidates) {
  10405. assert(AddressOfExpr->getType() == Context.OverloadTy);
  10406. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  10407. Complain);
  10408. int NumMatches = Resolver.getNumMatches();
  10409. FunctionDecl *Fn = nullptr;
  10410. bool ShouldComplain = Complain && !Resolver.hasComplained();
  10411. if (NumMatches == 0 && ShouldComplain) {
  10412. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  10413. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  10414. else
  10415. Resolver.ComplainNoMatchesFound();
  10416. }
  10417. else if (NumMatches > 1 && ShouldComplain)
  10418. Resolver.ComplainMultipleMatchesFound();
  10419. else if (NumMatches == 1) {
  10420. Fn = Resolver.getMatchingFunctionDecl();
  10421. assert(Fn);
  10422. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  10423. ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
  10424. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  10425. if (Complain) {
  10426. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  10427. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  10428. else
  10429. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  10430. }
  10431. }
  10432. if (pHadMultipleCandidates)
  10433. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  10434. return Fn;
  10435. }
  10436. /// Given an expression that refers to an overloaded function, try to
  10437. /// resolve that function to a single function that can have its address taken.
  10438. /// This will modify `Pair` iff it returns non-null.
  10439. ///
  10440. /// This routine can only realistically succeed if all but one candidates in the
  10441. /// overload set for SrcExpr cannot have their addresses taken.
  10442. FunctionDecl *
  10443. Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
  10444. DeclAccessPair &Pair) {
  10445. OverloadExpr::FindResult R = OverloadExpr::find(E);
  10446. OverloadExpr *Ovl = R.Expression;
  10447. FunctionDecl *Result = nullptr;
  10448. DeclAccessPair DAP;
  10449. // Don't use the AddressOfResolver because we're specifically looking for
  10450. // cases where we have one overload candidate that lacks
  10451. // enable_if/pass_object_size/...
  10452. for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
  10453. auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
  10454. if (!FD)
  10455. return nullptr;
  10456. if (!checkAddressOfFunctionIsAvailable(FD))
  10457. continue;
  10458. // We have more than one result; quit.
  10459. if (Result)
  10460. return nullptr;
  10461. DAP = I.getPair();
  10462. Result = FD;
  10463. }
  10464. if (Result)
  10465. Pair = DAP;
  10466. return Result;
  10467. }
  10468. /// Given an overloaded function, tries to turn it into a non-overloaded
  10469. /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
  10470. /// will perform access checks, diagnose the use of the resultant decl, and, if
  10471. /// requested, potentially perform a function-to-pointer decay.
  10472. ///
  10473. /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
  10474. /// Otherwise, returns true. This may emit diagnostics and return true.
  10475. bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
  10476. ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
  10477. Expr *E = SrcExpr.get();
  10478. assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
  10479. DeclAccessPair DAP;
  10480. FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
  10481. if (!Found || Found->isCPUDispatchMultiVersion() ||
  10482. Found->isCPUSpecificMultiVersion())
  10483. return false;
  10484. // Emitting multiple diagnostics for a function that is both inaccessible and
  10485. // unavailable is consistent with our behavior elsewhere. So, always check
  10486. // for both.
  10487. DiagnoseUseOfDecl(Found, E->getExprLoc());
  10488. CheckAddressOfMemberAccess(E, DAP);
  10489. Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
  10490. if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
  10491. SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
  10492. else
  10493. SrcExpr = Fixed;
  10494. return true;
  10495. }
  10496. /// Given an expression that refers to an overloaded function, try to
  10497. /// resolve that overloaded function expression down to a single function.
  10498. ///
  10499. /// This routine can only resolve template-ids that refer to a single function
  10500. /// template, where that template-id refers to a single template whose template
  10501. /// arguments are either provided by the template-id or have defaults,
  10502. /// as described in C++0x [temp.arg.explicit]p3.
  10503. ///
  10504. /// If no template-ids are found, no diagnostics are emitted and NULL is
  10505. /// returned.
  10506. FunctionDecl *
  10507. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  10508. bool Complain,
  10509. DeclAccessPair *FoundResult) {
  10510. // C++ [over.over]p1:
  10511. // [...] [Note: any redundant set of parentheses surrounding the
  10512. // overloaded function name is ignored (5.1). ]
  10513. // C++ [over.over]p1:
  10514. // [...] The overloaded function name can be preceded by the &
  10515. // operator.
  10516. // If we didn't actually find any template-ids, we're done.
  10517. if (!ovl->hasExplicitTemplateArgs())
  10518. return nullptr;
  10519. TemplateArgumentListInfo ExplicitTemplateArgs;
  10520. ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
  10521. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  10522. // Look through all of the overloaded functions, searching for one
  10523. // whose type matches exactly.
  10524. FunctionDecl *Matched = nullptr;
  10525. for (UnresolvedSetIterator I = ovl->decls_begin(),
  10526. E = ovl->decls_end(); I != E; ++I) {
  10527. // C++0x [temp.arg.explicit]p3:
  10528. // [...] In contexts where deduction is done and fails, or in contexts
  10529. // where deduction is not done, if a template argument list is
  10530. // specified and it, along with any default template arguments,
  10531. // identifies a single function template specialization, then the
  10532. // template-id is an lvalue for the function template specialization.
  10533. FunctionTemplateDecl *FunctionTemplate
  10534. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  10535. // C++ [over.over]p2:
  10536. // If the name is a function template, template argument deduction is
  10537. // done (14.8.2.2), and if the argument deduction succeeds, the
  10538. // resulting template argument list is used to generate a single
  10539. // function template specialization, which is added to the set of
  10540. // overloaded functions considered.
  10541. FunctionDecl *Specialization = nullptr;
  10542. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  10543. if (TemplateDeductionResult Result
  10544. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  10545. Specialization, Info,
  10546. /*IsAddressOfFunction*/true)) {
  10547. // Make a note of the failed deduction for diagnostics.
  10548. // TODO: Actually use the failed-deduction info?
  10549. FailedCandidates.addCandidate()
  10550. .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
  10551. MakeDeductionFailureInfo(Context, Result, Info));
  10552. continue;
  10553. }
  10554. assert(Specialization && "no specialization and no error?");
  10555. // Multiple matches; we can't resolve to a single declaration.
  10556. if (Matched) {
  10557. if (Complain) {
  10558. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  10559. << ovl->getName();
  10560. NoteAllOverloadCandidates(ovl);
  10561. }
  10562. return nullptr;
  10563. }
  10564. Matched = Specialization;
  10565. if (FoundResult) *FoundResult = I.getPair();
  10566. }
  10567. if (Matched &&
  10568. completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
  10569. return nullptr;
  10570. return Matched;
  10571. }
  10572. // Resolve and fix an overloaded expression that can be resolved
  10573. // because it identifies a single function template specialization.
  10574. //
  10575. // Last three arguments should only be supplied if Complain = true
  10576. //
  10577. // Return true if it was logically possible to so resolve the
  10578. // expression, regardless of whether or not it succeeded. Always
  10579. // returns true if 'complain' is set.
  10580. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  10581. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  10582. bool complain, SourceRange OpRangeForComplaining,
  10583. QualType DestTypeForComplaining,
  10584. unsigned DiagIDForComplaining) {
  10585. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  10586. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  10587. DeclAccessPair found;
  10588. ExprResult SingleFunctionExpression;
  10589. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  10590. ovl.Expression, /*complain*/ false, &found)) {
  10591. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
  10592. SrcExpr = ExprError();
  10593. return true;
  10594. }
  10595. // It is only correct to resolve to an instance method if we're
  10596. // resolving a form that's permitted to be a pointer to member.
  10597. // Otherwise we'll end up making a bound member expression, which
  10598. // is illegal in all the contexts we resolve like this.
  10599. if (!ovl.HasFormOfMemberPointer &&
  10600. isa<CXXMethodDecl>(fn) &&
  10601. cast<CXXMethodDecl>(fn)->isInstance()) {
  10602. if (!complain) return false;
  10603. Diag(ovl.Expression->getExprLoc(),
  10604. diag::err_bound_member_function)
  10605. << 0 << ovl.Expression->getSourceRange();
  10606. // TODO: I believe we only end up here if there's a mix of
  10607. // static and non-static candidates (otherwise the expression
  10608. // would have 'bound member' type, not 'overload' type).
  10609. // Ideally we would note which candidate was chosen and why
  10610. // the static candidates were rejected.
  10611. SrcExpr = ExprError();
  10612. return true;
  10613. }
  10614. // Fix the expression to refer to 'fn'.
  10615. SingleFunctionExpression =
  10616. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  10617. // If desired, do function-to-pointer decay.
  10618. if (doFunctionPointerConverion) {
  10619. SingleFunctionExpression =
  10620. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  10621. if (SingleFunctionExpression.isInvalid()) {
  10622. SrcExpr = ExprError();
  10623. return true;
  10624. }
  10625. }
  10626. }
  10627. if (!SingleFunctionExpression.isUsable()) {
  10628. if (complain) {
  10629. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  10630. << ovl.Expression->getName()
  10631. << DestTypeForComplaining
  10632. << OpRangeForComplaining
  10633. << ovl.Expression->getQualifierLoc().getSourceRange();
  10634. NoteAllOverloadCandidates(SrcExpr.get());
  10635. SrcExpr = ExprError();
  10636. return true;
  10637. }
  10638. return false;
  10639. }
  10640. SrcExpr = SingleFunctionExpression;
  10641. return true;
  10642. }
  10643. /// Add a single candidate to the overload set.
  10644. static void AddOverloadedCallCandidate(Sema &S,
  10645. DeclAccessPair FoundDecl,
  10646. TemplateArgumentListInfo *ExplicitTemplateArgs,
  10647. ArrayRef<Expr *> Args,
  10648. OverloadCandidateSet &CandidateSet,
  10649. bool PartialOverloading,
  10650. bool KnownValid) {
  10651. NamedDecl *Callee = FoundDecl.getDecl();
  10652. if (isa<UsingShadowDecl>(Callee))
  10653. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  10654. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  10655. if (ExplicitTemplateArgs) {
  10656. assert(!KnownValid && "Explicit template arguments?");
  10657. return;
  10658. }
  10659. // Prevent ill-formed function decls to be added as overload candidates.
  10660. if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
  10661. return;
  10662. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  10663. /*SuppressUserConversions=*/false,
  10664. PartialOverloading);
  10665. return;
  10666. }
  10667. if (FunctionTemplateDecl *FuncTemplate
  10668. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  10669. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  10670. ExplicitTemplateArgs, Args, CandidateSet,
  10671. /*SuppressUserConversions=*/false,
  10672. PartialOverloading);
  10673. return;
  10674. }
  10675. assert(!KnownValid && "unhandled case in overloaded call candidate");
  10676. }
  10677. /// Add the overload candidates named by callee and/or found by argument
  10678. /// dependent lookup to the given overload set.
  10679. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  10680. ArrayRef<Expr *> Args,
  10681. OverloadCandidateSet &CandidateSet,
  10682. bool PartialOverloading) {
  10683. #ifndef NDEBUG
  10684. // Verify that ArgumentDependentLookup is consistent with the rules
  10685. // in C++0x [basic.lookup.argdep]p3:
  10686. //
  10687. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  10688. // and let Y be the lookup set produced by argument dependent
  10689. // lookup (defined as follows). If X contains
  10690. //
  10691. // -- a declaration of a class member, or
  10692. //
  10693. // -- a block-scope function declaration that is not a
  10694. // using-declaration, or
  10695. //
  10696. // -- a declaration that is neither a function or a function
  10697. // template
  10698. //
  10699. // then Y is empty.
  10700. if (ULE->requiresADL()) {
  10701. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  10702. E = ULE->decls_end(); I != E; ++I) {
  10703. assert(!(*I)->getDeclContext()->isRecord());
  10704. assert(isa<UsingShadowDecl>(*I) ||
  10705. !(*I)->getDeclContext()->isFunctionOrMethod());
  10706. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  10707. }
  10708. }
  10709. #endif
  10710. // It would be nice to avoid this copy.
  10711. TemplateArgumentListInfo TABuffer;
  10712. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  10713. if (ULE->hasExplicitTemplateArgs()) {
  10714. ULE->copyTemplateArgumentsInto(TABuffer);
  10715. ExplicitTemplateArgs = &TABuffer;
  10716. }
  10717. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  10718. E = ULE->decls_end(); I != E; ++I)
  10719. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  10720. CandidateSet, PartialOverloading,
  10721. /*KnownValid*/ true);
  10722. if (ULE->requiresADL())
  10723. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  10724. Args, ExplicitTemplateArgs,
  10725. CandidateSet, PartialOverloading);
  10726. }
  10727. /// Determine whether a declaration with the specified name could be moved into
  10728. /// a different namespace.
  10729. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  10730. switch (Name.getCXXOverloadedOperator()) {
  10731. case OO_New: case OO_Array_New:
  10732. case OO_Delete: case OO_Array_Delete:
  10733. return false;
  10734. default:
  10735. return true;
  10736. }
  10737. }
  10738. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  10739. /// template, where the non-dependent name was declared after the template
  10740. /// was defined. This is common in code written for a compilers which do not
  10741. /// correctly implement two-stage name lookup.
  10742. ///
  10743. /// Returns true if a viable candidate was found and a diagnostic was issued.
  10744. static bool
  10745. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  10746. const CXXScopeSpec &SS, LookupResult &R,
  10747. OverloadCandidateSet::CandidateSetKind CSK,
  10748. TemplateArgumentListInfo *ExplicitTemplateArgs,
  10749. ArrayRef<Expr *> Args,
  10750. bool *DoDiagnoseEmptyLookup = nullptr) {
  10751. if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
  10752. return false;
  10753. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  10754. if (DC->isTransparentContext())
  10755. continue;
  10756. SemaRef.LookupQualifiedName(R, DC);
  10757. if (!R.empty()) {
  10758. R.suppressDiagnostics();
  10759. if (isa<CXXRecordDecl>(DC)) {
  10760. // Don't diagnose names we find in classes; we get much better
  10761. // diagnostics for these from DiagnoseEmptyLookup.
  10762. R.clear();
  10763. if (DoDiagnoseEmptyLookup)
  10764. *DoDiagnoseEmptyLookup = true;
  10765. return false;
  10766. }
  10767. OverloadCandidateSet Candidates(FnLoc, CSK);
  10768. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  10769. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  10770. ExplicitTemplateArgs, Args,
  10771. Candidates, false, /*KnownValid*/ false);
  10772. OverloadCandidateSet::iterator Best;
  10773. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  10774. // No viable functions. Don't bother the user with notes for functions
  10775. // which don't work and shouldn't be found anyway.
  10776. R.clear();
  10777. return false;
  10778. }
  10779. // Find the namespaces where ADL would have looked, and suggest
  10780. // declaring the function there instead.
  10781. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  10782. Sema::AssociatedClassSet AssociatedClasses;
  10783. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  10784. AssociatedNamespaces,
  10785. AssociatedClasses);
  10786. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  10787. if (canBeDeclaredInNamespace(R.getLookupName())) {
  10788. DeclContext *Std = SemaRef.getStdNamespace();
  10789. for (Sema::AssociatedNamespaceSet::iterator
  10790. it = AssociatedNamespaces.begin(),
  10791. end = AssociatedNamespaces.end(); it != end; ++it) {
  10792. // Never suggest declaring a function within namespace 'std'.
  10793. if (Std && Std->Encloses(*it))
  10794. continue;
  10795. // Never suggest declaring a function within a namespace with a
  10796. // reserved name, like __gnu_cxx.
  10797. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  10798. if (NS &&
  10799. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  10800. continue;
  10801. SuggestedNamespaces.insert(*it);
  10802. }
  10803. }
  10804. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  10805. << R.getLookupName();
  10806. if (SuggestedNamespaces.empty()) {
  10807. SemaRef.Diag(Best->Function->getLocation(),
  10808. diag::note_not_found_by_two_phase_lookup)
  10809. << R.getLookupName() << 0;
  10810. } else if (SuggestedNamespaces.size() == 1) {
  10811. SemaRef.Diag(Best->Function->getLocation(),
  10812. diag::note_not_found_by_two_phase_lookup)
  10813. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  10814. } else {
  10815. // FIXME: It would be useful to list the associated namespaces here,
  10816. // but the diagnostics infrastructure doesn't provide a way to produce
  10817. // a localized representation of a list of items.
  10818. SemaRef.Diag(Best->Function->getLocation(),
  10819. diag::note_not_found_by_two_phase_lookup)
  10820. << R.getLookupName() << 2;
  10821. }
  10822. // Try to recover by calling this function.
  10823. return true;
  10824. }
  10825. R.clear();
  10826. }
  10827. return false;
  10828. }
  10829. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  10830. /// template, where the non-dependent operator was declared after the template
  10831. /// was defined.
  10832. ///
  10833. /// Returns true if a viable candidate was found and a diagnostic was issued.
  10834. static bool
  10835. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  10836. SourceLocation OpLoc,
  10837. ArrayRef<Expr *> Args) {
  10838. DeclarationName OpName =
  10839. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  10840. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  10841. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  10842. OverloadCandidateSet::CSK_Operator,
  10843. /*ExplicitTemplateArgs=*/nullptr, Args);
  10844. }
  10845. namespace {
  10846. class BuildRecoveryCallExprRAII {
  10847. Sema &SemaRef;
  10848. public:
  10849. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  10850. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  10851. SemaRef.IsBuildingRecoveryCallExpr = true;
  10852. }
  10853. ~BuildRecoveryCallExprRAII() {
  10854. SemaRef.IsBuildingRecoveryCallExpr = false;
  10855. }
  10856. };
  10857. }
  10858. /// Attempts to recover from a call where no functions were found.
  10859. ///
  10860. /// Returns true if new candidates were found.
  10861. static ExprResult
  10862. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  10863. UnresolvedLookupExpr *ULE,
  10864. SourceLocation LParenLoc,
  10865. MutableArrayRef<Expr *> Args,
  10866. SourceLocation RParenLoc,
  10867. bool EmptyLookup, bool AllowTypoCorrection) {
  10868. // Do not try to recover if it is already building a recovery call.
  10869. // This stops infinite loops for template instantiations like
  10870. //
  10871. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  10872. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  10873. //
  10874. if (SemaRef.IsBuildingRecoveryCallExpr)
  10875. return ExprError();
  10876. BuildRecoveryCallExprRAII RCE(SemaRef);
  10877. CXXScopeSpec SS;
  10878. SS.Adopt(ULE->getQualifierLoc());
  10879. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  10880. TemplateArgumentListInfo TABuffer;
  10881. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  10882. if (ULE->hasExplicitTemplateArgs()) {
  10883. ULE->copyTemplateArgumentsInto(TABuffer);
  10884. ExplicitTemplateArgs = &TABuffer;
  10885. }
  10886. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  10887. Sema::LookupOrdinaryName);
  10888. bool DoDiagnoseEmptyLookup = EmptyLookup;
  10889. if (!DiagnoseTwoPhaseLookup(
  10890. SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
  10891. ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
  10892. NoTypoCorrectionCCC NoTypoValidator{};
  10893. FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
  10894. ExplicitTemplateArgs != nullptr,
  10895. dyn_cast<MemberExpr>(Fn));
  10896. CorrectionCandidateCallback &Validator =
  10897. AllowTypoCorrection
  10898. ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
  10899. : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
  10900. if (!DoDiagnoseEmptyLookup ||
  10901. SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
  10902. Args))
  10903. return ExprError();
  10904. }
  10905. assert(!R.empty() && "lookup results empty despite recovery");
  10906. // If recovery created an ambiguity, just bail out.
  10907. if (R.isAmbiguous()) {
  10908. R.suppressDiagnostics();
  10909. return ExprError();
  10910. }
  10911. // Build an implicit member call if appropriate. Just drop the
  10912. // casts and such from the call, we don't really care.
  10913. ExprResult NewFn = ExprError();
  10914. if ((*R.begin())->isCXXClassMember())
  10915. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
  10916. ExplicitTemplateArgs, S);
  10917. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  10918. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  10919. ExplicitTemplateArgs);
  10920. else
  10921. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  10922. if (NewFn.isInvalid())
  10923. return ExprError();
  10924. // This shouldn't cause an infinite loop because we're giving it
  10925. // an expression with viable lookup results, which should never
  10926. // end up here.
  10927. return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  10928. MultiExprArg(Args.data(), Args.size()),
  10929. RParenLoc);
  10930. }
  10931. /// Constructs and populates an OverloadedCandidateSet from
  10932. /// the given function.
  10933. /// \returns true when an the ExprResult output parameter has been set.
  10934. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  10935. UnresolvedLookupExpr *ULE,
  10936. MultiExprArg Args,
  10937. SourceLocation RParenLoc,
  10938. OverloadCandidateSet *CandidateSet,
  10939. ExprResult *Result) {
  10940. #ifndef NDEBUG
  10941. if (ULE->requiresADL()) {
  10942. // To do ADL, we must have found an unqualified name.
  10943. assert(!ULE->getQualifier() && "qualified name with ADL");
  10944. // We don't perform ADL for implicit declarations of builtins.
  10945. // Verify that this was correctly set up.
  10946. FunctionDecl *F;
  10947. if (ULE->decls_begin() != ULE->decls_end() &&
  10948. ULE->decls_begin() + 1 == ULE->decls_end() &&
  10949. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  10950. F->getBuiltinID() && F->isImplicit())
  10951. llvm_unreachable("performing ADL for builtin");
  10952. // We don't perform ADL in C.
  10953. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  10954. }
  10955. #endif
  10956. UnbridgedCastsSet UnbridgedCasts;
  10957. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  10958. *Result = ExprError();
  10959. return true;
  10960. }
  10961. // Add the functions denoted by the callee to the set of candidate
  10962. // functions, including those from argument-dependent lookup.
  10963. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  10964. if (getLangOpts().MSVCCompat &&
  10965. CurContext->isDependentContext() && !isSFINAEContext() &&
  10966. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  10967. OverloadCandidateSet::iterator Best;
  10968. if (CandidateSet->empty() ||
  10969. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
  10970. OR_No_Viable_Function) {
  10971. // In Microsoft mode, if we are inside a template class member function
  10972. // then create a type dependent CallExpr. The goal is to postpone name
  10973. // lookup to instantiation time to be able to search into type dependent
  10974. // base classes.
  10975. CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
  10976. VK_RValue, RParenLoc);
  10977. CE->setTypeDependent(true);
  10978. CE->setValueDependent(true);
  10979. CE->setInstantiationDependent(true);
  10980. *Result = CE;
  10981. return true;
  10982. }
  10983. }
  10984. if (CandidateSet->empty())
  10985. return false;
  10986. UnbridgedCasts.restore();
  10987. return false;
  10988. }
  10989. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  10990. /// the completed call expression. If overload resolution fails, emits
  10991. /// diagnostics and returns ExprError()
  10992. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  10993. UnresolvedLookupExpr *ULE,
  10994. SourceLocation LParenLoc,
  10995. MultiExprArg Args,
  10996. SourceLocation RParenLoc,
  10997. Expr *ExecConfig,
  10998. OverloadCandidateSet *CandidateSet,
  10999. OverloadCandidateSet::iterator *Best,
  11000. OverloadingResult OverloadResult,
  11001. bool AllowTypoCorrection) {
  11002. if (CandidateSet->empty())
  11003. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  11004. RParenLoc, /*EmptyLookup=*/true,
  11005. AllowTypoCorrection);
  11006. switch (OverloadResult) {
  11007. case OR_Success: {
  11008. FunctionDecl *FDecl = (*Best)->Function;
  11009. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  11010. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  11011. return ExprError();
  11012. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  11013. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  11014. ExecConfig, /*IsExecConfig=*/false,
  11015. (*Best)->IsADLCandidate);
  11016. }
  11017. case OR_No_Viable_Function: {
  11018. // Try to recover by looking for viable functions which the user might
  11019. // have meant to call.
  11020. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  11021. Args, RParenLoc,
  11022. /*EmptyLookup=*/false,
  11023. AllowTypoCorrection);
  11024. if (!Recovery.isInvalid())
  11025. return Recovery;
  11026. // If the user passes in a function that we can't take the address of, we
  11027. // generally end up emitting really bad error messages. Here, we attempt to
  11028. // emit better ones.
  11029. for (const Expr *Arg : Args) {
  11030. if (!Arg->getType()->isFunctionType())
  11031. continue;
  11032. if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
  11033. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  11034. if (FD &&
  11035. !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  11036. Arg->getExprLoc()))
  11037. return ExprError();
  11038. }
  11039. }
  11040. CandidateSet->NoteCandidates(
  11041. PartialDiagnosticAt(
  11042. Fn->getBeginLoc(),
  11043. SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
  11044. << ULE->getName() << Fn->getSourceRange()),
  11045. SemaRef, OCD_AllCandidates, Args);
  11046. break;
  11047. }
  11048. case OR_Ambiguous:
  11049. CandidateSet->NoteCandidates(
  11050. PartialDiagnosticAt(Fn->getBeginLoc(),
  11051. SemaRef.PDiag(diag::err_ovl_ambiguous_call)
  11052. << ULE->getName() << Fn->getSourceRange()),
  11053. SemaRef, OCD_ViableCandidates, Args);
  11054. break;
  11055. case OR_Deleted: {
  11056. CandidateSet->NoteCandidates(
  11057. PartialDiagnosticAt(Fn->getBeginLoc(),
  11058. SemaRef.PDiag(diag::err_ovl_deleted_call)
  11059. << ULE->getName() << Fn->getSourceRange()),
  11060. SemaRef, OCD_AllCandidates, Args);
  11061. // We emitted an error for the unavailable/deleted function call but keep
  11062. // the call in the AST.
  11063. FunctionDecl *FDecl = (*Best)->Function;
  11064. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  11065. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  11066. ExecConfig, /*IsExecConfig=*/false,
  11067. (*Best)->IsADLCandidate);
  11068. }
  11069. }
  11070. // Overload resolution failed.
  11071. return ExprError();
  11072. }
  11073. static void markUnaddressableCandidatesUnviable(Sema &S,
  11074. OverloadCandidateSet &CS) {
  11075. for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
  11076. if (I->Viable &&
  11077. !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
  11078. I->Viable = false;
  11079. I->FailureKind = ovl_fail_addr_not_available;
  11080. }
  11081. }
  11082. }
  11083. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  11084. /// (which eventually refers to the declaration Func) and the call
  11085. /// arguments Args/NumArgs, attempt to resolve the function call down
  11086. /// to a specific function. If overload resolution succeeds, returns
  11087. /// the call expression produced by overload resolution.
  11088. /// Otherwise, emits diagnostics and returns ExprError.
  11089. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  11090. UnresolvedLookupExpr *ULE,
  11091. SourceLocation LParenLoc,
  11092. MultiExprArg Args,
  11093. SourceLocation RParenLoc,
  11094. Expr *ExecConfig,
  11095. bool AllowTypoCorrection,
  11096. bool CalleesAddressIsTaken) {
  11097. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  11098. OverloadCandidateSet::CSK_Normal);
  11099. ExprResult result;
  11100. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  11101. &result))
  11102. return result;
  11103. // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
  11104. // functions that aren't addressible are considered unviable.
  11105. if (CalleesAddressIsTaken)
  11106. markUnaddressableCandidatesUnviable(*this, CandidateSet);
  11107. OverloadCandidateSet::iterator Best;
  11108. OverloadingResult OverloadResult =
  11109. CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
  11110. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
  11111. ExecConfig, &CandidateSet, &Best,
  11112. OverloadResult, AllowTypoCorrection);
  11113. }
  11114. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  11115. return Functions.size() > 1 ||
  11116. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  11117. }
  11118. /// Create a unary operation that may resolve to an overloaded
  11119. /// operator.
  11120. ///
  11121. /// \param OpLoc The location of the operator itself (e.g., '*').
  11122. ///
  11123. /// \param Opc The UnaryOperatorKind that describes this operator.
  11124. ///
  11125. /// \param Fns The set of non-member functions that will be
  11126. /// considered by overload resolution. The caller needs to build this
  11127. /// set based on the context using, e.g.,
  11128. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  11129. /// set should not contain any member functions; those will be added
  11130. /// by CreateOverloadedUnaryOp().
  11131. ///
  11132. /// \param Input The input argument.
  11133. ExprResult
  11134. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
  11135. const UnresolvedSetImpl &Fns,
  11136. Expr *Input, bool PerformADL) {
  11137. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  11138. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  11139. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  11140. // TODO: provide better source location info.
  11141. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  11142. if (checkPlaceholderForOverload(*this, Input))
  11143. return ExprError();
  11144. Expr *Args[2] = { Input, nullptr };
  11145. unsigned NumArgs = 1;
  11146. // For post-increment and post-decrement, add the implicit '0' as
  11147. // the second argument, so that we know this is a post-increment or
  11148. // post-decrement.
  11149. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  11150. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  11151. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  11152. SourceLocation());
  11153. NumArgs = 2;
  11154. }
  11155. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  11156. if (Input->isTypeDependent()) {
  11157. if (Fns.empty())
  11158. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  11159. VK_RValue, OK_Ordinary, OpLoc, false);
  11160. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11161. UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
  11162. Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
  11163. /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
  11164. return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
  11165. Context.DependentTy, VK_RValue, OpLoc,
  11166. FPOptions());
  11167. }
  11168. // Build an empty overload set.
  11169. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  11170. // Add the candidates from the given function set.
  11171. AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
  11172. // Add operator candidates that are member functions.
  11173. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  11174. // Add candidates from ADL.
  11175. if (PerformADL) {
  11176. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  11177. /*ExplicitTemplateArgs*/nullptr,
  11178. CandidateSet);
  11179. }
  11180. // Add builtin operator candidates.
  11181. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  11182. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11183. // Perform overload resolution.
  11184. OverloadCandidateSet::iterator Best;
  11185. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  11186. case OR_Success: {
  11187. // We found a built-in operator or an overloaded operator.
  11188. FunctionDecl *FnDecl = Best->Function;
  11189. if (FnDecl) {
  11190. Expr *Base = nullptr;
  11191. // We matched an overloaded operator. Build a call to that
  11192. // operator.
  11193. // Convert the arguments.
  11194. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11195. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  11196. ExprResult InputRes =
  11197. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  11198. Best->FoundDecl, Method);
  11199. if (InputRes.isInvalid())
  11200. return ExprError();
  11201. Base = Input = InputRes.get();
  11202. } else {
  11203. // Convert the arguments.
  11204. ExprResult InputInit
  11205. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11206. Context,
  11207. FnDecl->getParamDecl(0)),
  11208. SourceLocation(),
  11209. Input);
  11210. if (InputInit.isInvalid())
  11211. return ExprError();
  11212. Input = InputInit.get();
  11213. }
  11214. // Build the actual expression node.
  11215. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  11216. Base, HadMultipleCandidates,
  11217. OpLoc);
  11218. if (FnExpr.isInvalid())
  11219. return ExprError();
  11220. // Determine the result type.
  11221. QualType ResultTy = FnDecl->getReturnType();
  11222. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11223. ResultTy = ResultTy.getNonLValueExprType(Context);
  11224. Args[0] = Input;
  11225. CallExpr *TheCall = CXXOperatorCallExpr::Create(
  11226. Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
  11227. FPOptions(), Best->IsADLCandidate);
  11228. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  11229. return ExprError();
  11230. if (CheckFunctionCall(FnDecl, TheCall,
  11231. FnDecl->getType()->castAs<FunctionProtoType>()))
  11232. return ExprError();
  11233. return MaybeBindToTemporary(TheCall);
  11234. } else {
  11235. // We matched a built-in operator. Convert the arguments, then
  11236. // break out so that we will build the appropriate built-in
  11237. // operator node.
  11238. ExprResult InputRes = PerformImplicitConversion(
  11239. Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
  11240. CCK_ForBuiltinOverloadedOp);
  11241. if (InputRes.isInvalid())
  11242. return ExprError();
  11243. Input = InputRes.get();
  11244. break;
  11245. }
  11246. }
  11247. case OR_No_Viable_Function:
  11248. // This is an erroneous use of an operator which can be overloaded by
  11249. // a non-member function. Check for non-member operators which were
  11250. // defined too late to be candidates.
  11251. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  11252. // FIXME: Recover by calling the found function.
  11253. return ExprError();
  11254. // No viable function; fall through to handling this as a
  11255. // built-in operator, which will produce an error message for us.
  11256. break;
  11257. case OR_Ambiguous:
  11258. CandidateSet.NoteCandidates(
  11259. PartialDiagnosticAt(OpLoc,
  11260. PDiag(diag::err_ovl_ambiguous_oper_unary)
  11261. << UnaryOperator::getOpcodeStr(Opc)
  11262. << Input->getType() << Input->getSourceRange()),
  11263. *this, OCD_ViableCandidates, ArgsArray,
  11264. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  11265. return ExprError();
  11266. case OR_Deleted:
  11267. CandidateSet.NoteCandidates(
  11268. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  11269. << UnaryOperator::getOpcodeStr(Opc)
  11270. << Input->getSourceRange()),
  11271. *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
  11272. OpLoc);
  11273. return ExprError();
  11274. }
  11275. // Either we found no viable overloaded operator or we matched a
  11276. // built-in operator. In either case, fall through to trying to
  11277. // build a built-in operation.
  11278. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11279. }
  11280. /// Create a binary operation that may resolve to an overloaded
  11281. /// operator.
  11282. ///
  11283. /// \param OpLoc The location of the operator itself (e.g., '+').
  11284. ///
  11285. /// \param Opc The BinaryOperatorKind that describes this operator.
  11286. ///
  11287. /// \param Fns The set of non-member functions that will be
  11288. /// considered by overload resolution. The caller needs to build this
  11289. /// set based on the context using, e.g.,
  11290. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  11291. /// set should not contain any member functions; those will be added
  11292. /// by CreateOverloadedBinOp().
  11293. ///
  11294. /// \param LHS Left-hand argument.
  11295. /// \param RHS Right-hand argument.
  11296. ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  11297. BinaryOperatorKind Opc,
  11298. const UnresolvedSetImpl &Fns, Expr *LHS,
  11299. Expr *RHS, bool PerformADL,
  11300. bool AllowRewrittenCandidates) {
  11301. Expr *Args[2] = { LHS, RHS };
  11302. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  11303. if (!getLangOpts().CPlusPlus2a)
  11304. AllowRewrittenCandidates = false;
  11305. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  11306. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  11307. // If either side is type-dependent, create an appropriate dependent
  11308. // expression.
  11309. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  11310. if (Fns.empty()) {
  11311. // If there are no functions to store, just build a dependent
  11312. // BinaryOperator or CompoundAssignment.
  11313. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  11314. return new (Context) BinaryOperator(
  11315. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  11316. OpLoc, FPFeatures);
  11317. return new (Context) CompoundAssignOperator(
  11318. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  11319. Context.DependentTy, Context.DependentTy, OpLoc,
  11320. FPFeatures);
  11321. }
  11322. // FIXME: save results of ADL from here?
  11323. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11324. // TODO: provide better source location info in DNLoc component.
  11325. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  11326. UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
  11327. Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
  11328. /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
  11329. return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
  11330. Context.DependentTy, VK_RValue, OpLoc,
  11331. FPFeatures);
  11332. }
  11333. // Always do placeholder-like conversions on the RHS.
  11334. if (checkPlaceholderForOverload(*this, Args[1]))
  11335. return ExprError();
  11336. // Do placeholder-like conversion on the LHS; note that we should
  11337. // not get here with a PseudoObject LHS.
  11338. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  11339. if (checkPlaceholderForOverload(*this, Args[0]))
  11340. return ExprError();
  11341. // If this is the assignment operator, we only perform overload resolution
  11342. // if the left-hand side is a class or enumeration type. This is actually
  11343. // a hack. The standard requires that we do overload resolution between the
  11344. // various built-in candidates, but as DR507 points out, this can lead to
  11345. // problems. So we do it this way, which pretty much follows what GCC does.
  11346. // Note that we go the traditional code path for compound assignment forms.
  11347. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  11348. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11349. // If this is the .* operator, which is not overloadable, just
  11350. // create a built-in binary operator.
  11351. if (Opc == BO_PtrMemD)
  11352. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11353. // Build an empty overload set.
  11354. OverloadCandidateSet CandidateSet(
  11355. OpLoc, OverloadCandidateSet::CSK_Operator,
  11356. OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
  11357. OverloadedOperatorKind ExtraOp =
  11358. AllowRewrittenCandidates ? getRewrittenOverloadedOperator(Op) : OO_None;
  11359. // Add the candidates from the given function set. This also adds the
  11360. // rewritten candidates using these functions if necessary.
  11361. AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
  11362. // Add operator candidates that are member functions.
  11363. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  11364. if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
  11365. AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
  11366. OverloadCandidateParamOrder::Reversed);
  11367. // In C++20, also add any rewritten member candidates.
  11368. if (ExtraOp) {
  11369. AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
  11370. if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
  11371. AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
  11372. CandidateSet,
  11373. OverloadCandidateParamOrder::Reversed);
  11374. }
  11375. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  11376. // performed for an assignment operator (nor for operator[] nor operator->,
  11377. // which don't get here).
  11378. if (Opc != BO_Assign && PerformADL) {
  11379. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  11380. /*ExplicitTemplateArgs*/ nullptr,
  11381. CandidateSet);
  11382. if (ExtraOp) {
  11383. DeclarationName ExtraOpName =
  11384. Context.DeclarationNames.getCXXOperatorName(ExtraOp);
  11385. AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
  11386. /*ExplicitTemplateArgs*/ nullptr,
  11387. CandidateSet);
  11388. }
  11389. }
  11390. // Add builtin operator candidates.
  11391. //
  11392. // FIXME: We don't add any rewritten candidates here. This is strictly
  11393. // incorrect; a builtin candidate could be hidden by a non-viable candidate,
  11394. // resulting in our selecting a rewritten builtin candidate. For example:
  11395. //
  11396. // enum class E { e };
  11397. // bool operator!=(E, E) requires false;
  11398. // bool k = E::e != E::e;
  11399. //
  11400. // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
  11401. // it seems unreasonable to consider rewritten builtin candidates. A core
  11402. // issue has been filed proposing to removed this requirement.
  11403. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  11404. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11405. // Perform overload resolution.
  11406. OverloadCandidateSet::iterator Best;
  11407. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  11408. case OR_Success: {
  11409. // We found a built-in operator or an overloaded operator.
  11410. FunctionDecl *FnDecl = Best->Function;
  11411. bool IsReversed = (Best->RewriteKind & CRK_Reversed);
  11412. if (IsReversed)
  11413. std::swap(Args[0], Args[1]);
  11414. if (FnDecl) {
  11415. Expr *Base = nullptr;
  11416. // We matched an overloaded operator. Build a call to that
  11417. // operator.
  11418. OverloadedOperatorKind ChosenOp =
  11419. FnDecl->getDeclName().getCXXOverloadedOperator();
  11420. // C++2a [over.match.oper]p9:
  11421. // If a rewritten operator== candidate is selected by overload
  11422. // resolution for an operator@, its return type shall be cv bool
  11423. if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
  11424. !FnDecl->getReturnType()->isBooleanType()) {
  11425. Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
  11426. << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
  11427. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11428. Diag(FnDecl->getLocation(), diag::note_declared_at);
  11429. return ExprError();
  11430. }
  11431. if (AllowRewrittenCandidates && !IsReversed &&
  11432. CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
  11433. // We could have reversed this operator, but didn't. Check if the
  11434. // reversed form was a viable candidate, and if so, if it had a
  11435. // better conversion for either parameter. If so, this call is
  11436. // formally ambiguous, and allowing it is an extension.
  11437. for (OverloadCandidate &Cand : CandidateSet) {
  11438. if (Cand.Viable && Cand.Function == FnDecl &&
  11439. Cand.RewriteKind & CRK_Reversed) {
  11440. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  11441. if (CompareImplicitConversionSequences(
  11442. *this, OpLoc, Cand.Conversions[ArgIdx],
  11443. Best->Conversions[ArgIdx]) ==
  11444. ImplicitConversionSequence::Better) {
  11445. Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
  11446. << BinaryOperator::getOpcodeStr(Opc)
  11447. << Args[0]->getType() << Args[1]->getType()
  11448. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11449. Diag(FnDecl->getLocation(),
  11450. diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
  11451. }
  11452. }
  11453. break;
  11454. }
  11455. }
  11456. }
  11457. // Convert the arguments.
  11458. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11459. // Best->Access is only meaningful for class members.
  11460. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  11461. ExprResult Arg1 =
  11462. PerformCopyInitialization(
  11463. InitializedEntity::InitializeParameter(Context,
  11464. FnDecl->getParamDecl(0)),
  11465. SourceLocation(), Args[1]);
  11466. if (Arg1.isInvalid())
  11467. return ExprError();
  11468. ExprResult Arg0 =
  11469. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  11470. Best->FoundDecl, Method);
  11471. if (Arg0.isInvalid())
  11472. return ExprError();
  11473. Base = Args[0] = Arg0.getAs<Expr>();
  11474. Args[1] = RHS = Arg1.getAs<Expr>();
  11475. } else {
  11476. // Convert the arguments.
  11477. ExprResult Arg0 = PerformCopyInitialization(
  11478. InitializedEntity::InitializeParameter(Context,
  11479. FnDecl->getParamDecl(0)),
  11480. SourceLocation(), Args[0]);
  11481. if (Arg0.isInvalid())
  11482. return ExprError();
  11483. ExprResult Arg1 =
  11484. PerformCopyInitialization(
  11485. InitializedEntity::InitializeParameter(Context,
  11486. FnDecl->getParamDecl(1)),
  11487. SourceLocation(), Args[1]);
  11488. if (Arg1.isInvalid())
  11489. return ExprError();
  11490. Args[0] = LHS = Arg0.getAs<Expr>();
  11491. Args[1] = RHS = Arg1.getAs<Expr>();
  11492. }
  11493. // Build the actual expression node.
  11494. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  11495. Best->FoundDecl, Base,
  11496. HadMultipleCandidates, OpLoc);
  11497. if (FnExpr.isInvalid())
  11498. return ExprError();
  11499. // Determine the result type.
  11500. QualType ResultTy = FnDecl->getReturnType();
  11501. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11502. ResultTy = ResultTy.getNonLValueExprType(Context);
  11503. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  11504. Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
  11505. FPFeatures, Best->IsADLCandidate);
  11506. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  11507. FnDecl))
  11508. return ExprError();
  11509. ArrayRef<const Expr *> ArgsArray(Args, 2);
  11510. const Expr *ImplicitThis = nullptr;
  11511. // Cut off the implicit 'this'.
  11512. if (isa<CXXMethodDecl>(FnDecl)) {
  11513. ImplicitThis = ArgsArray[0];
  11514. ArgsArray = ArgsArray.slice(1);
  11515. }
  11516. // Check for a self move.
  11517. if (Op == OO_Equal)
  11518. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  11519. checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
  11520. isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
  11521. VariadicDoesNotApply);
  11522. ExprResult R = MaybeBindToTemporary(TheCall);
  11523. if (R.isInvalid())
  11524. return ExprError();
  11525. // For a rewritten candidate, we've already reversed the arguments
  11526. // if needed. Perform the rest of the rewrite now.
  11527. if ((Best->RewriteKind & CRK_DifferentOperator) ||
  11528. (Op == OO_Spaceship && IsReversed)) {
  11529. if (Op == OO_ExclaimEqual) {
  11530. assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
  11531. R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
  11532. } else {
  11533. assert(ChosenOp == OO_Spaceship && "unexpected operator name");
  11534. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  11535. Expr *ZeroLiteral =
  11536. IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
  11537. Sema::CodeSynthesisContext Ctx;
  11538. Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
  11539. Ctx.Entity = FnDecl;
  11540. pushCodeSynthesisContext(Ctx);
  11541. R = CreateOverloadedBinOp(
  11542. OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
  11543. IsReversed ? R.get() : ZeroLiteral, PerformADL,
  11544. /*AllowRewrittenCandidates=*/false);
  11545. popCodeSynthesisContext();
  11546. }
  11547. if (R.isInvalid())
  11548. return ExprError();
  11549. } else {
  11550. assert(ChosenOp == Op && "unexpected operator name");
  11551. }
  11552. // Make a note in the AST if we did any rewriting.
  11553. if (Best->RewriteKind != CRK_None)
  11554. R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
  11555. return R;
  11556. } else {
  11557. // We matched a built-in operator. Convert the arguments, then
  11558. // break out so that we will build the appropriate built-in
  11559. // operator node.
  11560. ExprResult ArgsRes0 = PerformImplicitConversion(
  11561. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  11562. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11563. if (ArgsRes0.isInvalid())
  11564. return ExprError();
  11565. Args[0] = ArgsRes0.get();
  11566. ExprResult ArgsRes1 = PerformImplicitConversion(
  11567. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  11568. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11569. if (ArgsRes1.isInvalid())
  11570. return ExprError();
  11571. Args[1] = ArgsRes1.get();
  11572. break;
  11573. }
  11574. }
  11575. case OR_No_Viable_Function: {
  11576. // C++ [over.match.oper]p9:
  11577. // If the operator is the operator , [...] and there are no
  11578. // viable functions, then the operator is assumed to be the
  11579. // built-in operator and interpreted according to clause 5.
  11580. if (Opc == BO_Comma)
  11581. break;
  11582. // For class as left operand for assignment or compound assignment
  11583. // operator do not fall through to handling in built-in, but report that
  11584. // no overloaded assignment operator found
  11585. ExprResult Result = ExprError();
  11586. StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
  11587. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
  11588. Args, OpLoc);
  11589. if (Args[0]->getType()->isRecordType() &&
  11590. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  11591. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  11592. << BinaryOperator::getOpcodeStr(Opc)
  11593. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11594. if (Args[0]->getType()->isIncompleteType()) {
  11595. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  11596. << Args[0]->getType()
  11597. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11598. }
  11599. } else {
  11600. // This is an erroneous use of an operator which can be overloaded by
  11601. // a non-member function. Check for non-member operators which were
  11602. // defined too late to be candidates.
  11603. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  11604. // FIXME: Recover by calling the found function.
  11605. return ExprError();
  11606. // No viable function; try to create a built-in operation, which will
  11607. // produce an error. Then, show the non-viable candidates.
  11608. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11609. }
  11610. assert(Result.isInvalid() &&
  11611. "C++ binary operator overloading is missing candidates!");
  11612. CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
  11613. return Result;
  11614. }
  11615. case OR_Ambiguous:
  11616. CandidateSet.NoteCandidates(
  11617. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  11618. << BinaryOperator::getOpcodeStr(Opc)
  11619. << Args[0]->getType()
  11620. << Args[1]->getType()
  11621. << Args[0]->getSourceRange()
  11622. << Args[1]->getSourceRange()),
  11623. *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  11624. OpLoc);
  11625. return ExprError();
  11626. case OR_Deleted:
  11627. if (isImplicitlyDeleted(Best->Function)) {
  11628. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  11629. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  11630. << Context.getRecordType(Method->getParent())
  11631. << getSpecialMember(Method);
  11632. // The user probably meant to call this special member. Just
  11633. // explain why it's deleted.
  11634. NoteDeletedFunction(Method);
  11635. return ExprError();
  11636. }
  11637. CandidateSet.NoteCandidates(
  11638. PartialDiagnosticAt(
  11639. OpLoc, PDiag(diag::err_ovl_deleted_oper)
  11640. << getOperatorSpelling(Best->Function->getDeclName()
  11641. .getCXXOverloadedOperator())
  11642. << Args[0]->getSourceRange()
  11643. << Args[1]->getSourceRange()),
  11644. *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  11645. OpLoc);
  11646. return ExprError();
  11647. }
  11648. // We matched a built-in operator; build it.
  11649. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11650. }
  11651. ExprResult
  11652. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  11653. SourceLocation RLoc,
  11654. Expr *Base, Expr *Idx) {
  11655. Expr *Args[2] = { Base, Idx };
  11656. DeclarationName OpName =
  11657. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  11658. // If either side is type-dependent, create an appropriate dependent
  11659. // expression.
  11660. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  11661. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11662. // CHECKME: no 'operator' keyword?
  11663. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  11664. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  11665. UnresolvedLookupExpr *Fn
  11666. = UnresolvedLookupExpr::Create(Context, NamingClass,
  11667. NestedNameSpecifierLoc(), OpNameInfo,
  11668. /*ADL*/ true, /*Overloaded*/ false,
  11669. UnresolvedSetIterator(),
  11670. UnresolvedSetIterator());
  11671. // Can't add any actual overloads yet
  11672. return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
  11673. Context.DependentTy, VK_RValue, RLoc,
  11674. FPOptions());
  11675. }
  11676. // Handle placeholders on both operands.
  11677. if (checkPlaceholderForOverload(*this, Args[0]))
  11678. return ExprError();
  11679. if (checkPlaceholderForOverload(*this, Args[1]))
  11680. return ExprError();
  11681. // Build an empty overload set.
  11682. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  11683. // Subscript can only be overloaded as a member function.
  11684. // Add operator candidates that are member functions.
  11685. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  11686. // Add builtin operator candidates.
  11687. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  11688. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11689. // Perform overload resolution.
  11690. OverloadCandidateSet::iterator Best;
  11691. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  11692. case OR_Success: {
  11693. // We found a built-in operator or an overloaded operator.
  11694. FunctionDecl *FnDecl = Best->Function;
  11695. if (FnDecl) {
  11696. // We matched an overloaded operator. Build a call to that
  11697. // operator.
  11698. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  11699. // Convert the arguments.
  11700. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  11701. ExprResult Arg0 =
  11702. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  11703. Best->FoundDecl, Method);
  11704. if (Arg0.isInvalid())
  11705. return ExprError();
  11706. Args[0] = Arg0.get();
  11707. // Convert the arguments.
  11708. ExprResult InputInit
  11709. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11710. Context,
  11711. FnDecl->getParamDecl(0)),
  11712. SourceLocation(),
  11713. Args[1]);
  11714. if (InputInit.isInvalid())
  11715. return ExprError();
  11716. Args[1] = InputInit.getAs<Expr>();
  11717. // Build the actual expression node.
  11718. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  11719. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  11720. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  11721. Best->FoundDecl,
  11722. Base,
  11723. HadMultipleCandidates,
  11724. OpLocInfo.getLoc(),
  11725. OpLocInfo.getInfo());
  11726. if (FnExpr.isInvalid())
  11727. return ExprError();
  11728. // Determine the result type
  11729. QualType ResultTy = FnDecl->getReturnType();
  11730. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11731. ResultTy = ResultTy.getNonLValueExprType(Context);
  11732. CXXOperatorCallExpr *TheCall =
  11733. CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
  11734. Args, ResultTy, VK, RLoc, FPOptions());
  11735. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  11736. return ExprError();
  11737. if (CheckFunctionCall(Method, TheCall,
  11738. Method->getType()->castAs<FunctionProtoType>()))
  11739. return ExprError();
  11740. return MaybeBindToTemporary(TheCall);
  11741. } else {
  11742. // We matched a built-in operator. Convert the arguments, then
  11743. // break out so that we will build the appropriate built-in
  11744. // operator node.
  11745. ExprResult ArgsRes0 = PerformImplicitConversion(
  11746. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  11747. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11748. if (ArgsRes0.isInvalid())
  11749. return ExprError();
  11750. Args[0] = ArgsRes0.get();
  11751. ExprResult ArgsRes1 = PerformImplicitConversion(
  11752. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  11753. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11754. if (ArgsRes1.isInvalid())
  11755. return ExprError();
  11756. Args[1] = ArgsRes1.get();
  11757. break;
  11758. }
  11759. }
  11760. case OR_No_Viable_Function: {
  11761. PartialDiagnostic PD = CandidateSet.empty()
  11762. ? (PDiag(diag::err_ovl_no_oper)
  11763. << Args[0]->getType() << /*subscript*/ 0
  11764. << Args[0]->getSourceRange() << Args[1]->getSourceRange())
  11765. : (PDiag(diag::err_ovl_no_viable_subscript)
  11766. << Args[0]->getType() << Args[0]->getSourceRange()
  11767. << Args[1]->getSourceRange());
  11768. CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
  11769. OCD_AllCandidates, Args, "[]", LLoc);
  11770. return ExprError();
  11771. }
  11772. case OR_Ambiguous:
  11773. CandidateSet.NoteCandidates(
  11774. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  11775. << "[]" << Args[0]->getType()
  11776. << Args[1]->getType()
  11777. << Args[0]->getSourceRange()
  11778. << Args[1]->getSourceRange()),
  11779. *this, OCD_ViableCandidates, Args, "[]", LLoc);
  11780. return ExprError();
  11781. case OR_Deleted:
  11782. CandidateSet.NoteCandidates(
  11783. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
  11784. << "[]" << Args[0]->getSourceRange()
  11785. << Args[1]->getSourceRange()),
  11786. *this, OCD_AllCandidates, Args, "[]", LLoc);
  11787. return ExprError();
  11788. }
  11789. // We matched a built-in operator; build it.
  11790. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  11791. }
  11792. /// BuildCallToMemberFunction - Build a call to a member
  11793. /// function. MemExpr is the expression that refers to the member
  11794. /// function (and includes the object parameter), Args/NumArgs are the
  11795. /// arguments to the function call (not including the object
  11796. /// parameter). The caller needs to validate that the member
  11797. /// expression refers to a non-static member function or an overloaded
  11798. /// member function.
  11799. ExprResult
  11800. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  11801. SourceLocation LParenLoc,
  11802. MultiExprArg Args,
  11803. SourceLocation RParenLoc) {
  11804. assert(MemExprE->getType() == Context.BoundMemberTy ||
  11805. MemExprE->getType() == Context.OverloadTy);
  11806. // Dig out the member expression. This holds both the object
  11807. // argument and the member function we're referring to.
  11808. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  11809. // Determine whether this is a call to a pointer-to-member function.
  11810. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  11811. assert(op->getType() == Context.BoundMemberTy);
  11812. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  11813. QualType fnType =
  11814. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  11815. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  11816. QualType resultType = proto->getCallResultType(Context);
  11817. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  11818. // Check that the object type isn't more qualified than the
  11819. // member function we're calling.
  11820. Qualifiers funcQuals = proto->getMethodQuals();
  11821. QualType objectType = op->getLHS()->getType();
  11822. if (op->getOpcode() == BO_PtrMemI)
  11823. objectType = objectType->castAs<PointerType>()->getPointeeType();
  11824. Qualifiers objectQuals = objectType.getQualifiers();
  11825. Qualifiers difference = objectQuals - funcQuals;
  11826. difference.removeObjCGCAttr();
  11827. difference.removeAddressSpace();
  11828. if (difference) {
  11829. std::string qualsString = difference.getAsString();
  11830. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  11831. << fnType.getUnqualifiedType()
  11832. << qualsString
  11833. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  11834. }
  11835. CXXMemberCallExpr *call =
  11836. CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
  11837. valueKind, RParenLoc, proto->getNumParams());
  11838. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
  11839. call, nullptr))
  11840. return ExprError();
  11841. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  11842. return ExprError();
  11843. if (CheckOtherCall(call, proto))
  11844. return ExprError();
  11845. return MaybeBindToTemporary(call);
  11846. }
  11847. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  11848. return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
  11849. RParenLoc);
  11850. UnbridgedCastsSet UnbridgedCasts;
  11851. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  11852. return ExprError();
  11853. MemberExpr *MemExpr;
  11854. CXXMethodDecl *Method = nullptr;
  11855. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  11856. NestedNameSpecifier *Qualifier = nullptr;
  11857. if (isa<MemberExpr>(NakedMemExpr)) {
  11858. MemExpr = cast<MemberExpr>(NakedMemExpr);
  11859. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  11860. FoundDecl = MemExpr->getFoundDecl();
  11861. Qualifier = MemExpr->getQualifier();
  11862. UnbridgedCasts.restore();
  11863. } else {
  11864. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  11865. Qualifier = UnresExpr->getQualifier();
  11866. QualType ObjectType = UnresExpr->getBaseType();
  11867. Expr::Classification ObjectClassification
  11868. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  11869. : UnresExpr->getBase()->Classify(Context);
  11870. // Add overload candidates
  11871. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  11872. OverloadCandidateSet::CSK_Normal);
  11873. // FIXME: avoid copy.
  11874. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11875. if (UnresExpr->hasExplicitTemplateArgs()) {
  11876. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11877. TemplateArgs = &TemplateArgsBuffer;
  11878. }
  11879. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  11880. E = UnresExpr->decls_end(); I != E; ++I) {
  11881. NamedDecl *Func = *I;
  11882. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  11883. if (isa<UsingShadowDecl>(Func))
  11884. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  11885. // Microsoft supports direct constructor calls.
  11886. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  11887. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
  11888. CandidateSet,
  11889. /*SuppressUserConversions*/ false);
  11890. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  11891. // If explicit template arguments were provided, we can't call a
  11892. // non-template member function.
  11893. if (TemplateArgs)
  11894. continue;
  11895. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  11896. ObjectClassification, Args, CandidateSet,
  11897. /*SuppressUserConversions=*/false);
  11898. } else {
  11899. AddMethodTemplateCandidate(
  11900. cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
  11901. TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
  11902. /*SuppressUserConversions=*/false);
  11903. }
  11904. }
  11905. DeclarationName DeclName = UnresExpr->getMemberName();
  11906. UnbridgedCasts.restore();
  11907. OverloadCandidateSet::iterator Best;
  11908. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
  11909. Best)) {
  11910. case OR_Success:
  11911. Method = cast<CXXMethodDecl>(Best->Function);
  11912. FoundDecl = Best->FoundDecl;
  11913. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  11914. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  11915. return ExprError();
  11916. // If FoundDecl is different from Method (such as if one is a template
  11917. // and the other a specialization), make sure DiagnoseUseOfDecl is
  11918. // called on both.
  11919. // FIXME: This would be more comprehensively addressed by modifying
  11920. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  11921. // being used.
  11922. if (Method != FoundDecl.getDecl() &&
  11923. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  11924. return ExprError();
  11925. break;
  11926. case OR_No_Viable_Function:
  11927. CandidateSet.NoteCandidates(
  11928. PartialDiagnosticAt(
  11929. UnresExpr->getMemberLoc(),
  11930. PDiag(diag::err_ovl_no_viable_member_function_in_call)
  11931. << DeclName << MemExprE->getSourceRange()),
  11932. *this, OCD_AllCandidates, Args);
  11933. // FIXME: Leaking incoming expressions!
  11934. return ExprError();
  11935. case OR_Ambiguous:
  11936. CandidateSet.NoteCandidates(
  11937. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  11938. PDiag(diag::err_ovl_ambiguous_member_call)
  11939. << DeclName << MemExprE->getSourceRange()),
  11940. *this, OCD_AllCandidates, Args);
  11941. // FIXME: Leaking incoming expressions!
  11942. return ExprError();
  11943. case OR_Deleted:
  11944. CandidateSet.NoteCandidates(
  11945. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  11946. PDiag(diag::err_ovl_deleted_member_call)
  11947. << DeclName << MemExprE->getSourceRange()),
  11948. *this, OCD_AllCandidates, Args);
  11949. // FIXME: Leaking incoming expressions!
  11950. return ExprError();
  11951. }
  11952. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  11953. // If overload resolution picked a static member, build a
  11954. // non-member call based on that function.
  11955. if (Method->isStatic()) {
  11956. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  11957. RParenLoc);
  11958. }
  11959. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  11960. }
  11961. QualType ResultType = Method->getReturnType();
  11962. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  11963. ResultType = ResultType.getNonLValueExprType(Context);
  11964. assert(Method && "Member call to something that isn't a method?");
  11965. const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
  11966. CXXMemberCallExpr *TheCall =
  11967. CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
  11968. RParenLoc, Proto->getNumParams());
  11969. // Check for a valid return type.
  11970. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  11971. TheCall, Method))
  11972. return ExprError();
  11973. // Convert the object argument (for a non-static member function call).
  11974. // We only need to do this if there was actually an overload; otherwise
  11975. // it was done at lookup.
  11976. if (!Method->isStatic()) {
  11977. ExprResult ObjectArg =
  11978. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  11979. FoundDecl, Method);
  11980. if (ObjectArg.isInvalid())
  11981. return ExprError();
  11982. MemExpr->setBase(ObjectArg.get());
  11983. }
  11984. // Convert the rest of the arguments
  11985. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  11986. RParenLoc))
  11987. return ExprError();
  11988. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  11989. if (CheckFunctionCall(Method, TheCall, Proto))
  11990. return ExprError();
  11991. // In the case the method to call was not selected by the overloading
  11992. // resolution process, we still need to handle the enable_if attribute. Do
  11993. // that here, so it will not hide previous -- and more relevant -- errors.
  11994. if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
  11995. if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
  11996. Diag(MemE->getMemberLoc(),
  11997. diag::err_ovl_no_viable_member_function_in_call)
  11998. << Method << Method->getSourceRange();
  11999. Diag(Method->getLocation(),
  12000. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  12001. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  12002. return ExprError();
  12003. }
  12004. }
  12005. if ((isa<CXXConstructorDecl>(CurContext) ||
  12006. isa<CXXDestructorDecl>(CurContext)) &&
  12007. TheCall->getMethodDecl()->isPure()) {
  12008. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  12009. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
  12010. MemExpr->performsVirtualDispatch(getLangOpts())) {
  12011. Diag(MemExpr->getBeginLoc(),
  12012. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  12013. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  12014. << MD->getParent()->getDeclName();
  12015. Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
  12016. if (getLangOpts().AppleKext)
  12017. Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
  12018. << MD->getParent()->getDeclName() << MD->getDeclName();
  12019. }
  12020. }
  12021. if (CXXDestructorDecl *DD =
  12022. dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
  12023. // a->A::f() doesn't go through the vtable, except in AppleKext mode.
  12024. bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
  12025. CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
  12026. CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
  12027. MemExpr->getMemberLoc());
  12028. }
  12029. return MaybeBindToTemporary(TheCall);
  12030. }
  12031. /// BuildCallToObjectOfClassType - Build a call to an object of class
  12032. /// type (C++ [over.call.object]), which can end up invoking an
  12033. /// overloaded function call operator (@c operator()) or performing a
  12034. /// user-defined conversion on the object argument.
  12035. ExprResult
  12036. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  12037. SourceLocation LParenLoc,
  12038. MultiExprArg Args,
  12039. SourceLocation RParenLoc) {
  12040. if (checkPlaceholderForOverload(*this, Obj))
  12041. return ExprError();
  12042. ExprResult Object = Obj;
  12043. UnbridgedCastsSet UnbridgedCasts;
  12044. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  12045. return ExprError();
  12046. assert(Object.get()->getType()->isRecordType() &&
  12047. "Requires object type argument");
  12048. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  12049. // C++ [over.call.object]p1:
  12050. // If the primary-expression E in the function call syntax
  12051. // evaluates to a class object of type "cv T", then the set of
  12052. // candidate functions includes at least the function call
  12053. // operators of T. The function call operators of T are obtained by
  12054. // ordinary lookup of the name operator() in the context of
  12055. // (E).operator().
  12056. OverloadCandidateSet CandidateSet(LParenLoc,
  12057. OverloadCandidateSet::CSK_Operator);
  12058. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  12059. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  12060. diag::err_incomplete_object_call, Object.get()))
  12061. return true;
  12062. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  12063. LookupQualifiedName(R, Record->getDecl());
  12064. R.suppressDiagnostics();
  12065. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  12066. Oper != OperEnd; ++Oper) {
  12067. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  12068. Object.get()->Classify(Context), Args, CandidateSet,
  12069. /*SuppressUserConversion=*/false);
  12070. }
  12071. // C++ [over.call.object]p2:
  12072. // In addition, for each (non-explicit in C++0x) conversion function
  12073. // declared in T of the form
  12074. //
  12075. // operator conversion-type-id () cv-qualifier;
  12076. //
  12077. // where cv-qualifier is the same cv-qualification as, or a
  12078. // greater cv-qualification than, cv, and where conversion-type-id
  12079. // denotes the type "pointer to function of (P1,...,Pn) returning
  12080. // R", or the type "reference to pointer to function of
  12081. // (P1,...,Pn) returning R", or the type "reference to function
  12082. // of (P1,...,Pn) returning R", a surrogate call function [...]
  12083. // is also considered as a candidate function. Similarly,
  12084. // surrogate call functions are added to the set of candidate
  12085. // functions for each conversion function declared in an
  12086. // accessible base class provided the function is not hidden
  12087. // within T by another intervening declaration.
  12088. const auto &Conversions =
  12089. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  12090. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  12091. NamedDecl *D = *I;
  12092. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  12093. if (isa<UsingShadowDecl>(D))
  12094. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  12095. // Skip over templated conversion functions; they aren't
  12096. // surrogates.
  12097. if (isa<FunctionTemplateDecl>(D))
  12098. continue;
  12099. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  12100. if (!Conv->isExplicit()) {
  12101. // Strip the reference type (if any) and then the pointer type (if
  12102. // any) to get down to what might be a function type.
  12103. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  12104. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  12105. ConvType = ConvPtrType->getPointeeType();
  12106. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  12107. {
  12108. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  12109. Object.get(), Args, CandidateSet);
  12110. }
  12111. }
  12112. }
  12113. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12114. // Perform overload resolution.
  12115. OverloadCandidateSet::iterator Best;
  12116. switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
  12117. Best)) {
  12118. case OR_Success:
  12119. // Overload resolution succeeded; we'll build the appropriate call
  12120. // below.
  12121. break;
  12122. case OR_No_Viable_Function: {
  12123. PartialDiagnostic PD =
  12124. CandidateSet.empty()
  12125. ? (PDiag(diag::err_ovl_no_oper)
  12126. << Object.get()->getType() << /*call*/ 1
  12127. << Object.get()->getSourceRange())
  12128. : (PDiag(diag::err_ovl_no_viable_object_call)
  12129. << Object.get()->getType() << Object.get()->getSourceRange());
  12130. CandidateSet.NoteCandidates(
  12131. PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
  12132. OCD_AllCandidates, Args);
  12133. break;
  12134. }
  12135. case OR_Ambiguous:
  12136. CandidateSet.NoteCandidates(
  12137. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  12138. PDiag(diag::err_ovl_ambiguous_object_call)
  12139. << Object.get()->getType()
  12140. << Object.get()->getSourceRange()),
  12141. *this, OCD_ViableCandidates, Args);
  12142. break;
  12143. case OR_Deleted:
  12144. CandidateSet.NoteCandidates(
  12145. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  12146. PDiag(diag::err_ovl_deleted_object_call)
  12147. << Object.get()->getType()
  12148. << Object.get()->getSourceRange()),
  12149. *this, OCD_AllCandidates, Args);
  12150. break;
  12151. }
  12152. if (Best == CandidateSet.end())
  12153. return true;
  12154. UnbridgedCasts.restore();
  12155. if (Best->Function == nullptr) {
  12156. // Since there is no function declaration, this is one of the
  12157. // surrogate candidates. Dig out the conversion function.
  12158. CXXConversionDecl *Conv
  12159. = cast<CXXConversionDecl>(
  12160. Best->Conversions[0].UserDefined.ConversionFunction);
  12161. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  12162. Best->FoundDecl);
  12163. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  12164. return ExprError();
  12165. assert(Conv == Best->FoundDecl.getDecl() &&
  12166. "Found Decl & conversion-to-functionptr should be same, right?!");
  12167. // We selected one of the surrogate functions that converts the
  12168. // object parameter to a function pointer. Perform the conversion
  12169. // on the object argument, then let BuildCallExpr finish the job.
  12170. // Create an implicit member expr to refer to the conversion operator.
  12171. // and then call it.
  12172. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  12173. Conv, HadMultipleCandidates);
  12174. if (Call.isInvalid())
  12175. return ExprError();
  12176. // Record usage of conversion in an implicit cast.
  12177. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  12178. CK_UserDefinedConversion, Call.get(),
  12179. nullptr, VK_RValue);
  12180. return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  12181. }
  12182. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  12183. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  12184. // that calls this method, using Object for the implicit object
  12185. // parameter and passing along the remaining arguments.
  12186. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  12187. // An error diagnostic has already been printed when parsing the declaration.
  12188. if (Method->isInvalidDecl())
  12189. return ExprError();
  12190. const FunctionProtoType *Proto =
  12191. Method->getType()->getAs<FunctionProtoType>();
  12192. unsigned NumParams = Proto->getNumParams();
  12193. DeclarationNameInfo OpLocInfo(
  12194. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  12195. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  12196. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  12197. Obj, HadMultipleCandidates,
  12198. OpLocInfo.getLoc(),
  12199. OpLocInfo.getInfo());
  12200. if (NewFn.isInvalid())
  12201. return true;
  12202. // The number of argument slots to allocate in the call. If we have default
  12203. // arguments we need to allocate space for them as well. We additionally
  12204. // need one more slot for the object parameter.
  12205. unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
  12206. // Build the full argument list for the method call (the implicit object
  12207. // parameter is placed at the beginning of the list).
  12208. SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
  12209. bool IsError = false;
  12210. // Initialize the implicit object parameter.
  12211. ExprResult ObjRes =
  12212. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  12213. Best->FoundDecl, Method);
  12214. if (ObjRes.isInvalid())
  12215. IsError = true;
  12216. else
  12217. Object = ObjRes;
  12218. MethodArgs[0] = Object.get();
  12219. // Check the argument types.
  12220. for (unsigned i = 0; i != NumParams; i++) {
  12221. Expr *Arg;
  12222. if (i < Args.size()) {
  12223. Arg = Args[i];
  12224. // Pass the argument.
  12225. ExprResult InputInit
  12226. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  12227. Context,
  12228. Method->getParamDecl(i)),
  12229. SourceLocation(), Arg);
  12230. IsError |= InputInit.isInvalid();
  12231. Arg = InputInit.getAs<Expr>();
  12232. } else {
  12233. ExprResult DefArg
  12234. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  12235. if (DefArg.isInvalid()) {
  12236. IsError = true;
  12237. break;
  12238. }
  12239. Arg = DefArg.getAs<Expr>();
  12240. }
  12241. MethodArgs[i + 1] = Arg;
  12242. }
  12243. // If this is a variadic call, handle args passed through "...".
  12244. if (Proto->isVariadic()) {
  12245. // Promote the arguments (C99 6.5.2.2p7).
  12246. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  12247. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  12248. nullptr);
  12249. IsError |= Arg.isInvalid();
  12250. MethodArgs[i + 1] = Arg.get();
  12251. }
  12252. }
  12253. if (IsError)
  12254. return true;
  12255. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  12256. // Once we've built TheCall, all of the expressions are properly owned.
  12257. QualType ResultTy = Method->getReturnType();
  12258. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12259. ResultTy = ResultTy.getNonLValueExprType(Context);
  12260. CXXOperatorCallExpr *TheCall =
  12261. CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
  12262. ResultTy, VK, RParenLoc, FPOptions());
  12263. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  12264. return true;
  12265. if (CheckFunctionCall(Method, TheCall, Proto))
  12266. return true;
  12267. return MaybeBindToTemporary(TheCall);
  12268. }
  12269. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  12270. /// (if one exists), where @c Base is an expression of class type and
  12271. /// @c Member is the name of the member we're trying to find.
  12272. ExprResult
  12273. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  12274. bool *NoArrowOperatorFound) {
  12275. assert(Base->getType()->isRecordType() &&
  12276. "left-hand side must have class type");
  12277. if (checkPlaceholderForOverload(*this, Base))
  12278. return ExprError();
  12279. SourceLocation Loc = Base->getExprLoc();
  12280. // C++ [over.ref]p1:
  12281. //
  12282. // [...] An expression x->m is interpreted as (x.operator->())->m
  12283. // for a class object x of type T if T::operator->() exists and if
  12284. // the operator is selected as the best match function by the
  12285. // overload resolution mechanism (13.3).
  12286. DeclarationName OpName =
  12287. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  12288. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  12289. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  12290. if (RequireCompleteType(Loc, Base->getType(),
  12291. diag::err_typecheck_incomplete_tag, Base))
  12292. return ExprError();
  12293. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  12294. LookupQualifiedName(R, BaseRecord->getDecl());
  12295. R.suppressDiagnostics();
  12296. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  12297. Oper != OperEnd; ++Oper) {
  12298. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  12299. None, CandidateSet, /*SuppressUserConversion=*/false);
  12300. }
  12301. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12302. // Perform overload resolution.
  12303. OverloadCandidateSet::iterator Best;
  12304. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  12305. case OR_Success:
  12306. // Overload resolution succeeded; we'll build the call below.
  12307. break;
  12308. case OR_No_Viable_Function: {
  12309. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
  12310. if (CandidateSet.empty()) {
  12311. QualType BaseType = Base->getType();
  12312. if (NoArrowOperatorFound) {
  12313. // Report this specific error to the caller instead of emitting a
  12314. // diagnostic, as requested.
  12315. *NoArrowOperatorFound = true;
  12316. return ExprError();
  12317. }
  12318. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  12319. << BaseType << Base->getSourceRange();
  12320. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  12321. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  12322. << FixItHint::CreateReplacement(OpLoc, ".");
  12323. }
  12324. } else
  12325. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  12326. << "operator->" << Base->getSourceRange();
  12327. CandidateSet.NoteCandidates(*this, Base, Cands);
  12328. return ExprError();
  12329. }
  12330. case OR_Ambiguous:
  12331. CandidateSet.NoteCandidates(
  12332. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
  12333. << "->" << Base->getType()
  12334. << Base->getSourceRange()),
  12335. *this, OCD_ViableCandidates, Base);
  12336. return ExprError();
  12337. case OR_Deleted:
  12338. CandidateSet.NoteCandidates(
  12339. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  12340. << "->" << Base->getSourceRange()),
  12341. *this, OCD_AllCandidates, Base);
  12342. return ExprError();
  12343. }
  12344. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  12345. // Convert the object parameter.
  12346. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  12347. ExprResult BaseResult =
  12348. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  12349. Best->FoundDecl, Method);
  12350. if (BaseResult.isInvalid())
  12351. return ExprError();
  12352. Base = BaseResult.get();
  12353. // Build the operator call.
  12354. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  12355. Base, HadMultipleCandidates, OpLoc);
  12356. if (FnExpr.isInvalid())
  12357. return ExprError();
  12358. QualType ResultTy = Method->getReturnType();
  12359. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12360. ResultTy = ResultTy.getNonLValueExprType(Context);
  12361. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  12362. Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
  12363. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  12364. return ExprError();
  12365. if (CheckFunctionCall(Method, TheCall,
  12366. Method->getType()->castAs<FunctionProtoType>()))
  12367. return ExprError();
  12368. return MaybeBindToTemporary(TheCall);
  12369. }
  12370. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  12371. /// a literal operator described by the provided lookup results.
  12372. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  12373. DeclarationNameInfo &SuffixInfo,
  12374. ArrayRef<Expr*> Args,
  12375. SourceLocation LitEndLoc,
  12376. TemplateArgumentListInfo *TemplateArgs) {
  12377. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  12378. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  12379. OverloadCandidateSet::CSK_Normal);
  12380. AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
  12381. TemplateArgs);
  12382. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12383. // Perform overload resolution. This will usually be trivial, but might need
  12384. // to perform substitutions for a literal operator template.
  12385. OverloadCandidateSet::iterator Best;
  12386. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  12387. case OR_Success:
  12388. case OR_Deleted:
  12389. break;
  12390. case OR_No_Viable_Function:
  12391. CandidateSet.NoteCandidates(
  12392. PartialDiagnosticAt(UDSuffixLoc,
  12393. PDiag(diag::err_ovl_no_viable_function_in_call)
  12394. << R.getLookupName()),
  12395. *this, OCD_AllCandidates, Args);
  12396. return ExprError();
  12397. case OR_Ambiguous:
  12398. CandidateSet.NoteCandidates(
  12399. PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
  12400. << R.getLookupName()),
  12401. *this, OCD_ViableCandidates, Args);
  12402. return ExprError();
  12403. }
  12404. FunctionDecl *FD = Best->Function;
  12405. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  12406. nullptr, HadMultipleCandidates,
  12407. SuffixInfo.getLoc(),
  12408. SuffixInfo.getInfo());
  12409. if (Fn.isInvalid())
  12410. return true;
  12411. // Check the argument types. This should almost always be a no-op, except
  12412. // that array-to-pointer decay is applied to string literals.
  12413. Expr *ConvArgs[2];
  12414. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  12415. ExprResult InputInit = PerformCopyInitialization(
  12416. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  12417. SourceLocation(), Args[ArgIdx]);
  12418. if (InputInit.isInvalid())
  12419. return true;
  12420. ConvArgs[ArgIdx] = InputInit.get();
  12421. }
  12422. QualType ResultTy = FD->getReturnType();
  12423. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12424. ResultTy = ResultTy.getNonLValueExprType(Context);
  12425. UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
  12426. Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
  12427. VK, LitEndLoc, UDSuffixLoc);
  12428. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  12429. return ExprError();
  12430. if (CheckFunctionCall(FD, UDL, nullptr))
  12431. return ExprError();
  12432. return MaybeBindToTemporary(UDL);
  12433. }
  12434. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  12435. /// given LookupResult is non-empty, it is assumed to describe a member which
  12436. /// will be invoked. Otherwise, the function will be found via argument
  12437. /// dependent lookup.
  12438. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  12439. /// otherwise CallExpr is set to ExprError() and some non-success value
  12440. /// is returned.
  12441. Sema::ForRangeStatus
  12442. Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
  12443. SourceLocation RangeLoc,
  12444. const DeclarationNameInfo &NameInfo,
  12445. LookupResult &MemberLookup,
  12446. OverloadCandidateSet *CandidateSet,
  12447. Expr *Range, ExprResult *CallExpr) {
  12448. Scope *S = nullptr;
  12449. CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
  12450. if (!MemberLookup.empty()) {
  12451. ExprResult MemberRef =
  12452. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  12453. /*IsPtr=*/false, CXXScopeSpec(),
  12454. /*TemplateKWLoc=*/SourceLocation(),
  12455. /*FirstQualifierInScope=*/nullptr,
  12456. MemberLookup,
  12457. /*TemplateArgs=*/nullptr, S);
  12458. if (MemberRef.isInvalid()) {
  12459. *CallExpr = ExprError();
  12460. return FRS_DiagnosticIssued;
  12461. }
  12462. *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  12463. if (CallExpr->isInvalid()) {
  12464. *CallExpr = ExprError();
  12465. return FRS_DiagnosticIssued;
  12466. }
  12467. } else {
  12468. UnresolvedSet<0> FoundNames;
  12469. UnresolvedLookupExpr *Fn =
  12470. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  12471. NestedNameSpecifierLoc(), NameInfo,
  12472. /*NeedsADL=*/true, /*Overloaded=*/false,
  12473. FoundNames.begin(), FoundNames.end());
  12474. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  12475. CandidateSet, CallExpr);
  12476. if (CandidateSet->empty() || CandidateSetError) {
  12477. *CallExpr = ExprError();
  12478. return FRS_NoViableFunction;
  12479. }
  12480. OverloadCandidateSet::iterator Best;
  12481. OverloadingResult OverloadResult =
  12482. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
  12483. if (OverloadResult == OR_No_Viable_Function) {
  12484. *CallExpr = ExprError();
  12485. return FRS_NoViableFunction;
  12486. }
  12487. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  12488. Loc, nullptr, CandidateSet, &Best,
  12489. OverloadResult,
  12490. /*AllowTypoCorrection=*/false);
  12491. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  12492. *CallExpr = ExprError();
  12493. return FRS_DiagnosticIssued;
  12494. }
  12495. }
  12496. return FRS_Success;
  12497. }
  12498. /// FixOverloadedFunctionReference - E is an expression that refers to
  12499. /// a C++ overloaded function (possibly with some parentheses and
  12500. /// perhaps a '&' around it). We have resolved the overloaded function
  12501. /// to the function declaration Fn, so patch up the expression E to
  12502. /// refer (possibly indirectly) to Fn. Returns the new expr.
  12503. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  12504. FunctionDecl *Fn) {
  12505. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  12506. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  12507. Found, Fn);
  12508. if (SubExpr == PE->getSubExpr())
  12509. return PE;
  12510. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  12511. }
  12512. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  12513. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  12514. Found, Fn);
  12515. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  12516. SubExpr->getType()) &&
  12517. "Implicit cast type cannot be determined from overload");
  12518. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  12519. if (SubExpr == ICE->getSubExpr())
  12520. return ICE;
  12521. return ImplicitCastExpr::Create(Context, ICE->getType(),
  12522. ICE->getCastKind(),
  12523. SubExpr, nullptr,
  12524. ICE->getValueKind());
  12525. }
  12526. if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  12527. if (!GSE->isResultDependent()) {
  12528. Expr *SubExpr =
  12529. FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
  12530. if (SubExpr == GSE->getResultExpr())
  12531. return GSE;
  12532. // Replace the resulting type information before rebuilding the generic
  12533. // selection expression.
  12534. ArrayRef<Expr *> A = GSE->getAssocExprs();
  12535. SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
  12536. unsigned ResultIdx = GSE->getResultIndex();
  12537. AssocExprs[ResultIdx] = SubExpr;
  12538. return GenericSelectionExpr::Create(
  12539. Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
  12540. GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
  12541. GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
  12542. ResultIdx);
  12543. }
  12544. // Rather than fall through to the unreachable, return the original generic
  12545. // selection expression.
  12546. return GSE;
  12547. }
  12548. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  12549. assert(UnOp->getOpcode() == UO_AddrOf &&
  12550. "Can only take the address of an overloaded function");
  12551. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  12552. if (Method->isStatic()) {
  12553. // Do nothing: static member functions aren't any different
  12554. // from non-member functions.
  12555. } else {
  12556. // Fix the subexpression, which really has to be an
  12557. // UnresolvedLookupExpr holding an overloaded member function
  12558. // or template.
  12559. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  12560. Found, Fn);
  12561. if (SubExpr == UnOp->getSubExpr())
  12562. return UnOp;
  12563. assert(isa<DeclRefExpr>(SubExpr)
  12564. && "fixed to something other than a decl ref");
  12565. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  12566. && "fixed to a member ref with no nested name qualifier");
  12567. // We have taken the address of a pointer to member
  12568. // function. Perform the computation here so that we get the
  12569. // appropriate pointer to member type.
  12570. QualType ClassType
  12571. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  12572. QualType MemPtrType
  12573. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  12574. // Under the MS ABI, lock down the inheritance model now.
  12575. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  12576. (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
  12577. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  12578. VK_RValue, OK_Ordinary,
  12579. UnOp->getOperatorLoc(), false);
  12580. }
  12581. }
  12582. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  12583. Found, Fn);
  12584. if (SubExpr == UnOp->getSubExpr())
  12585. return UnOp;
  12586. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  12587. Context.getPointerType(SubExpr->getType()),
  12588. VK_RValue, OK_Ordinary,
  12589. UnOp->getOperatorLoc(), false);
  12590. }
  12591. // C++ [except.spec]p17:
  12592. // An exception-specification is considered to be needed when:
  12593. // - in an expression the function is the unique lookup result or the
  12594. // selected member of a set of overloaded functions
  12595. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  12596. ResolveExceptionSpec(E->getExprLoc(), FPT);
  12597. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  12598. // FIXME: avoid copy.
  12599. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  12600. if (ULE->hasExplicitTemplateArgs()) {
  12601. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  12602. TemplateArgs = &TemplateArgsBuffer;
  12603. }
  12604. DeclRefExpr *DRE =
  12605. BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
  12606. ULE->getQualifierLoc(), Found.getDecl(),
  12607. ULE->getTemplateKeywordLoc(), TemplateArgs);
  12608. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  12609. return DRE;
  12610. }
  12611. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  12612. // FIXME: avoid copy.
  12613. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  12614. if (MemExpr->hasExplicitTemplateArgs()) {
  12615. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  12616. TemplateArgs = &TemplateArgsBuffer;
  12617. }
  12618. Expr *Base;
  12619. // If we're filling in a static method where we used to have an
  12620. // implicit member access, rewrite to a simple decl ref.
  12621. if (MemExpr->isImplicitAccess()) {
  12622. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  12623. DeclRefExpr *DRE = BuildDeclRefExpr(
  12624. Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
  12625. MemExpr->getQualifierLoc(), Found.getDecl(),
  12626. MemExpr->getTemplateKeywordLoc(), TemplateArgs);
  12627. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  12628. return DRE;
  12629. } else {
  12630. SourceLocation Loc = MemExpr->getMemberLoc();
  12631. if (MemExpr->getQualifier())
  12632. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  12633. Base =
  12634. BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
  12635. }
  12636. } else
  12637. Base = MemExpr->getBase();
  12638. ExprValueKind valueKind;
  12639. QualType type;
  12640. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  12641. valueKind = VK_LValue;
  12642. type = Fn->getType();
  12643. } else {
  12644. valueKind = VK_RValue;
  12645. type = Context.BoundMemberTy;
  12646. }
  12647. return BuildMemberExpr(
  12648. Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  12649. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  12650. /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
  12651. type, valueKind, OK_Ordinary, TemplateArgs);
  12652. }
  12653. llvm_unreachable("Invalid reference to overloaded function");
  12654. }
  12655. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  12656. DeclAccessPair Found,
  12657. FunctionDecl *Fn) {
  12658. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  12659. }