SemaOverload.cpp 570 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275
  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. assert(!OrigT1->isReferenceType() &&
  3925. "T1 must be the pointee type of the reference type");
  3926. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3927. QualType T1 = Context.getCanonicalType(OrigT1);
  3928. QualType T2 = Context.getCanonicalType(OrigT2);
  3929. Qualifiers T1Quals, T2Quals;
  3930. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3931. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3932. // C++ [dcl.init.ref]p4:
  3933. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3934. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3935. // T1 is a base class of T2.
  3936. DerivedToBase = false;
  3937. ObjCConversion = false;
  3938. ObjCLifetimeConversion = false;
  3939. QualType ConvertedT2;
  3940. if (UnqualT1 == UnqualT2) {
  3941. // Nothing to do.
  3942. } else if (isCompleteType(Loc, OrigT2) &&
  3943. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3944. IsDerivedFrom(Loc, UnqualT2, UnqualT1))
  3945. DerivedToBase = true;
  3946. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3947. UnqualT2->isObjCObjectOrInterfaceType() &&
  3948. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3949. ObjCConversion = true;
  3950. else if (UnqualT2->isFunctionType() &&
  3951. IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
  3952. // C++1z [dcl.init.ref]p4:
  3953. // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
  3954. // function" and T1 is "function"
  3955. //
  3956. // We extend this to also apply to 'noreturn', so allow any function
  3957. // conversion between function types.
  3958. return Ref_Compatible;
  3959. else
  3960. return Ref_Incompatible;
  3961. // At this point, we know that T1 and T2 are reference-related (at
  3962. // least).
  3963. // If the type is an array type, promote the element qualifiers to the type
  3964. // for comparison.
  3965. if (isa<ArrayType>(T1) && T1Quals)
  3966. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3967. if (isa<ArrayType>(T2) && T2Quals)
  3968. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3969. // C++ [dcl.init.ref]p4:
  3970. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3971. // reference-related to T2 and cv1 is the same cv-qualification
  3972. // as, or greater cv-qualification than, cv2. For purposes of
  3973. // overload resolution, cases for which cv1 is greater
  3974. // cv-qualification than cv2 are identified as
  3975. // reference-compatible with added qualification (see 13.3.3.2).
  3976. //
  3977. // Note that we also require equivalence of Objective-C GC and address-space
  3978. // qualifiers when performing these computations, so that e.g., an int in
  3979. // address space 1 is not reference-compatible with an int in address
  3980. // space 2.
  3981. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3982. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3983. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3984. ObjCLifetimeConversion = true;
  3985. T1Quals.removeObjCLifetime();
  3986. T2Quals.removeObjCLifetime();
  3987. }
  3988. // MS compiler ignores __unaligned qualifier for references; do the same.
  3989. T1Quals.removeUnaligned();
  3990. T2Quals.removeUnaligned();
  3991. if (T1Quals.compatiblyIncludes(T2Quals))
  3992. return Ref_Compatible;
  3993. else
  3994. return Ref_Related;
  3995. }
  3996. /// Look for a user-defined conversion to a value reference-compatible
  3997. /// with DeclType. Return true if something definite is found.
  3998. static bool
  3999. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  4000. QualType DeclType, SourceLocation DeclLoc,
  4001. Expr *Init, QualType T2, bool AllowRvalues,
  4002. bool AllowExplicit) {
  4003. assert(T2->isRecordType() && "Can only find conversions of record types.");
  4004. CXXRecordDecl *T2RecordDecl
  4005. = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
  4006. OverloadCandidateSet CandidateSet(
  4007. DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4008. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  4009. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4010. NamedDecl *D = *I;
  4011. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4012. if (isa<UsingShadowDecl>(D))
  4013. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4014. FunctionTemplateDecl *ConvTemplate
  4015. = dyn_cast<FunctionTemplateDecl>(D);
  4016. CXXConversionDecl *Conv;
  4017. if (ConvTemplate)
  4018. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4019. else
  4020. Conv = cast<CXXConversionDecl>(D);
  4021. // If this is an explicit conversion, and we're not allowed to consider
  4022. // explicit conversions, skip it.
  4023. if (!AllowExplicit && Conv->isExplicit())
  4024. continue;
  4025. if (AllowRvalues) {
  4026. bool DerivedToBase = false;
  4027. bool ObjCConversion = false;
  4028. bool ObjCLifetimeConversion = false;
  4029. // If we are initializing an rvalue reference, don't permit conversion
  4030. // functions that return lvalues.
  4031. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  4032. const ReferenceType *RefType
  4033. = Conv->getConversionType()->getAs<LValueReferenceType>();
  4034. if (RefType && !RefType->getPointeeType()->isFunctionType())
  4035. continue;
  4036. }
  4037. if (!ConvTemplate &&
  4038. S.CompareReferenceRelationship(
  4039. DeclLoc,
  4040. Conv->getConversionType().getNonReferenceType()
  4041. .getUnqualifiedType(),
  4042. DeclType.getNonReferenceType().getUnqualifiedType(),
  4043. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  4044. Sema::Ref_Incompatible)
  4045. continue;
  4046. } else {
  4047. // If the conversion function doesn't return a reference type,
  4048. // it can't be considered for this conversion. An rvalue reference
  4049. // is only acceptable if its referencee is a function type.
  4050. const ReferenceType *RefType =
  4051. Conv->getConversionType()->getAs<ReferenceType>();
  4052. if (!RefType ||
  4053. (!RefType->isLValueReferenceType() &&
  4054. !RefType->getPointeeType()->isFunctionType()))
  4055. continue;
  4056. }
  4057. if (ConvTemplate)
  4058. S.AddTemplateConversionCandidate(
  4059. ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4060. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4061. else
  4062. S.AddConversionCandidate(
  4063. Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
  4064. /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
  4065. }
  4066. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4067. OverloadCandidateSet::iterator Best;
  4068. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  4069. case OR_Success:
  4070. // C++ [over.ics.ref]p1:
  4071. //
  4072. // [...] If the parameter binds directly to the result of
  4073. // applying a conversion function to the argument
  4074. // expression, the implicit conversion sequence is a
  4075. // user-defined conversion sequence (13.3.3.1.2), with the
  4076. // second standard conversion sequence either an identity
  4077. // conversion or, if the conversion function returns an
  4078. // entity of a type that is a derived class of the parameter
  4079. // type, a derived-to-base Conversion.
  4080. if (!Best->FinalConversion.DirectBinding)
  4081. return false;
  4082. ICS.setUserDefined();
  4083. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  4084. ICS.UserDefined.After = Best->FinalConversion;
  4085. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  4086. ICS.UserDefined.ConversionFunction = Best->Function;
  4087. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  4088. ICS.UserDefined.EllipsisConversion = false;
  4089. assert(ICS.UserDefined.After.ReferenceBinding &&
  4090. ICS.UserDefined.After.DirectBinding &&
  4091. "Expected a direct reference binding!");
  4092. return true;
  4093. case OR_Ambiguous:
  4094. ICS.setAmbiguous();
  4095. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  4096. Cand != CandidateSet.end(); ++Cand)
  4097. if (Cand->Viable)
  4098. ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
  4099. return true;
  4100. case OR_No_Viable_Function:
  4101. case OR_Deleted:
  4102. // There was no suitable conversion, or we found a deleted
  4103. // conversion; continue with other checks.
  4104. return false;
  4105. }
  4106. llvm_unreachable("Invalid OverloadResult!");
  4107. }
  4108. /// Compute an implicit conversion sequence for reference
  4109. /// initialization.
  4110. static ImplicitConversionSequence
  4111. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  4112. SourceLocation DeclLoc,
  4113. bool SuppressUserConversions,
  4114. bool AllowExplicit) {
  4115. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  4116. // Most paths end in a failed conversion.
  4117. ImplicitConversionSequence ICS;
  4118. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4119. QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
  4120. QualType T2 = Init->getType();
  4121. // If the initializer is the address of an overloaded function, try
  4122. // to resolve the overloaded function. If all goes well, T2 is the
  4123. // type of the resulting function.
  4124. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4125. DeclAccessPair Found;
  4126. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  4127. false, Found))
  4128. T2 = Fn->getType();
  4129. }
  4130. // Compute some basic properties of the types and the initializer.
  4131. bool isRValRef = DeclType->isRValueReferenceType();
  4132. bool DerivedToBase = false;
  4133. bool ObjCConversion = false;
  4134. bool ObjCLifetimeConversion = false;
  4135. Expr::Classification InitCategory = Init->Classify(S.Context);
  4136. Sema::ReferenceCompareResult RefRelationship
  4137. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  4138. ObjCConversion, ObjCLifetimeConversion);
  4139. // C++0x [dcl.init.ref]p5:
  4140. // A reference to type "cv1 T1" is initialized by an expression
  4141. // of type "cv2 T2" as follows:
  4142. // -- If reference is an lvalue reference and the initializer expression
  4143. if (!isRValRef) {
  4144. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  4145. // reference-compatible with "cv2 T2," or
  4146. //
  4147. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  4148. if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
  4149. // C++ [over.ics.ref]p1:
  4150. // When a parameter of reference type binds directly (8.5.3)
  4151. // to an argument expression, the implicit conversion sequence
  4152. // is the identity conversion, unless the argument expression
  4153. // has a type that is a derived class of the parameter type,
  4154. // in which case the implicit conversion sequence is a
  4155. // derived-to-base Conversion (13.3.3.1).
  4156. ICS.setStandard();
  4157. ICS.Standard.First = ICK_Identity;
  4158. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  4159. : ObjCConversion? ICK_Compatible_Conversion
  4160. : ICK_Identity;
  4161. ICS.Standard.Third = ICK_Identity;
  4162. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  4163. ICS.Standard.setToType(0, T2);
  4164. ICS.Standard.setToType(1, T1);
  4165. ICS.Standard.setToType(2, T1);
  4166. ICS.Standard.ReferenceBinding = true;
  4167. ICS.Standard.DirectBinding = true;
  4168. ICS.Standard.IsLvalueReference = !isRValRef;
  4169. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4170. ICS.Standard.BindsToRvalue = false;
  4171. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4172. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  4173. ICS.Standard.CopyConstructor = nullptr;
  4174. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4175. // Nothing more to do: the inaccessibility/ambiguity check for
  4176. // derived-to-base conversions is suppressed when we're
  4177. // computing the implicit conversion sequence (C++
  4178. // [over.best.ics]p2).
  4179. return ICS;
  4180. }
  4181. // -- has a class type (i.e., T2 is a class type), where T1 is
  4182. // not reference-related to T2, and can be implicitly
  4183. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  4184. // is reference-compatible with "cv3 T3" 92) (this
  4185. // conversion is selected by enumerating the applicable
  4186. // conversion functions (13.3.1.6) and choosing the best
  4187. // one through overload resolution (13.3)),
  4188. if (!SuppressUserConversions && T2->isRecordType() &&
  4189. S.isCompleteType(DeclLoc, T2) &&
  4190. RefRelationship == Sema::Ref_Incompatible) {
  4191. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4192. Init, T2, /*AllowRvalues=*/false,
  4193. AllowExplicit))
  4194. return ICS;
  4195. }
  4196. }
  4197. // -- Otherwise, the reference shall be an lvalue reference to a
  4198. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4199. // shall be an rvalue reference.
  4200. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  4201. return ICS;
  4202. // -- If the initializer expression
  4203. //
  4204. // -- is an xvalue, class prvalue, array prvalue or function
  4205. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  4206. if (RefRelationship == Sema::Ref_Compatible &&
  4207. (InitCategory.isXValue() ||
  4208. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  4209. (InitCategory.isLValue() && T2->isFunctionType()))) {
  4210. ICS.setStandard();
  4211. ICS.Standard.First = ICK_Identity;
  4212. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  4213. : ObjCConversion? ICK_Compatible_Conversion
  4214. : ICK_Identity;
  4215. ICS.Standard.Third = ICK_Identity;
  4216. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  4217. ICS.Standard.setToType(0, T2);
  4218. ICS.Standard.setToType(1, T1);
  4219. ICS.Standard.setToType(2, T1);
  4220. ICS.Standard.ReferenceBinding = true;
  4221. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  4222. // binding unless we're binding to a class prvalue.
  4223. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  4224. // allow the use of rvalue references in C++98/03 for the benefit of
  4225. // standard library implementors; therefore, we need the xvalue check here.
  4226. ICS.Standard.DirectBinding =
  4227. S.getLangOpts().CPlusPlus11 ||
  4228. !(InitCategory.isPRValue() || T2->isRecordType());
  4229. ICS.Standard.IsLvalueReference = !isRValRef;
  4230. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  4231. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  4232. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4233. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  4234. ICS.Standard.CopyConstructor = nullptr;
  4235. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  4236. return ICS;
  4237. }
  4238. // -- has a class type (i.e., T2 is a class type), where T1 is not
  4239. // reference-related to T2, and can be implicitly converted to
  4240. // an xvalue, class prvalue, or function lvalue of type
  4241. // "cv3 T3", where "cv1 T1" is reference-compatible with
  4242. // "cv3 T3",
  4243. //
  4244. // then the reference is bound to the value of the initializer
  4245. // expression in the first case and to the result of the conversion
  4246. // in the second case (or, in either case, to an appropriate base
  4247. // class subobject).
  4248. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4249. T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
  4250. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  4251. Init, T2, /*AllowRvalues=*/true,
  4252. AllowExplicit)) {
  4253. // In the second case, if the reference is an rvalue reference
  4254. // and the second standard conversion sequence of the
  4255. // user-defined conversion sequence includes an lvalue-to-rvalue
  4256. // conversion, the program is ill-formed.
  4257. if (ICS.isUserDefined() && isRValRef &&
  4258. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  4259. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  4260. return ICS;
  4261. }
  4262. // A temporary of function type cannot be created; don't even try.
  4263. if (T1->isFunctionType())
  4264. return ICS;
  4265. // -- Otherwise, a temporary of type "cv1 T1" is created and
  4266. // initialized from the initializer expression using the
  4267. // rules for a non-reference copy initialization (8.5). The
  4268. // reference is then bound to the temporary. If T1 is
  4269. // reference-related to T2, cv1 must be the same
  4270. // cv-qualification as, or greater cv-qualification than,
  4271. // cv2; otherwise, the program is ill-formed.
  4272. if (RefRelationship == Sema::Ref_Related) {
  4273. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  4274. // we would be reference-compatible or reference-compatible with
  4275. // added qualification. But that wasn't the case, so the reference
  4276. // initialization fails.
  4277. //
  4278. // Note that we only want to check address spaces and cvr-qualifiers here.
  4279. // ObjC GC, lifetime and unaligned qualifiers aren't important.
  4280. Qualifiers T1Quals = T1.getQualifiers();
  4281. Qualifiers T2Quals = T2.getQualifiers();
  4282. T1Quals.removeObjCGCAttr();
  4283. T1Quals.removeObjCLifetime();
  4284. T2Quals.removeObjCGCAttr();
  4285. T2Quals.removeObjCLifetime();
  4286. // MS compiler ignores __unaligned qualifier for references; do the same.
  4287. T1Quals.removeUnaligned();
  4288. T2Quals.removeUnaligned();
  4289. if (!T1Quals.compatiblyIncludes(T2Quals))
  4290. return ICS;
  4291. }
  4292. // If at least one of the types is a class type, the types are not
  4293. // related, and we aren't allowed any user conversions, the
  4294. // reference binding fails. This case is important for breaking
  4295. // recursion, since TryImplicitConversion below will attempt to
  4296. // create a temporary through the use of a copy constructor.
  4297. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  4298. (T1->isRecordType() || T2->isRecordType()))
  4299. return ICS;
  4300. // If T1 is reference-related to T2 and the reference is an rvalue
  4301. // reference, the initializer expression shall not be an lvalue.
  4302. if (RefRelationship >= Sema::Ref_Related &&
  4303. isRValRef && Init->Classify(S.Context).isLValue())
  4304. return ICS;
  4305. // C++ [over.ics.ref]p2:
  4306. // When a parameter of reference type is not bound directly to
  4307. // an argument expression, the conversion sequence is the one
  4308. // required to convert the argument expression to the
  4309. // underlying type of the reference according to
  4310. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  4311. // to copy-initializing a temporary of the underlying type with
  4312. // the argument expression. Any difference in top-level
  4313. // cv-qualification is subsumed by the initialization itself
  4314. // and does not constitute a conversion.
  4315. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4316. /*AllowExplicit=*/false,
  4317. /*InOverloadResolution=*/false,
  4318. /*CStyle=*/false,
  4319. /*AllowObjCWritebackConversion=*/false,
  4320. /*AllowObjCConversionOnExplicit=*/false);
  4321. // Of course, that's still a reference binding.
  4322. if (ICS.isStandard()) {
  4323. ICS.Standard.ReferenceBinding = true;
  4324. ICS.Standard.IsLvalueReference = !isRValRef;
  4325. ICS.Standard.BindsToFunctionLvalue = false;
  4326. ICS.Standard.BindsToRvalue = true;
  4327. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4328. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4329. } else if (ICS.isUserDefined()) {
  4330. const ReferenceType *LValRefType =
  4331. ICS.UserDefined.ConversionFunction->getReturnType()
  4332. ->getAs<LValueReferenceType>();
  4333. // C++ [over.ics.ref]p3:
  4334. // Except for an implicit object parameter, for which see 13.3.1, a
  4335. // standard conversion sequence cannot be formed if it requires [...]
  4336. // binding an rvalue reference to an lvalue other than a function
  4337. // lvalue.
  4338. // Note that the function case is not possible here.
  4339. if (DeclType->isRValueReferenceType() && LValRefType) {
  4340. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4341. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4342. // reference to an rvalue!
  4343. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4344. return ICS;
  4345. }
  4346. ICS.UserDefined.After.ReferenceBinding = true;
  4347. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4348. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4349. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4350. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4351. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4352. }
  4353. return ICS;
  4354. }
  4355. static ImplicitConversionSequence
  4356. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4357. bool SuppressUserConversions,
  4358. bool InOverloadResolution,
  4359. bool AllowObjCWritebackConversion,
  4360. bool AllowExplicit = false);
  4361. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4362. /// initializer list From.
  4363. static ImplicitConversionSequence
  4364. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4365. bool SuppressUserConversions,
  4366. bool InOverloadResolution,
  4367. bool AllowObjCWritebackConversion) {
  4368. // C++11 [over.ics.list]p1:
  4369. // When an argument is an initializer list, it is not an expression and
  4370. // special rules apply for converting it to a parameter type.
  4371. ImplicitConversionSequence Result;
  4372. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4373. // We need a complete type for what follows. Incomplete types can never be
  4374. // initialized from init lists.
  4375. if (!S.isCompleteType(From->getBeginLoc(), ToType))
  4376. return Result;
  4377. // Per DR1467:
  4378. // If the parameter type is a class X and the initializer list has a single
  4379. // element of type cv U, where U is X or a class derived from X, the
  4380. // implicit conversion sequence is the one required to convert the element
  4381. // to the parameter type.
  4382. //
  4383. // Otherwise, if the parameter type is a character array [... ]
  4384. // and the initializer list has a single element that is an
  4385. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4386. // implicit conversion sequence is the identity conversion.
  4387. if (From->getNumInits() == 1) {
  4388. if (ToType->isRecordType()) {
  4389. QualType InitType = From->getInit(0)->getType();
  4390. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4391. S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
  4392. return TryCopyInitialization(S, From->getInit(0), ToType,
  4393. SuppressUserConversions,
  4394. InOverloadResolution,
  4395. AllowObjCWritebackConversion);
  4396. }
  4397. // FIXME: Check the other conditions here: array of character type,
  4398. // initializer is a string literal.
  4399. if (ToType->isArrayType()) {
  4400. InitializedEntity Entity =
  4401. InitializedEntity::InitializeParameter(S.Context, ToType,
  4402. /*Consumed=*/false);
  4403. if (S.CanPerformCopyInitialization(Entity, From)) {
  4404. Result.setStandard();
  4405. Result.Standard.setAsIdentityConversion();
  4406. Result.Standard.setFromType(ToType);
  4407. Result.Standard.setAllToTypes(ToType);
  4408. return Result;
  4409. }
  4410. }
  4411. }
  4412. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4413. // C++11 [over.ics.list]p2:
  4414. // If the parameter type is std::initializer_list<X> or "array of X" and
  4415. // all the elements can be implicitly converted to X, the implicit
  4416. // conversion sequence is the worst conversion necessary to convert an
  4417. // element of the list to X.
  4418. //
  4419. // C++14 [over.ics.list]p3:
  4420. // Otherwise, if the parameter type is "array of N X", if the initializer
  4421. // list has exactly N elements or if it has fewer than N elements and X is
  4422. // default-constructible, and if all the elements of the initializer list
  4423. // can be implicitly converted to X, the implicit conversion sequence is
  4424. // the worst conversion necessary to convert an element of the list to X.
  4425. //
  4426. // FIXME: We're missing a lot of these checks.
  4427. bool toStdInitializerList = false;
  4428. QualType X;
  4429. if (ToType->isArrayType())
  4430. X = S.Context.getAsArrayType(ToType)->getElementType();
  4431. else
  4432. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4433. if (!X.isNull()) {
  4434. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4435. Expr *Init = From->getInit(i);
  4436. ImplicitConversionSequence ICS =
  4437. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4438. InOverloadResolution,
  4439. AllowObjCWritebackConversion);
  4440. // If a single element isn't convertible, fail.
  4441. if (ICS.isBad()) {
  4442. Result = ICS;
  4443. break;
  4444. }
  4445. // Otherwise, look for the worst conversion.
  4446. if (Result.isBad() || CompareImplicitConversionSequences(
  4447. S, From->getBeginLoc(), ICS, Result) ==
  4448. ImplicitConversionSequence::Worse)
  4449. Result = ICS;
  4450. }
  4451. // For an empty list, we won't have computed any conversion sequence.
  4452. // Introduce the identity conversion sequence.
  4453. if (From->getNumInits() == 0) {
  4454. Result.setStandard();
  4455. Result.Standard.setAsIdentityConversion();
  4456. Result.Standard.setFromType(ToType);
  4457. Result.Standard.setAllToTypes(ToType);
  4458. }
  4459. Result.setStdInitializerListElement(toStdInitializerList);
  4460. return Result;
  4461. }
  4462. // C++14 [over.ics.list]p4:
  4463. // C++11 [over.ics.list]p3:
  4464. // Otherwise, if the parameter is a non-aggregate class X and overload
  4465. // resolution chooses a single best constructor [...] the implicit
  4466. // conversion sequence is a user-defined conversion sequence. If multiple
  4467. // constructors are viable but none is better than the others, the
  4468. // implicit conversion sequence is a user-defined conversion sequence.
  4469. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4470. // This function can deal with initializer lists.
  4471. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4472. /*AllowExplicit=*/false,
  4473. InOverloadResolution, /*CStyle=*/false,
  4474. AllowObjCWritebackConversion,
  4475. /*AllowObjCConversionOnExplicit=*/false);
  4476. }
  4477. // C++14 [over.ics.list]p5:
  4478. // C++11 [over.ics.list]p4:
  4479. // Otherwise, if the parameter has an aggregate type which can be
  4480. // initialized from the initializer list [...] the implicit conversion
  4481. // sequence is a user-defined conversion sequence.
  4482. if (ToType->isAggregateType()) {
  4483. // Type is an aggregate, argument is an init list. At this point it comes
  4484. // down to checking whether the initialization works.
  4485. // FIXME: Find out whether this parameter is consumed or not.
  4486. InitializedEntity Entity =
  4487. InitializedEntity::InitializeParameter(S.Context, ToType,
  4488. /*Consumed=*/false);
  4489. if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
  4490. From)) {
  4491. Result.setUserDefined();
  4492. Result.UserDefined.Before.setAsIdentityConversion();
  4493. // Initializer lists don't have a type.
  4494. Result.UserDefined.Before.setFromType(QualType());
  4495. Result.UserDefined.Before.setAllToTypes(QualType());
  4496. Result.UserDefined.After.setAsIdentityConversion();
  4497. Result.UserDefined.After.setFromType(ToType);
  4498. Result.UserDefined.After.setAllToTypes(ToType);
  4499. Result.UserDefined.ConversionFunction = nullptr;
  4500. }
  4501. return Result;
  4502. }
  4503. // C++14 [over.ics.list]p6:
  4504. // C++11 [over.ics.list]p5:
  4505. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4506. if (ToType->isReferenceType()) {
  4507. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4508. // mention initializer lists in any way. So we go by what list-
  4509. // initialization would do and try to extrapolate from that.
  4510. QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
  4511. // If the initializer list has a single element that is reference-related
  4512. // to the parameter type, we initialize the reference from that.
  4513. if (From->getNumInits() == 1) {
  4514. Expr *Init = From->getInit(0);
  4515. QualType T2 = Init->getType();
  4516. // If the initializer is the address of an overloaded function, try
  4517. // to resolve the overloaded function. If all goes well, T2 is the
  4518. // type of the resulting function.
  4519. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4520. DeclAccessPair Found;
  4521. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4522. Init, ToType, false, Found))
  4523. T2 = Fn->getType();
  4524. }
  4525. // Compute some basic properties of the types and the initializer.
  4526. bool dummy1 = false;
  4527. bool dummy2 = false;
  4528. bool dummy3 = false;
  4529. Sema::ReferenceCompareResult RefRelationship =
  4530. S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
  4531. dummy2, dummy3);
  4532. if (RefRelationship >= Sema::Ref_Related) {
  4533. return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
  4534. SuppressUserConversions,
  4535. /*AllowExplicit=*/false);
  4536. }
  4537. }
  4538. // Otherwise, we bind the reference to a temporary created from the
  4539. // initializer list.
  4540. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4541. InOverloadResolution,
  4542. AllowObjCWritebackConversion);
  4543. if (Result.isFailure())
  4544. return Result;
  4545. assert(!Result.isEllipsis() &&
  4546. "Sub-initialization cannot result in ellipsis conversion.");
  4547. // Can we even bind to a temporary?
  4548. if (ToType->isRValueReferenceType() ||
  4549. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4550. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4551. Result.UserDefined.After;
  4552. SCS.ReferenceBinding = true;
  4553. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4554. SCS.BindsToRvalue = true;
  4555. SCS.BindsToFunctionLvalue = false;
  4556. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4557. SCS.ObjCLifetimeConversionBinding = false;
  4558. } else
  4559. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4560. From, ToType);
  4561. return Result;
  4562. }
  4563. // C++14 [over.ics.list]p7:
  4564. // C++11 [over.ics.list]p6:
  4565. // Otherwise, if the parameter type is not a class:
  4566. if (!ToType->isRecordType()) {
  4567. // - if the initializer list has one element that is not itself an
  4568. // initializer list, the implicit conversion sequence is the one
  4569. // required to convert the element to the parameter type.
  4570. unsigned NumInits = From->getNumInits();
  4571. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4572. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4573. SuppressUserConversions,
  4574. InOverloadResolution,
  4575. AllowObjCWritebackConversion);
  4576. // - if the initializer list has no elements, the implicit conversion
  4577. // sequence is the identity conversion.
  4578. else if (NumInits == 0) {
  4579. Result.setStandard();
  4580. Result.Standard.setAsIdentityConversion();
  4581. Result.Standard.setFromType(ToType);
  4582. Result.Standard.setAllToTypes(ToType);
  4583. }
  4584. return Result;
  4585. }
  4586. // C++14 [over.ics.list]p8:
  4587. // C++11 [over.ics.list]p7:
  4588. // In all cases other than those enumerated above, no conversion is possible
  4589. return Result;
  4590. }
  4591. /// TryCopyInitialization - Try to copy-initialize a value of type
  4592. /// ToType from the expression From. Return the implicit conversion
  4593. /// sequence required to pass this argument, which may be a bad
  4594. /// conversion sequence (meaning that the argument cannot be passed to
  4595. /// a parameter of this type). If @p SuppressUserConversions, then we
  4596. /// do not permit any user-defined conversion sequences.
  4597. static ImplicitConversionSequence
  4598. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4599. bool SuppressUserConversions,
  4600. bool InOverloadResolution,
  4601. bool AllowObjCWritebackConversion,
  4602. bool AllowExplicit) {
  4603. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4604. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4605. InOverloadResolution,AllowObjCWritebackConversion);
  4606. if (ToType->isReferenceType())
  4607. return TryReferenceInit(S, From, ToType,
  4608. /*FIXME:*/ From->getBeginLoc(),
  4609. SuppressUserConversions, AllowExplicit);
  4610. return TryImplicitConversion(S, From, ToType,
  4611. SuppressUserConversions,
  4612. /*AllowExplicit=*/false,
  4613. InOverloadResolution,
  4614. /*CStyle=*/false,
  4615. AllowObjCWritebackConversion,
  4616. /*AllowObjCConversionOnExplicit=*/false);
  4617. }
  4618. static bool TryCopyInitialization(const CanQualType FromQTy,
  4619. const CanQualType ToQTy,
  4620. Sema &S,
  4621. SourceLocation Loc,
  4622. ExprValueKind FromVK) {
  4623. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4624. ImplicitConversionSequence ICS =
  4625. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4626. return !ICS.isBad();
  4627. }
  4628. /// TryObjectArgumentInitialization - Try to initialize the object
  4629. /// parameter of the given member function (@c Method) from the
  4630. /// expression @p From.
  4631. static ImplicitConversionSequence
  4632. TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
  4633. Expr::Classification FromClassification,
  4634. CXXMethodDecl *Method,
  4635. CXXRecordDecl *ActingContext) {
  4636. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4637. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4638. // const volatile object.
  4639. Qualifiers Quals = Method->getMethodQualifiers();
  4640. if (isa<CXXDestructorDecl>(Method)) {
  4641. Quals.addConst();
  4642. Quals.addVolatile();
  4643. }
  4644. QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
  4645. // Set up the conversion sequence as a "bad" conversion, to allow us
  4646. // to exit early.
  4647. ImplicitConversionSequence ICS;
  4648. // We need to have an object of class type.
  4649. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4650. FromType = PT->getPointeeType();
  4651. // When we had a pointer, it's implicitly dereferenced, so we
  4652. // better have an lvalue.
  4653. assert(FromClassification.isLValue());
  4654. }
  4655. assert(FromType->isRecordType());
  4656. // C++0x [over.match.funcs]p4:
  4657. // For non-static member functions, the type of the implicit object
  4658. // parameter is
  4659. //
  4660. // - "lvalue reference to cv X" for functions declared without a
  4661. // ref-qualifier or with the & ref-qualifier
  4662. // - "rvalue reference to cv X" for functions declared with the &&
  4663. // ref-qualifier
  4664. //
  4665. // where X is the class of which the function is a member and cv is the
  4666. // cv-qualification on the member function declaration.
  4667. //
  4668. // However, when finding an implicit conversion sequence for the argument, we
  4669. // are not allowed to perform user-defined conversions
  4670. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4671. // reference binding here, that allows class rvalues to bind to
  4672. // non-constant references.
  4673. // First check the qualifiers.
  4674. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4675. if (ImplicitParamType.getCVRQualifiers()
  4676. != FromTypeCanon.getLocalCVRQualifiers() &&
  4677. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4678. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4679. FromType, ImplicitParamType);
  4680. return ICS;
  4681. }
  4682. if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
  4683. Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
  4684. Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
  4685. if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
  4686. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4687. FromType, ImplicitParamType);
  4688. return ICS;
  4689. }
  4690. }
  4691. // Check that we have either the same type or a derived type. It
  4692. // affects the conversion rank.
  4693. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4694. ImplicitConversionKind SecondKind;
  4695. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4696. SecondKind = ICK_Identity;
  4697. } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
  4698. SecondKind = ICK_Derived_To_Base;
  4699. else {
  4700. ICS.setBad(BadConversionSequence::unrelated_class,
  4701. FromType, ImplicitParamType);
  4702. return ICS;
  4703. }
  4704. // Check the ref-qualifier.
  4705. switch (Method->getRefQualifier()) {
  4706. case RQ_None:
  4707. // Do nothing; we don't care about lvalueness or rvalueness.
  4708. break;
  4709. case RQ_LValue:
  4710. if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
  4711. // non-const lvalue reference cannot bind to an rvalue
  4712. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4713. ImplicitParamType);
  4714. return ICS;
  4715. }
  4716. break;
  4717. case RQ_RValue:
  4718. if (!FromClassification.isRValue()) {
  4719. // rvalue reference cannot bind to an lvalue
  4720. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4721. ImplicitParamType);
  4722. return ICS;
  4723. }
  4724. break;
  4725. }
  4726. // Success. Mark this as a reference binding.
  4727. ICS.setStandard();
  4728. ICS.Standard.setAsIdentityConversion();
  4729. ICS.Standard.Second = SecondKind;
  4730. ICS.Standard.setFromType(FromType);
  4731. ICS.Standard.setAllToTypes(ImplicitParamType);
  4732. ICS.Standard.ReferenceBinding = true;
  4733. ICS.Standard.DirectBinding = true;
  4734. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4735. ICS.Standard.BindsToFunctionLvalue = false;
  4736. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4737. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4738. = (Method->getRefQualifier() == RQ_None);
  4739. return ICS;
  4740. }
  4741. /// PerformObjectArgumentInitialization - Perform initialization of
  4742. /// the implicit object parameter for the given Method with the given
  4743. /// expression.
  4744. ExprResult
  4745. Sema::PerformObjectArgumentInitialization(Expr *From,
  4746. NestedNameSpecifier *Qualifier,
  4747. NamedDecl *FoundDecl,
  4748. CXXMethodDecl *Method) {
  4749. QualType FromRecordType, DestType;
  4750. QualType ImplicitParamRecordType =
  4751. Method->getThisType()->castAs<PointerType>()->getPointeeType();
  4752. Expr::Classification FromClassification;
  4753. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4754. FromRecordType = PT->getPointeeType();
  4755. DestType = Method->getThisType();
  4756. FromClassification = Expr::Classification::makeSimpleLValue();
  4757. } else {
  4758. FromRecordType = From->getType();
  4759. DestType = ImplicitParamRecordType;
  4760. FromClassification = From->Classify(Context);
  4761. // When performing member access on an rvalue, materialize a temporary.
  4762. if (From->isRValue()) {
  4763. From = CreateMaterializeTemporaryExpr(FromRecordType, From,
  4764. Method->getRefQualifier() !=
  4765. RefQualifierKind::RQ_RValue);
  4766. }
  4767. }
  4768. // Note that we always use the true parent context when performing
  4769. // the actual argument initialization.
  4770. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4771. *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
  4772. Method->getParent());
  4773. if (ICS.isBad()) {
  4774. switch (ICS.Bad.Kind) {
  4775. case BadConversionSequence::bad_qualifiers: {
  4776. Qualifiers FromQs = FromRecordType.getQualifiers();
  4777. Qualifiers ToQs = DestType.getQualifiers();
  4778. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4779. if (CVR) {
  4780. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
  4781. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4782. << From->getSourceRange();
  4783. Diag(Method->getLocation(), diag::note_previous_decl)
  4784. << Method->getDeclName();
  4785. return ExprError();
  4786. }
  4787. break;
  4788. }
  4789. case BadConversionSequence::lvalue_ref_to_rvalue:
  4790. case BadConversionSequence::rvalue_ref_to_lvalue: {
  4791. bool IsRValueQualified =
  4792. Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
  4793. Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
  4794. << Method->getDeclName() << FromClassification.isRValue()
  4795. << IsRValueQualified;
  4796. Diag(Method->getLocation(), diag::note_previous_decl)
  4797. << Method->getDeclName();
  4798. return ExprError();
  4799. }
  4800. case BadConversionSequence::no_conversion:
  4801. case BadConversionSequence::unrelated_class:
  4802. break;
  4803. }
  4804. return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
  4805. << ImplicitParamRecordType << FromRecordType
  4806. << From->getSourceRange();
  4807. }
  4808. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4809. ExprResult FromRes =
  4810. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4811. if (FromRes.isInvalid())
  4812. return ExprError();
  4813. From = FromRes.get();
  4814. }
  4815. if (!Context.hasSameType(From->getType(), DestType)) {
  4816. CastKind CK;
  4817. if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
  4818. CK = CK_AddressSpaceConversion;
  4819. else
  4820. CK = CK_NoOp;
  4821. From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
  4822. }
  4823. return From;
  4824. }
  4825. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4826. /// expression From to bool (C++0x [conv]p3).
  4827. static ImplicitConversionSequence
  4828. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4829. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4830. /*SuppressUserConversions=*/false,
  4831. /*AllowExplicit=*/true,
  4832. /*InOverloadResolution=*/false,
  4833. /*CStyle=*/false,
  4834. /*AllowObjCWritebackConversion=*/false,
  4835. /*AllowObjCConversionOnExplicit=*/false);
  4836. }
  4837. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4838. /// of the expression From to bool (C++0x [conv]p3).
  4839. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4840. if (checkPlaceholderForOverload(*this, From))
  4841. return ExprError();
  4842. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4843. if (!ICS.isBad())
  4844. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4845. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4846. return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
  4847. << From->getType() << From->getSourceRange();
  4848. return ExprError();
  4849. }
  4850. /// Check that the specified conversion is permitted in a converted constant
  4851. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4852. /// is acceptable.
  4853. static bool CheckConvertedConstantConversions(Sema &S,
  4854. StandardConversionSequence &SCS) {
  4855. // Since we know that the target type is an integral or unscoped enumeration
  4856. // type, most conversion kinds are impossible. All possible First and Third
  4857. // conversions are fine.
  4858. switch (SCS.Second) {
  4859. case ICK_Identity:
  4860. case ICK_Function_Conversion:
  4861. case ICK_Integral_Promotion:
  4862. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4863. case ICK_Zero_Queue_Conversion:
  4864. return true;
  4865. case ICK_Boolean_Conversion:
  4866. // Conversion from an integral or unscoped enumeration type to bool is
  4867. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4868. // conversion, so we allow it in a converted constant expression.
  4869. //
  4870. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4871. // a lot of popular code. We should at least add a warning for this
  4872. // (non-conforming) extension.
  4873. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4874. SCS.getToType(2)->isBooleanType();
  4875. case ICK_Pointer_Conversion:
  4876. case ICK_Pointer_Member:
  4877. // C++1z: null pointer conversions and null member pointer conversions are
  4878. // only permitted if the source type is std::nullptr_t.
  4879. return SCS.getFromType()->isNullPtrType();
  4880. case ICK_Floating_Promotion:
  4881. case ICK_Complex_Promotion:
  4882. case ICK_Floating_Conversion:
  4883. case ICK_Complex_Conversion:
  4884. case ICK_Floating_Integral:
  4885. case ICK_Compatible_Conversion:
  4886. case ICK_Derived_To_Base:
  4887. case ICK_Vector_Conversion:
  4888. case ICK_Vector_Splat:
  4889. case ICK_Complex_Real:
  4890. case ICK_Block_Pointer_Conversion:
  4891. case ICK_TransparentUnionConversion:
  4892. case ICK_Writeback_Conversion:
  4893. case ICK_Zero_Event_Conversion:
  4894. case ICK_C_Only_Conversion:
  4895. case ICK_Incompatible_Pointer_Conversion:
  4896. return false;
  4897. case ICK_Lvalue_To_Rvalue:
  4898. case ICK_Array_To_Pointer:
  4899. case ICK_Function_To_Pointer:
  4900. llvm_unreachable("found a first conversion kind in Second");
  4901. case ICK_Qualification:
  4902. llvm_unreachable("found a third conversion kind in Second");
  4903. case ICK_Num_Conversion_Kinds:
  4904. break;
  4905. }
  4906. llvm_unreachable("unknown conversion kind");
  4907. }
  4908. /// CheckConvertedConstantExpression - Check that the expression From is a
  4909. /// converted constant expression of type T, perform the conversion and produce
  4910. /// the converted expression, per C++11 [expr.const]p3.
  4911. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4912. QualType T, APValue &Value,
  4913. Sema::CCEKind CCE,
  4914. bool RequireInt) {
  4915. assert(S.getLangOpts().CPlusPlus11 &&
  4916. "converted constant expression outside C++11");
  4917. if (checkPlaceholderForOverload(S, From))
  4918. return ExprError();
  4919. // C++1z [expr.const]p3:
  4920. // A converted constant expression of type T is an expression,
  4921. // implicitly converted to type T, where the converted
  4922. // expression is a constant expression and the implicit conversion
  4923. // sequence contains only [... list of conversions ...].
  4924. // C++1z [stmt.if]p2:
  4925. // If the if statement is of the form if constexpr, the value of the
  4926. // condition shall be a contextually converted constant expression of type
  4927. // bool.
  4928. ImplicitConversionSequence ICS =
  4929. CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
  4930. ? TryContextuallyConvertToBool(S, From)
  4931. : TryCopyInitialization(S, From, T,
  4932. /*SuppressUserConversions=*/false,
  4933. /*InOverloadResolution=*/false,
  4934. /*AllowObjCWritebackConversion=*/false,
  4935. /*AllowExplicit=*/false);
  4936. StandardConversionSequence *SCS = nullptr;
  4937. switch (ICS.getKind()) {
  4938. case ImplicitConversionSequence::StandardConversion:
  4939. SCS = &ICS.Standard;
  4940. break;
  4941. case ImplicitConversionSequence::UserDefinedConversion:
  4942. // We are converting to a non-class type, so the Before sequence
  4943. // must be trivial.
  4944. SCS = &ICS.UserDefined.After;
  4945. break;
  4946. case ImplicitConversionSequence::AmbiguousConversion:
  4947. case ImplicitConversionSequence::BadConversion:
  4948. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4949. return S.Diag(From->getBeginLoc(),
  4950. diag::err_typecheck_converted_constant_expression)
  4951. << From->getType() << From->getSourceRange() << T;
  4952. return ExprError();
  4953. case ImplicitConversionSequence::EllipsisConversion:
  4954. llvm_unreachable("ellipsis conversion in converted constant expression");
  4955. }
  4956. // Check that we would only use permitted conversions.
  4957. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4958. return S.Diag(From->getBeginLoc(),
  4959. diag::err_typecheck_converted_constant_expression_disallowed)
  4960. << From->getType() << From->getSourceRange() << T;
  4961. }
  4962. // [...] and where the reference binding (if any) binds directly.
  4963. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4964. return S.Diag(From->getBeginLoc(),
  4965. diag::err_typecheck_converted_constant_expression_indirect)
  4966. << From->getType() << From->getSourceRange() << T;
  4967. }
  4968. ExprResult Result =
  4969. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4970. if (Result.isInvalid())
  4971. return Result;
  4972. // C++2a [intro.execution]p5:
  4973. // A full-expression is [...] a constant-expression [...]
  4974. Result =
  4975. S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
  4976. /*DiscardedValue=*/false, /*IsConstexpr=*/true);
  4977. if (Result.isInvalid())
  4978. return Result;
  4979. // Check for a narrowing implicit conversion.
  4980. APValue PreNarrowingValue;
  4981. QualType PreNarrowingType;
  4982. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4983. PreNarrowingType)) {
  4984. case NK_Dependent_Narrowing:
  4985. // Implicit conversion to a narrower type, but the expression is
  4986. // value-dependent so we can't tell whether it's actually narrowing.
  4987. case NK_Variable_Narrowing:
  4988. // Implicit conversion to a narrower type, and the value is not a constant
  4989. // expression. We'll diagnose this in a moment.
  4990. case NK_Not_Narrowing:
  4991. break;
  4992. case NK_Constant_Narrowing:
  4993. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  4994. << CCE << /*Constant*/ 1
  4995. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  4996. break;
  4997. case NK_Type_Narrowing:
  4998. S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
  4999. << CCE << /*Constant*/ 0 << From->getType() << T;
  5000. break;
  5001. }
  5002. if (Result.get()->isValueDependent()) {
  5003. Value = APValue();
  5004. return Result;
  5005. }
  5006. // Check the expression is a constant expression.
  5007. SmallVector<PartialDiagnosticAt, 8> Notes;
  5008. Expr::EvalResult Eval;
  5009. Eval.Diag = &Notes;
  5010. Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
  5011. ? Expr::EvaluateForMangling
  5012. : Expr::EvaluateForCodeGen;
  5013. if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
  5014. (RequireInt && !Eval.Val.isInt())) {
  5015. // The expression can't be folded, so we can't keep it at this position in
  5016. // the AST.
  5017. Result = ExprError();
  5018. } else {
  5019. Value = Eval.Val;
  5020. if (Notes.empty()) {
  5021. // It's a constant expression.
  5022. return ConstantExpr::Create(S.Context, Result.get(), Value);
  5023. }
  5024. }
  5025. // It's not a constant expression. Produce an appropriate diagnostic.
  5026. if (Notes.size() == 1 &&
  5027. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  5028. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  5029. else {
  5030. S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
  5031. << CCE << From->getSourceRange();
  5032. for (unsigned I = 0; I < Notes.size(); ++I)
  5033. S.Diag(Notes[I].first, Notes[I].second);
  5034. }
  5035. return ExprError();
  5036. }
  5037. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  5038. APValue &Value, CCEKind CCE) {
  5039. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  5040. }
  5041. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  5042. llvm::APSInt &Value,
  5043. CCEKind CCE) {
  5044. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  5045. APValue V;
  5046. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  5047. if (!R.isInvalid() && !R.get()->isValueDependent())
  5048. Value = V.getInt();
  5049. return R;
  5050. }
  5051. /// dropPointerConversions - If the given standard conversion sequence
  5052. /// involves any pointer conversions, remove them. This may change
  5053. /// the result type of the conversion sequence.
  5054. static void dropPointerConversion(StandardConversionSequence &SCS) {
  5055. if (SCS.Second == ICK_Pointer_Conversion) {
  5056. SCS.Second = ICK_Identity;
  5057. SCS.Third = ICK_Identity;
  5058. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  5059. }
  5060. }
  5061. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  5062. /// convert the expression From to an Objective-C pointer type.
  5063. static ImplicitConversionSequence
  5064. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  5065. // Do an implicit conversion to 'id'.
  5066. QualType Ty = S.Context.getObjCIdType();
  5067. ImplicitConversionSequence ICS
  5068. = TryImplicitConversion(S, From, Ty,
  5069. // FIXME: Are these flags correct?
  5070. /*SuppressUserConversions=*/false,
  5071. /*AllowExplicit=*/true,
  5072. /*InOverloadResolution=*/false,
  5073. /*CStyle=*/false,
  5074. /*AllowObjCWritebackConversion=*/false,
  5075. /*AllowObjCConversionOnExplicit=*/true);
  5076. // Strip off any final conversions to 'id'.
  5077. switch (ICS.getKind()) {
  5078. case ImplicitConversionSequence::BadConversion:
  5079. case ImplicitConversionSequence::AmbiguousConversion:
  5080. case ImplicitConversionSequence::EllipsisConversion:
  5081. break;
  5082. case ImplicitConversionSequence::UserDefinedConversion:
  5083. dropPointerConversion(ICS.UserDefined.After);
  5084. break;
  5085. case ImplicitConversionSequence::StandardConversion:
  5086. dropPointerConversion(ICS.Standard);
  5087. break;
  5088. }
  5089. return ICS;
  5090. }
  5091. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  5092. /// conversion of the expression From to an Objective-C pointer type.
  5093. /// Returns a valid but null ExprResult if no conversion sequence exists.
  5094. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  5095. if (checkPlaceholderForOverload(*this, From))
  5096. return ExprError();
  5097. QualType Ty = Context.getObjCIdType();
  5098. ImplicitConversionSequence ICS =
  5099. TryContextuallyConvertToObjCPointer(*this, From);
  5100. if (!ICS.isBad())
  5101. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  5102. return ExprResult();
  5103. }
  5104. /// Determine whether the provided type is an integral type, or an enumeration
  5105. /// type of a permitted flavor.
  5106. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  5107. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  5108. : T->isIntegralOrUnscopedEnumerationType();
  5109. }
  5110. static ExprResult
  5111. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  5112. Sema::ContextualImplicitConverter &Converter,
  5113. QualType T, UnresolvedSetImpl &ViableConversions) {
  5114. if (Converter.Suppress)
  5115. return ExprError();
  5116. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  5117. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5118. CXXConversionDecl *Conv =
  5119. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  5120. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  5121. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  5122. }
  5123. return From;
  5124. }
  5125. static bool
  5126. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5127. Sema::ContextualImplicitConverter &Converter,
  5128. QualType T, bool HadMultipleCandidates,
  5129. UnresolvedSetImpl &ExplicitConversions) {
  5130. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  5131. DeclAccessPair Found = ExplicitConversions[0];
  5132. CXXConversionDecl *Conversion =
  5133. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5134. // The user probably meant to invoke the given explicit
  5135. // conversion; use it.
  5136. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  5137. std::string TypeStr;
  5138. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  5139. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  5140. << FixItHint::CreateInsertion(From->getBeginLoc(),
  5141. "static_cast<" + TypeStr + ">(")
  5142. << FixItHint::CreateInsertion(
  5143. SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
  5144. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  5145. // If we aren't in a SFINAE context, build a call to the
  5146. // explicit conversion function.
  5147. if (SemaRef.isSFINAEContext())
  5148. return true;
  5149. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5150. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5151. HadMultipleCandidates);
  5152. if (Result.isInvalid())
  5153. return true;
  5154. // Record usage of conversion in an implicit cast.
  5155. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5156. CK_UserDefinedConversion, Result.get(),
  5157. nullptr, Result.get()->getValueKind());
  5158. }
  5159. return false;
  5160. }
  5161. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  5162. Sema::ContextualImplicitConverter &Converter,
  5163. QualType T, bool HadMultipleCandidates,
  5164. DeclAccessPair &Found) {
  5165. CXXConversionDecl *Conversion =
  5166. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  5167. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  5168. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  5169. if (!Converter.SuppressConversion) {
  5170. if (SemaRef.isSFINAEContext())
  5171. return true;
  5172. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  5173. << From->getSourceRange();
  5174. }
  5175. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  5176. HadMultipleCandidates);
  5177. if (Result.isInvalid())
  5178. return true;
  5179. // Record usage of conversion in an implicit cast.
  5180. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  5181. CK_UserDefinedConversion, Result.get(),
  5182. nullptr, Result.get()->getValueKind());
  5183. return false;
  5184. }
  5185. static ExprResult finishContextualImplicitConversion(
  5186. Sema &SemaRef, SourceLocation Loc, Expr *From,
  5187. Sema::ContextualImplicitConverter &Converter) {
  5188. if (!Converter.match(From->getType()) && !Converter.Suppress)
  5189. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  5190. << From->getSourceRange();
  5191. return SemaRef.DefaultLvalueConversion(From);
  5192. }
  5193. static void
  5194. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  5195. UnresolvedSetImpl &ViableConversions,
  5196. OverloadCandidateSet &CandidateSet) {
  5197. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  5198. DeclAccessPair FoundDecl = ViableConversions[I];
  5199. NamedDecl *D = FoundDecl.getDecl();
  5200. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  5201. if (isa<UsingShadowDecl>(D))
  5202. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  5203. CXXConversionDecl *Conv;
  5204. FunctionTemplateDecl *ConvTemplate;
  5205. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  5206. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5207. else
  5208. Conv = cast<CXXConversionDecl>(D);
  5209. if (ConvTemplate)
  5210. SemaRef.AddTemplateConversionCandidate(
  5211. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  5212. /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
  5213. else
  5214. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  5215. ToType, CandidateSet,
  5216. /*AllowObjCConversionOnExplicit=*/false,
  5217. /*AllowExplicit*/ true);
  5218. }
  5219. }
  5220. /// Attempt to convert the given expression to a type which is accepted
  5221. /// by the given converter.
  5222. ///
  5223. /// This routine will attempt to convert an expression of class type to a
  5224. /// type accepted by the specified converter. In C++11 and before, the class
  5225. /// must have a single non-explicit conversion function converting to a matching
  5226. /// type. In C++1y, there can be multiple such conversion functions, but only
  5227. /// one target type.
  5228. ///
  5229. /// \param Loc The source location of the construct that requires the
  5230. /// conversion.
  5231. ///
  5232. /// \param From The expression we're converting from.
  5233. ///
  5234. /// \param Converter Used to control and diagnose the conversion process.
  5235. ///
  5236. /// \returns The expression, converted to an integral or enumeration type if
  5237. /// successful.
  5238. ExprResult Sema::PerformContextualImplicitConversion(
  5239. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  5240. // We can't perform any more checking for type-dependent expressions.
  5241. if (From->isTypeDependent())
  5242. return From;
  5243. // Process placeholders immediately.
  5244. if (From->hasPlaceholderType()) {
  5245. ExprResult result = CheckPlaceholderExpr(From);
  5246. if (result.isInvalid())
  5247. return result;
  5248. From = result.get();
  5249. }
  5250. // If the expression already has a matching type, we're golden.
  5251. QualType T = From->getType();
  5252. if (Converter.match(T))
  5253. return DefaultLvalueConversion(From);
  5254. // FIXME: Check for missing '()' if T is a function type?
  5255. // We can only perform contextual implicit conversions on objects of class
  5256. // type.
  5257. const RecordType *RecordTy = T->getAs<RecordType>();
  5258. if (!RecordTy || !getLangOpts().CPlusPlus) {
  5259. if (!Converter.Suppress)
  5260. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  5261. return From;
  5262. }
  5263. // We must have a complete class type.
  5264. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  5265. ContextualImplicitConverter &Converter;
  5266. Expr *From;
  5267. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  5268. : Converter(Converter), From(From) {}
  5269. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  5270. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  5271. }
  5272. } IncompleteDiagnoser(Converter, From);
  5273. if (Converter.Suppress ? !isCompleteType(Loc, T)
  5274. : RequireCompleteType(Loc, T, IncompleteDiagnoser))
  5275. return From;
  5276. // Look for a conversion to an integral or enumeration type.
  5277. UnresolvedSet<4>
  5278. ViableConversions; // These are *potentially* viable in C++1y.
  5279. UnresolvedSet<4> ExplicitConversions;
  5280. const auto &Conversions =
  5281. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  5282. bool HadMultipleCandidates =
  5283. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  5284. // To check that there is only one target type, in C++1y:
  5285. QualType ToType;
  5286. bool HasUniqueTargetType = true;
  5287. // Collect explicit or viable (potentially in C++1y) conversions.
  5288. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  5289. NamedDecl *D = (*I)->getUnderlyingDecl();
  5290. CXXConversionDecl *Conversion;
  5291. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  5292. if (ConvTemplate) {
  5293. if (getLangOpts().CPlusPlus14)
  5294. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  5295. else
  5296. continue; // C++11 does not consider conversion operator templates(?).
  5297. } else
  5298. Conversion = cast<CXXConversionDecl>(D);
  5299. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  5300. "Conversion operator templates are considered potentially "
  5301. "viable in C++1y");
  5302. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  5303. if (Converter.match(CurToType) || ConvTemplate) {
  5304. if (Conversion->isExplicit()) {
  5305. // FIXME: For C++1y, do we need this restriction?
  5306. // cf. diagnoseNoViableConversion()
  5307. if (!ConvTemplate)
  5308. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  5309. } else {
  5310. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  5311. if (ToType.isNull())
  5312. ToType = CurToType.getUnqualifiedType();
  5313. else if (HasUniqueTargetType &&
  5314. (CurToType.getUnqualifiedType() != ToType))
  5315. HasUniqueTargetType = false;
  5316. }
  5317. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5318. }
  5319. }
  5320. }
  5321. if (getLangOpts().CPlusPlus14) {
  5322. // C++1y [conv]p6:
  5323. // ... An expression e of class type E appearing in such a context
  5324. // is said to be contextually implicitly converted to a specified
  5325. // type T and is well-formed if and only if e can be implicitly
  5326. // converted to a type T that is determined as follows: E is searched
  5327. // for conversion functions whose return type is cv T or reference to
  5328. // cv T such that T is allowed by the context. There shall be
  5329. // exactly one such T.
  5330. // If no unique T is found:
  5331. if (ToType.isNull()) {
  5332. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5333. HadMultipleCandidates,
  5334. ExplicitConversions))
  5335. return ExprError();
  5336. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5337. }
  5338. // If more than one unique Ts are found:
  5339. if (!HasUniqueTargetType)
  5340. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5341. ViableConversions);
  5342. // If one unique T is found:
  5343. // First, build a candidate set from the previously recorded
  5344. // potentially viable conversions.
  5345. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5346. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5347. CandidateSet);
  5348. // Then, perform overload resolution over the candidate set.
  5349. OverloadCandidateSet::iterator Best;
  5350. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5351. case OR_Success: {
  5352. // Apply this conversion.
  5353. DeclAccessPair Found =
  5354. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5355. if (recordConversion(*this, Loc, From, Converter, T,
  5356. HadMultipleCandidates, Found))
  5357. return ExprError();
  5358. break;
  5359. }
  5360. case OR_Ambiguous:
  5361. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5362. ViableConversions);
  5363. case OR_No_Viable_Function:
  5364. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5365. HadMultipleCandidates,
  5366. ExplicitConversions))
  5367. return ExprError();
  5368. LLVM_FALLTHROUGH;
  5369. case OR_Deleted:
  5370. // We'll complain below about a non-integral condition type.
  5371. break;
  5372. }
  5373. } else {
  5374. switch (ViableConversions.size()) {
  5375. case 0: {
  5376. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5377. HadMultipleCandidates,
  5378. ExplicitConversions))
  5379. return ExprError();
  5380. // We'll complain below about a non-integral condition type.
  5381. break;
  5382. }
  5383. case 1: {
  5384. // Apply this conversion.
  5385. DeclAccessPair Found = ViableConversions[0];
  5386. if (recordConversion(*this, Loc, From, Converter, T,
  5387. HadMultipleCandidates, Found))
  5388. return ExprError();
  5389. break;
  5390. }
  5391. default:
  5392. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5393. ViableConversions);
  5394. }
  5395. }
  5396. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5397. }
  5398. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5399. /// an acceptable non-member overloaded operator for a call whose
  5400. /// arguments have types T1 (and, if non-empty, T2). This routine
  5401. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5402. /// enumeration types.
  5403. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5404. FunctionDecl *Fn,
  5405. ArrayRef<Expr *> Args) {
  5406. QualType T1 = Args[0]->getType();
  5407. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5408. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5409. return true;
  5410. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5411. return true;
  5412. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5413. if (Proto->getNumParams() < 1)
  5414. return false;
  5415. if (T1->isEnumeralType()) {
  5416. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5417. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5418. return true;
  5419. }
  5420. if (Proto->getNumParams() < 2)
  5421. return false;
  5422. if (!T2.isNull() && T2->isEnumeralType()) {
  5423. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5424. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5425. return true;
  5426. }
  5427. return false;
  5428. }
  5429. /// AddOverloadCandidate - Adds the given function to the set of
  5430. /// candidate functions, using the given function call arguments. If
  5431. /// @p SuppressUserConversions, then don't allow user-defined
  5432. /// conversions via constructors or conversion operators.
  5433. ///
  5434. /// \param PartialOverloading true if we are performing "partial" overloading
  5435. /// based on an incomplete set of function arguments. This feature is used by
  5436. /// code completion.
  5437. void Sema::AddOverloadCandidate(
  5438. FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
  5439. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  5440. bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
  5441. ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
  5442. OverloadCandidateParamOrder PO) {
  5443. const FunctionProtoType *Proto
  5444. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5445. assert(Proto && "Functions without a prototype cannot be overloaded");
  5446. assert(!Function->getDescribedFunctionTemplate() &&
  5447. "Use AddTemplateOverloadCandidate for function templates");
  5448. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5449. if (!isa<CXXConstructorDecl>(Method)) {
  5450. // If we get here, it's because we're calling a member function
  5451. // that is named without a member access expression (e.g.,
  5452. // "this->f") that was either written explicitly or created
  5453. // implicitly. This can happen with a qualified call to a member
  5454. // function, e.g., X::f(). We use an empty type for the implied
  5455. // object argument (C++ [over.call.func]p3), and the acting context
  5456. // is irrelevant.
  5457. AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
  5458. Expr::Classification::makeSimpleLValue(), Args,
  5459. CandidateSet, SuppressUserConversions,
  5460. PartialOverloading, EarlyConversions, PO);
  5461. return;
  5462. }
  5463. // We treat a constructor like a non-member function, since its object
  5464. // argument doesn't participate in overload resolution.
  5465. }
  5466. if (!CandidateSet.isNewCandidate(Function, PO))
  5467. return;
  5468. // C++11 [class.copy]p11: [DR1402]
  5469. // A defaulted move constructor that is defined as deleted is ignored by
  5470. // overload resolution.
  5471. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5472. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5473. Constructor->isMoveConstructor())
  5474. return;
  5475. // Overload resolution is always an unevaluated context.
  5476. EnterExpressionEvaluationContext Unevaluated(
  5477. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5478. // C++ [over.match.oper]p3:
  5479. // if no operand has a class type, only those non-member functions in the
  5480. // lookup set that have a first parameter of type T1 or "reference to
  5481. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5482. // is a right operand) a second parameter of type T2 or "reference to
  5483. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5484. // candidate functions.
  5485. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5486. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5487. return;
  5488. // Add this candidate
  5489. OverloadCandidate &Candidate =
  5490. CandidateSet.addCandidate(Args.size(), EarlyConversions);
  5491. Candidate.FoundDecl = FoundDecl;
  5492. Candidate.Function = Function;
  5493. Candidate.Viable = true;
  5494. Candidate.RewriteKind =
  5495. CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
  5496. Candidate.IsSurrogate = false;
  5497. Candidate.IsADLCandidate = IsADLCandidate;
  5498. Candidate.IgnoreObjectArgument = false;
  5499. Candidate.ExplicitCallArguments = Args.size();
  5500. if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
  5501. !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
  5502. Candidate.Viable = false;
  5503. Candidate.FailureKind = ovl_non_default_multiversion_function;
  5504. return;
  5505. }
  5506. if (Constructor) {
  5507. // C++ [class.copy]p3:
  5508. // A member function template is never instantiated to perform the copy
  5509. // of a class object to an object of its class type.
  5510. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5511. if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
  5512. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5513. IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
  5514. ClassType))) {
  5515. Candidate.Viable = false;
  5516. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5517. return;
  5518. }
  5519. // C++ [over.match.funcs]p8: (proposed DR resolution)
  5520. // A constructor inherited from class type C that has a first parameter
  5521. // of type "reference to P" (including such a constructor instantiated
  5522. // from a template) is excluded from the set of candidate functions when
  5523. // constructing an object of type cv D if the argument list has exactly
  5524. // one argument and D is reference-related to P and P is reference-related
  5525. // to C.
  5526. auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
  5527. if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
  5528. Constructor->getParamDecl(0)->getType()->isReferenceType()) {
  5529. QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
  5530. QualType C = Context.getRecordType(Constructor->getParent());
  5531. QualType D = Context.getRecordType(Shadow->getParent());
  5532. SourceLocation Loc = Args.front()->getExprLoc();
  5533. if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
  5534. (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
  5535. Candidate.Viable = false;
  5536. Candidate.FailureKind = ovl_fail_inhctor_slice;
  5537. return;
  5538. }
  5539. }
  5540. // Check that the constructor is capable of constructing an object in the
  5541. // destination address space.
  5542. if (!Qualifiers::isAddressSpaceSupersetOf(
  5543. Constructor->getMethodQualifiers().getAddressSpace(),
  5544. CandidateSet.getDestAS())) {
  5545. Candidate.Viable = false;
  5546. Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
  5547. }
  5548. }
  5549. unsigned NumParams = Proto->getNumParams();
  5550. // (C++ 13.3.2p2): A candidate function having fewer than m
  5551. // parameters is viable only if it has an ellipsis in its parameter
  5552. // list (8.3.5).
  5553. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5554. !Proto->isVariadic()) {
  5555. Candidate.Viable = false;
  5556. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5557. return;
  5558. }
  5559. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5560. // is viable only if the (m+1)st parameter has a default argument
  5561. // (8.3.6). For the purposes of overload resolution, the
  5562. // parameter list is truncated on the right, so that there are
  5563. // exactly m parameters.
  5564. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5565. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5566. // Not enough arguments.
  5567. Candidate.Viable = false;
  5568. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5569. return;
  5570. }
  5571. // (CUDA B.1): Check for invalid calls between targets.
  5572. if (getLangOpts().CUDA)
  5573. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5574. // Skip the check for callers that are implicit members, because in this
  5575. // case we may not yet know what the member's target is; the target is
  5576. // inferred for the member automatically, based on the bases and fields of
  5577. // the class.
  5578. if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
  5579. Candidate.Viable = false;
  5580. Candidate.FailureKind = ovl_fail_bad_target;
  5581. return;
  5582. }
  5583. // Determine the implicit conversion sequences for each of the
  5584. // arguments.
  5585. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5586. unsigned ConvIdx =
  5587. PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
  5588. if (Candidate.Conversions[ConvIdx].isInitialized()) {
  5589. // We already formed a conversion sequence for this parameter during
  5590. // template argument deduction.
  5591. } else if (ArgIdx < NumParams) {
  5592. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5593. // exist for each argument an implicit conversion sequence
  5594. // (13.3.3.1) that converts that argument to the corresponding
  5595. // parameter of F.
  5596. QualType ParamType = Proto->getParamType(ArgIdx);
  5597. Candidate.Conversions[ConvIdx] = TryCopyInitialization(
  5598. *this, Args[ArgIdx], ParamType, SuppressUserConversions,
  5599. /*InOverloadResolution=*/true,
  5600. /*AllowObjCWritebackConversion=*/
  5601. getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
  5602. if (Candidate.Conversions[ConvIdx].isBad()) {
  5603. Candidate.Viable = false;
  5604. Candidate.FailureKind = ovl_fail_bad_conversion;
  5605. return;
  5606. }
  5607. } else {
  5608. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5609. // argument for which there is no corresponding parameter is
  5610. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5611. Candidate.Conversions[ConvIdx].setEllipsis();
  5612. }
  5613. }
  5614. if (!AllowExplicit) {
  5615. ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
  5616. if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
  5617. Candidate.Viable = false;
  5618. Candidate.FailureKind = ovl_fail_explicit_resolved;
  5619. return;
  5620. }
  5621. }
  5622. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5623. Candidate.Viable = false;
  5624. Candidate.FailureKind = ovl_fail_enable_if;
  5625. Candidate.DeductionFailure.Data = FailedAttr;
  5626. return;
  5627. }
  5628. if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
  5629. Candidate.Viable = false;
  5630. Candidate.FailureKind = ovl_fail_ext_disabled;
  5631. return;
  5632. }
  5633. }
  5634. ObjCMethodDecl *
  5635. Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
  5636. SmallVectorImpl<ObjCMethodDecl *> &Methods) {
  5637. if (Methods.size() <= 1)
  5638. return nullptr;
  5639. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5640. bool Match = true;
  5641. ObjCMethodDecl *Method = Methods[b];
  5642. unsigned NumNamedArgs = Sel.getNumArgs();
  5643. // Method might have more arguments than selector indicates. This is due
  5644. // to addition of c-style arguments in method.
  5645. if (Method->param_size() > NumNamedArgs)
  5646. NumNamedArgs = Method->param_size();
  5647. if (Args.size() < NumNamedArgs)
  5648. continue;
  5649. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5650. // We can't do any type-checking on a type-dependent argument.
  5651. if (Args[i]->isTypeDependent()) {
  5652. Match = false;
  5653. break;
  5654. }
  5655. ParmVarDecl *param = Method->parameters()[i];
  5656. Expr *argExpr = Args[i];
  5657. assert(argExpr && "SelectBestMethod(): missing expression");
  5658. // Strip the unbridged-cast placeholder expression off unless it's
  5659. // a consumed argument.
  5660. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5661. !param->hasAttr<CFConsumedAttr>())
  5662. argExpr = stripARCUnbridgedCast(argExpr);
  5663. // If the parameter is __unknown_anytype, move on to the next method.
  5664. if (param->getType() == Context.UnknownAnyTy) {
  5665. Match = false;
  5666. break;
  5667. }
  5668. ImplicitConversionSequence ConversionState
  5669. = TryCopyInitialization(*this, argExpr, param->getType(),
  5670. /*SuppressUserConversions*/false,
  5671. /*InOverloadResolution=*/true,
  5672. /*AllowObjCWritebackConversion=*/
  5673. getLangOpts().ObjCAutoRefCount,
  5674. /*AllowExplicit*/false);
  5675. // This function looks for a reasonably-exact match, so we consider
  5676. // incompatible pointer conversions to be a failure here.
  5677. if (ConversionState.isBad() ||
  5678. (ConversionState.isStandard() &&
  5679. ConversionState.Standard.Second ==
  5680. ICK_Incompatible_Pointer_Conversion)) {
  5681. Match = false;
  5682. break;
  5683. }
  5684. }
  5685. // Promote additional arguments to variadic methods.
  5686. if (Match && Method->isVariadic()) {
  5687. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5688. if (Args[i]->isTypeDependent()) {
  5689. Match = false;
  5690. break;
  5691. }
  5692. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5693. nullptr);
  5694. if (Arg.isInvalid()) {
  5695. Match = false;
  5696. break;
  5697. }
  5698. }
  5699. } else {
  5700. // Check for extra arguments to non-variadic methods.
  5701. if (Args.size() != NumNamedArgs)
  5702. Match = false;
  5703. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5704. // Special case when selectors have no argument. In this case, select
  5705. // one with the most general result type of 'id'.
  5706. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5707. QualType ReturnT = Methods[b]->getReturnType();
  5708. if (ReturnT->isObjCIdType())
  5709. return Methods[b];
  5710. }
  5711. }
  5712. }
  5713. if (Match)
  5714. return Method;
  5715. }
  5716. return nullptr;
  5717. }
  5718. static bool
  5719. convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
  5720. ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
  5721. bool MissingImplicitThis, Expr *&ConvertedThis,
  5722. SmallVectorImpl<Expr *> &ConvertedArgs) {
  5723. if (ThisArg) {
  5724. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5725. assert(!isa<CXXConstructorDecl>(Method) &&
  5726. "Shouldn't have `this` for ctors!");
  5727. assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
  5728. ExprResult R = S.PerformObjectArgumentInitialization(
  5729. ThisArg, /*Qualifier=*/nullptr, Method, Method);
  5730. if (R.isInvalid())
  5731. return false;
  5732. ConvertedThis = R.get();
  5733. } else {
  5734. if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
  5735. (void)MD;
  5736. assert((MissingImplicitThis || MD->isStatic() ||
  5737. isa<CXXConstructorDecl>(MD)) &&
  5738. "Expected `this` for non-ctor instance methods");
  5739. }
  5740. ConvertedThis = nullptr;
  5741. }
  5742. // Ignore any variadic arguments. Converting them is pointless, since the
  5743. // user can't refer to them in the function condition.
  5744. unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
  5745. // Convert the arguments.
  5746. for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
  5747. ExprResult R;
  5748. R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5749. S.Context, Function->getParamDecl(I)),
  5750. SourceLocation(), Args[I]);
  5751. if (R.isInvalid())
  5752. return false;
  5753. ConvertedArgs.push_back(R.get());
  5754. }
  5755. if (Trap.hasErrorOccurred())
  5756. return false;
  5757. // Push default arguments if needed.
  5758. if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
  5759. for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
  5760. ParmVarDecl *P = Function->getParamDecl(i);
  5761. Expr *DefArg = P->hasUninstantiatedDefaultArg()
  5762. ? P->getUninstantiatedDefaultArg()
  5763. : P->getDefaultArg();
  5764. // This can only happen in code completion, i.e. when PartialOverloading
  5765. // is true.
  5766. if (!DefArg)
  5767. return false;
  5768. ExprResult R =
  5769. S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5770. S.Context, Function->getParamDecl(i)),
  5771. SourceLocation(), DefArg);
  5772. if (R.isInvalid())
  5773. return false;
  5774. ConvertedArgs.push_back(R.get());
  5775. }
  5776. if (Trap.hasErrorOccurred())
  5777. return false;
  5778. }
  5779. return true;
  5780. }
  5781. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5782. bool MissingImplicitThis) {
  5783. auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
  5784. if (EnableIfAttrs.begin() == EnableIfAttrs.end())
  5785. return nullptr;
  5786. SFINAETrap Trap(*this);
  5787. SmallVector<Expr *, 16> ConvertedArgs;
  5788. // FIXME: We should look into making enable_if late-parsed.
  5789. Expr *DiscardedThis;
  5790. if (!convertArgsForAvailabilityChecks(
  5791. *this, Function, /*ThisArg=*/nullptr, Args, Trap,
  5792. /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
  5793. return *EnableIfAttrs.begin();
  5794. for (auto *EIA : EnableIfAttrs) {
  5795. APValue Result;
  5796. // FIXME: This doesn't consider value-dependent cases, because doing so is
  5797. // very difficult. Ideally, we should handle them more gracefully.
  5798. if (EIA->getCond()->isValueDependent() ||
  5799. !EIA->getCond()->EvaluateWithSubstitution(
  5800. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
  5801. return EIA;
  5802. if (!Result.isInt() || !Result.getInt().getBoolValue())
  5803. return EIA;
  5804. }
  5805. return nullptr;
  5806. }
  5807. template <typename CheckFn>
  5808. static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
  5809. bool ArgDependent, SourceLocation Loc,
  5810. CheckFn &&IsSuccessful) {
  5811. SmallVector<const DiagnoseIfAttr *, 8> Attrs;
  5812. for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
  5813. if (ArgDependent == DIA->getArgDependent())
  5814. Attrs.push_back(DIA);
  5815. }
  5816. // Common case: No diagnose_if attributes, so we can quit early.
  5817. if (Attrs.empty())
  5818. return false;
  5819. auto WarningBegin = std::stable_partition(
  5820. Attrs.begin(), Attrs.end(),
  5821. [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
  5822. // Note that diagnose_if attributes are late-parsed, so they appear in the
  5823. // correct order (unlike enable_if attributes).
  5824. auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
  5825. IsSuccessful);
  5826. if (ErrAttr != WarningBegin) {
  5827. const DiagnoseIfAttr *DIA = *ErrAttr;
  5828. S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
  5829. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  5830. << DIA->getParent() << DIA->getCond()->getSourceRange();
  5831. return true;
  5832. }
  5833. for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
  5834. if (IsSuccessful(DIA)) {
  5835. S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
  5836. S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
  5837. << DIA->getParent() << DIA->getCond()->getSourceRange();
  5838. }
  5839. return false;
  5840. }
  5841. bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
  5842. const Expr *ThisArg,
  5843. ArrayRef<const Expr *> Args,
  5844. SourceLocation Loc) {
  5845. return diagnoseDiagnoseIfAttrsWith(
  5846. *this, Function, /*ArgDependent=*/true, Loc,
  5847. [&](const DiagnoseIfAttr *DIA) {
  5848. APValue Result;
  5849. // It's sane to use the same Args for any redecl of this function, since
  5850. // EvaluateWithSubstitution only cares about the position of each
  5851. // argument in the arg list, not the ParmVarDecl* it maps to.
  5852. if (!DIA->getCond()->EvaluateWithSubstitution(
  5853. Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
  5854. return false;
  5855. return Result.isInt() && Result.getInt().getBoolValue();
  5856. });
  5857. }
  5858. bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
  5859. SourceLocation Loc) {
  5860. return diagnoseDiagnoseIfAttrsWith(
  5861. *this, ND, /*ArgDependent=*/false, Loc,
  5862. [&](const DiagnoseIfAttr *DIA) {
  5863. bool Result;
  5864. return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
  5865. Result;
  5866. });
  5867. }
  5868. /// Add all of the function declarations in the given function set to
  5869. /// the overload candidate set.
  5870. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5871. ArrayRef<Expr *> Args,
  5872. OverloadCandidateSet &CandidateSet,
  5873. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5874. bool SuppressUserConversions,
  5875. bool PartialOverloading,
  5876. bool FirstArgumentIsBase) {
  5877. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5878. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5879. ArrayRef<Expr *> FunctionArgs = Args;
  5880. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  5881. FunctionDecl *FD =
  5882. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  5883. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
  5884. QualType ObjectType;
  5885. Expr::Classification ObjectClassification;
  5886. if (Args.size() > 0) {
  5887. if (Expr *E = Args[0]) {
  5888. // Use the explicit base to restrict the lookup:
  5889. ObjectType = E->getType();
  5890. // Pointers in the object arguments are implicitly dereferenced, so we
  5891. // always classify them as l-values.
  5892. if (!ObjectType.isNull() && ObjectType->isPointerType())
  5893. ObjectClassification = Expr::Classification::makeSimpleLValue();
  5894. else
  5895. ObjectClassification = E->Classify(Context);
  5896. } // .. else there is an implicit base.
  5897. FunctionArgs = Args.slice(1);
  5898. }
  5899. if (FunTmpl) {
  5900. AddMethodTemplateCandidate(
  5901. FunTmpl, F.getPair(),
  5902. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5903. ExplicitTemplateArgs, ObjectType, ObjectClassification,
  5904. FunctionArgs, CandidateSet, SuppressUserConversions,
  5905. PartialOverloading);
  5906. } else {
  5907. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5908. cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
  5909. ObjectClassification, FunctionArgs, CandidateSet,
  5910. SuppressUserConversions, PartialOverloading);
  5911. }
  5912. } else {
  5913. // This branch handles both standalone functions and static methods.
  5914. // Slice the first argument (which is the base) when we access
  5915. // static method as non-static.
  5916. if (Args.size() > 0 &&
  5917. (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
  5918. !isa<CXXConstructorDecl>(FD)))) {
  5919. assert(cast<CXXMethodDecl>(FD)->isStatic());
  5920. FunctionArgs = Args.slice(1);
  5921. }
  5922. if (FunTmpl) {
  5923. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  5924. ExplicitTemplateArgs, FunctionArgs,
  5925. CandidateSet, SuppressUserConversions,
  5926. PartialOverloading);
  5927. } else {
  5928. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
  5929. SuppressUserConversions, PartialOverloading);
  5930. }
  5931. }
  5932. }
  5933. }
  5934. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5935. /// method) as a method candidate to the given overload set.
  5936. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
  5937. Expr::Classification ObjectClassification,
  5938. ArrayRef<Expr *> Args,
  5939. OverloadCandidateSet &CandidateSet,
  5940. bool SuppressUserConversions,
  5941. OverloadCandidateParamOrder PO) {
  5942. NamedDecl *Decl = FoundDecl.getDecl();
  5943. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5944. if (isa<UsingShadowDecl>(Decl))
  5945. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5946. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5947. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5948. "Expected a member function template");
  5949. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5950. /*ExplicitArgs*/ nullptr, ObjectType,
  5951. ObjectClassification, Args, CandidateSet,
  5952. SuppressUserConversions, false, PO);
  5953. } else {
  5954. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5955. ObjectType, ObjectClassification, Args, CandidateSet,
  5956. SuppressUserConversions, false, None, PO);
  5957. }
  5958. }
  5959. /// AddMethodCandidate - Adds the given C++ member function to the set
  5960. /// of candidate functions, using the given function call arguments
  5961. /// and the object argument (@c Object). For example, in a call
  5962. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5963. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5964. /// allow user-defined conversions via constructors or conversion
  5965. /// operators.
  5966. void
  5967. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5968. CXXRecordDecl *ActingContext, QualType ObjectType,
  5969. Expr::Classification ObjectClassification,
  5970. ArrayRef<Expr *> Args,
  5971. OverloadCandidateSet &CandidateSet,
  5972. bool SuppressUserConversions,
  5973. bool PartialOverloading,
  5974. ConversionSequenceList EarlyConversions,
  5975. OverloadCandidateParamOrder PO) {
  5976. const FunctionProtoType *Proto
  5977. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5978. assert(Proto && "Methods without a prototype cannot be overloaded");
  5979. assert(!isa<CXXConstructorDecl>(Method) &&
  5980. "Use AddOverloadCandidate for constructors");
  5981. if (!CandidateSet.isNewCandidate(Method, PO))
  5982. return;
  5983. // C++11 [class.copy]p23: [DR1402]
  5984. // A defaulted move assignment operator that is defined as deleted is
  5985. // ignored by overload resolution.
  5986. if (Method->isDefaulted() && Method->isDeleted() &&
  5987. Method->isMoveAssignmentOperator())
  5988. return;
  5989. // Overload resolution is always an unevaluated context.
  5990. EnterExpressionEvaluationContext Unevaluated(
  5991. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  5992. // Add this candidate
  5993. OverloadCandidate &Candidate =
  5994. CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
  5995. Candidate.FoundDecl = FoundDecl;
  5996. Candidate.Function = Method;
  5997. Candidate.RewriteKind =
  5998. CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
  5999. Candidate.IsSurrogate = false;
  6000. Candidate.IgnoreObjectArgument = false;
  6001. Candidate.ExplicitCallArguments = Args.size();
  6002. unsigned NumParams = Proto->getNumParams();
  6003. // (C++ 13.3.2p2): A candidate function having fewer than m
  6004. // parameters is viable only if it has an ellipsis in its parameter
  6005. // list (8.3.5).
  6006. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  6007. !Proto->isVariadic()) {
  6008. Candidate.Viable = false;
  6009. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6010. return;
  6011. }
  6012. // (C++ 13.3.2p2): A candidate function having more than m parameters
  6013. // is viable only if the (m+1)st parameter has a default argument
  6014. // (8.3.6). For the purposes of overload resolution, the
  6015. // parameter list is truncated on the right, so that there are
  6016. // exactly m parameters.
  6017. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  6018. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  6019. // Not enough arguments.
  6020. Candidate.Viable = false;
  6021. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6022. return;
  6023. }
  6024. Candidate.Viable = true;
  6025. if (Method->isStatic() || ObjectType.isNull())
  6026. // The implicit object argument is ignored.
  6027. Candidate.IgnoreObjectArgument = true;
  6028. else {
  6029. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
  6030. // Determine the implicit conversion sequence for the object
  6031. // parameter.
  6032. Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
  6033. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6034. Method, ActingContext);
  6035. if (Candidate.Conversions[ConvIdx].isBad()) {
  6036. Candidate.Viable = false;
  6037. Candidate.FailureKind = ovl_fail_bad_conversion;
  6038. return;
  6039. }
  6040. }
  6041. // (CUDA B.1): Check for invalid calls between targets.
  6042. if (getLangOpts().CUDA)
  6043. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  6044. if (!IsAllowedCUDACall(Caller, Method)) {
  6045. Candidate.Viable = false;
  6046. Candidate.FailureKind = ovl_fail_bad_target;
  6047. return;
  6048. }
  6049. // Determine the implicit conversion sequences for each of the
  6050. // arguments.
  6051. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  6052. unsigned ConvIdx =
  6053. PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
  6054. if (Candidate.Conversions[ConvIdx].isInitialized()) {
  6055. // We already formed a conversion sequence for this parameter during
  6056. // template argument deduction.
  6057. } else if (ArgIdx < NumParams) {
  6058. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6059. // exist for each argument an implicit conversion sequence
  6060. // (13.3.3.1) that converts that argument to the corresponding
  6061. // parameter of F.
  6062. QualType ParamType = Proto->getParamType(ArgIdx);
  6063. Candidate.Conversions[ConvIdx]
  6064. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6065. SuppressUserConversions,
  6066. /*InOverloadResolution=*/true,
  6067. /*AllowObjCWritebackConversion=*/
  6068. getLangOpts().ObjCAutoRefCount);
  6069. if (Candidate.Conversions[ConvIdx].isBad()) {
  6070. Candidate.Viable = false;
  6071. Candidate.FailureKind = ovl_fail_bad_conversion;
  6072. return;
  6073. }
  6074. } else {
  6075. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6076. // argument for which there is no corresponding parameter is
  6077. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  6078. Candidate.Conversions[ConvIdx].setEllipsis();
  6079. }
  6080. }
  6081. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  6082. Candidate.Viable = false;
  6083. Candidate.FailureKind = ovl_fail_enable_if;
  6084. Candidate.DeductionFailure.Data = FailedAttr;
  6085. return;
  6086. }
  6087. if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
  6088. !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
  6089. Candidate.Viable = false;
  6090. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6091. }
  6092. }
  6093. /// Add a C++ member function template as a candidate to the candidate
  6094. /// set, using template argument deduction to produce an appropriate member
  6095. /// function template specialization.
  6096. void Sema::AddMethodTemplateCandidate(
  6097. FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
  6098. CXXRecordDecl *ActingContext,
  6099. TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
  6100. Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
  6101. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6102. bool PartialOverloading, OverloadCandidateParamOrder PO) {
  6103. if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
  6104. return;
  6105. // C++ [over.match.funcs]p7:
  6106. // In each case where a candidate is a function template, candidate
  6107. // function template specializations are generated using template argument
  6108. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6109. // candidate functions in the usual way.113) A given name can refer to one
  6110. // or more function templates and also to a set of overloaded non-template
  6111. // functions. In such a case, the candidate functions generated from each
  6112. // function template are combined with the set of non-template candidate
  6113. // functions.
  6114. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6115. FunctionDecl *Specialization = nullptr;
  6116. ConversionSequenceList Conversions;
  6117. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6118. MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
  6119. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6120. return CheckNonDependentConversions(
  6121. MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
  6122. SuppressUserConversions, ActingContext, ObjectType,
  6123. ObjectClassification, PO);
  6124. })) {
  6125. OverloadCandidate &Candidate =
  6126. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6127. Candidate.FoundDecl = FoundDecl;
  6128. Candidate.Function = MethodTmpl->getTemplatedDecl();
  6129. Candidate.Viable = false;
  6130. Candidate.RewriteKind =
  6131. CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
  6132. Candidate.IsSurrogate = false;
  6133. Candidate.IgnoreObjectArgument =
  6134. cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
  6135. ObjectType.isNull();
  6136. Candidate.ExplicitCallArguments = Args.size();
  6137. if (Result == TDK_NonDependentConversionFailure)
  6138. Candidate.FailureKind = ovl_fail_bad_conversion;
  6139. else {
  6140. Candidate.FailureKind = ovl_fail_bad_deduction;
  6141. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6142. Info);
  6143. }
  6144. return;
  6145. }
  6146. // Add the function template specialization produced by template argument
  6147. // deduction as a candidate.
  6148. assert(Specialization && "Missing member function template specialization?");
  6149. assert(isa<CXXMethodDecl>(Specialization) &&
  6150. "Specialization is not a member function?");
  6151. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  6152. ActingContext, ObjectType, ObjectClassification, Args,
  6153. CandidateSet, SuppressUserConversions, PartialOverloading,
  6154. Conversions, PO);
  6155. }
  6156. /// Add a C++ function template specialization as a candidate
  6157. /// in the candidate set, using template argument deduction to produce
  6158. /// an appropriate function template specialization.
  6159. void Sema::AddTemplateOverloadCandidate(
  6160. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6161. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  6162. OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
  6163. bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
  6164. OverloadCandidateParamOrder PO) {
  6165. if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
  6166. return;
  6167. // C++ [over.match.funcs]p7:
  6168. // In each case where a candidate is a function template, candidate
  6169. // function template specializations are generated using template argument
  6170. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  6171. // candidate functions in the usual way.113) A given name can refer to one
  6172. // or more function templates and also to a set of overloaded non-template
  6173. // functions. In such a case, the candidate functions generated from each
  6174. // function template are combined with the set of non-template candidate
  6175. // functions.
  6176. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6177. FunctionDecl *Specialization = nullptr;
  6178. ConversionSequenceList Conversions;
  6179. if (TemplateDeductionResult Result = DeduceTemplateArguments(
  6180. FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
  6181. PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
  6182. return CheckNonDependentConversions(
  6183. FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
  6184. SuppressUserConversions, nullptr, QualType(), {}, PO);
  6185. })) {
  6186. OverloadCandidate &Candidate =
  6187. CandidateSet.addCandidate(Conversions.size(), Conversions);
  6188. Candidate.FoundDecl = FoundDecl;
  6189. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6190. Candidate.Viable = false;
  6191. Candidate.RewriteKind =
  6192. CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
  6193. Candidate.IsSurrogate = false;
  6194. Candidate.IsADLCandidate = IsADLCandidate;
  6195. // Ignore the object argument if there is one, since we don't have an object
  6196. // type.
  6197. Candidate.IgnoreObjectArgument =
  6198. isa<CXXMethodDecl>(Candidate.Function) &&
  6199. !isa<CXXConstructorDecl>(Candidate.Function);
  6200. Candidate.ExplicitCallArguments = Args.size();
  6201. if (Result == TDK_NonDependentConversionFailure)
  6202. Candidate.FailureKind = ovl_fail_bad_conversion;
  6203. else {
  6204. Candidate.FailureKind = ovl_fail_bad_deduction;
  6205. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6206. Info);
  6207. }
  6208. return;
  6209. }
  6210. // Add the function template specialization produced by template argument
  6211. // deduction as a candidate.
  6212. assert(Specialization && "Missing function template specialization?");
  6213. AddOverloadCandidate(
  6214. Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
  6215. PartialOverloading, AllowExplicit,
  6216. /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
  6217. }
  6218. /// Check that implicit conversion sequences can be formed for each argument
  6219. /// whose corresponding parameter has a non-dependent type, per DR1391's
  6220. /// [temp.deduct.call]p10.
  6221. bool Sema::CheckNonDependentConversions(
  6222. FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
  6223. ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
  6224. ConversionSequenceList &Conversions, bool SuppressUserConversions,
  6225. CXXRecordDecl *ActingContext, QualType ObjectType,
  6226. Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
  6227. // FIXME: The cases in which we allow explicit conversions for constructor
  6228. // arguments never consider calling a constructor template. It's not clear
  6229. // that is correct.
  6230. const bool AllowExplicit = false;
  6231. auto *FD = FunctionTemplate->getTemplatedDecl();
  6232. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  6233. bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
  6234. unsigned ThisConversions = HasThisConversion ? 1 : 0;
  6235. Conversions =
  6236. CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
  6237. // Overload resolution is always an unevaluated context.
  6238. EnterExpressionEvaluationContext Unevaluated(
  6239. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6240. // For a method call, check the 'this' conversion here too. DR1391 doesn't
  6241. // require that, but this check should never result in a hard error, and
  6242. // overload resolution is permitted to sidestep instantiations.
  6243. if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
  6244. !ObjectType.isNull()) {
  6245. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
  6246. Conversions[ConvIdx] = TryObjectArgumentInitialization(
  6247. *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
  6248. Method, ActingContext);
  6249. if (Conversions[ConvIdx].isBad())
  6250. return true;
  6251. }
  6252. for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
  6253. ++I) {
  6254. QualType ParamType = ParamTypes[I];
  6255. if (!ParamType->isDependentType()) {
  6256. unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
  6257. ? 0
  6258. : (ThisConversions + I);
  6259. Conversions[ConvIdx]
  6260. = TryCopyInitialization(*this, Args[I], ParamType,
  6261. SuppressUserConversions,
  6262. /*InOverloadResolution=*/true,
  6263. /*AllowObjCWritebackConversion=*/
  6264. getLangOpts().ObjCAutoRefCount,
  6265. AllowExplicit);
  6266. if (Conversions[ConvIdx].isBad())
  6267. return true;
  6268. }
  6269. }
  6270. return false;
  6271. }
  6272. /// Determine whether this is an allowable conversion from the result
  6273. /// of an explicit conversion operator to the expected type, per C++
  6274. /// [over.match.conv]p1 and [over.match.ref]p1.
  6275. ///
  6276. /// \param ConvType The return type of the conversion function.
  6277. ///
  6278. /// \param ToType The type we are converting to.
  6279. ///
  6280. /// \param AllowObjCPointerConversion Allow a conversion from one
  6281. /// Objective-C pointer to another.
  6282. ///
  6283. /// \returns true if the conversion is allowable, false otherwise.
  6284. static bool isAllowableExplicitConversion(Sema &S,
  6285. QualType ConvType, QualType ToType,
  6286. bool AllowObjCPointerConversion) {
  6287. QualType ToNonRefType = ToType.getNonReferenceType();
  6288. // Easy case: the types are the same.
  6289. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  6290. return true;
  6291. // Allow qualification conversions.
  6292. bool ObjCLifetimeConversion;
  6293. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  6294. ObjCLifetimeConversion))
  6295. return true;
  6296. // If we're not allowed to consider Objective-C pointer conversions,
  6297. // we're done.
  6298. if (!AllowObjCPointerConversion)
  6299. return false;
  6300. // Is this an Objective-C pointer conversion?
  6301. bool IncompatibleObjC = false;
  6302. QualType ConvertedType;
  6303. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  6304. IncompatibleObjC);
  6305. }
  6306. /// AddConversionCandidate - Add a C++ conversion function as a
  6307. /// candidate in the candidate set (C++ [over.match.conv],
  6308. /// C++ [over.match.copy]). From is the expression we're converting from,
  6309. /// and ToType is the type that we're eventually trying to convert to
  6310. /// (which may or may not be the same type as the type that the
  6311. /// conversion function produces).
  6312. void Sema::AddConversionCandidate(
  6313. CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
  6314. CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
  6315. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6316. bool AllowExplicit, bool AllowResultConversion) {
  6317. assert(!Conversion->getDescribedFunctionTemplate() &&
  6318. "Conversion function templates use AddTemplateConversionCandidate");
  6319. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  6320. if (!CandidateSet.isNewCandidate(Conversion))
  6321. return;
  6322. // If the conversion function has an undeduced return type, trigger its
  6323. // deduction now.
  6324. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  6325. if (DeduceReturnType(Conversion, From->getExprLoc()))
  6326. return;
  6327. ConvType = Conversion->getConversionType().getNonReferenceType();
  6328. }
  6329. // If we don't allow any conversion of the result type, ignore conversion
  6330. // functions that don't convert to exactly (possibly cv-qualified) T.
  6331. if (!AllowResultConversion &&
  6332. !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
  6333. return;
  6334. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  6335. // operator is only a candidate if its return type is the target type or
  6336. // can be converted to the target type with a qualification conversion.
  6337. if (Conversion->isExplicit() &&
  6338. !isAllowableExplicitConversion(*this, ConvType, ToType,
  6339. AllowObjCConversionOnExplicit))
  6340. return;
  6341. // Overload resolution is always an unevaluated context.
  6342. EnterExpressionEvaluationContext Unevaluated(
  6343. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6344. // Add this candidate
  6345. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  6346. Candidate.FoundDecl = FoundDecl;
  6347. Candidate.Function = Conversion;
  6348. Candidate.IsSurrogate = false;
  6349. Candidate.IgnoreObjectArgument = false;
  6350. Candidate.FinalConversion.setAsIdentityConversion();
  6351. Candidate.FinalConversion.setFromType(ConvType);
  6352. Candidate.FinalConversion.setAllToTypes(ToType);
  6353. Candidate.Viable = true;
  6354. Candidate.ExplicitCallArguments = 1;
  6355. // C++ [over.match.funcs]p4:
  6356. // For conversion functions, the function is considered to be a member of
  6357. // the class of the implicit implied object argument for the purpose of
  6358. // defining the type of the implicit object parameter.
  6359. //
  6360. // Determine the implicit conversion sequence for the implicit
  6361. // object parameter.
  6362. QualType ImplicitParamType = From->getType();
  6363. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  6364. ImplicitParamType = FromPtrType->getPointeeType();
  6365. CXXRecordDecl *ConversionContext
  6366. = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
  6367. Candidate.Conversions[0] = TryObjectArgumentInitialization(
  6368. *this, CandidateSet.getLocation(), From->getType(),
  6369. From->Classify(Context), Conversion, ConversionContext);
  6370. if (Candidate.Conversions[0].isBad()) {
  6371. Candidate.Viable = false;
  6372. Candidate.FailureKind = ovl_fail_bad_conversion;
  6373. return;
  6374. }
  6375. // We won't go through a user-defined type conversion function to convert a
  6376. // derived to base as such conversions are given Conversion Rank. They only
  6377. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  6378. QualType FromCanon
  6379. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  6380. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  6381. if (FromCanon == ToCanon ||
  6382. IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
  6383. Candidate.Viable = false;
  6384. Candidate.FailureKind = ovl_fail_trivial_conversion;
  6385. return;
  6386. }
  6387. // To determine what the conversion from the result of calling the
  6388. // conversion function to the type we're eventually trying to
  6389. // convert to (ToType), we need to synthesize a call to the
  6390. // conversion function and attempt copy initialization from it. This
  6391. // makes sure that we get the right semantics with respect to
  6392. // lvalues/rvalues and the type. Fortunately, we can allocate this
  6393. // call on the stack and we don't need its arguments to be
  6394. // well-formed.
  6395. DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
  6396. VK_LValue, From->getBeginLoc());
  6397. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  6398. Context.getPointerType(Conversion->getType()),
  6399. CK_FunctionToPointerDecay,
  6400. &ConversionRef, VK_RValue);
  6401. QualType ConversionType = Conversion->getConversionType();
  6402. if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
  6403. Candidate.Viable = false;
  6404. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6405. return;
  6406. }
  6407. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  6408. // Note that it is safe to allocate CallExpr on the stack here because
  6409. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  6410. // allocator).
  6411. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  6412. alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
  6413. CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
  6414. Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
  6415. ImplicitConversionSequence ICS =
  6416. TryCopyInitialization(*this, TheTemporaryCall, ToType,
  6417. /*SuppressUserConversions=*/true,
  6418. /*InOverloadResolution=*/false,
  6419. /*AllowObjCWritebackConversion=*/false);
  6420. switch (ICS.getKind()) {
  6421. case ImplicitConversionSequence::StandardConversion:
  6422. Candidate.FinalConversion = ICS.Standard;
  6423. // C++ [over.ics.user]p3:
  6424. // If the user-defined conversion is specified by a specialization of a
  6425. // conversion function template, the second standard conversion sequence
  6426. // shall have exact match rank.
  6427. if (Conversion->getPrimaryTemplate() &&
  6428. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  6429. Candidate.Viable = false;
  6430. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  6431. return;
  6432. }
  6433. // C++0x [dcl.init.ref]p5:
  6434. // In the second case, if the reference is an rvalue reference and
  6435. // the second standard conversion sequence of the user-defined
  6436. // conversion sequence includes an lvalue-to-rvalue conversion, the
  6437. // program is ill-formed.
  6438. if (ToType->isRValueReferenceType() &&
  6439. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  6440. Candidate.Viable = false;
  6441. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6442. return;
  6443. }
  6444. break;
  6445. case ImplicitConversionSequence::BadConversion:
  6446. Candidate.Viable = false;
  6447. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  6448. return;
  6449. default:
  6450. llvm_unreachable(
  6451. "Can only end up with a standard conversion sequence or failure");
  6452. }
  6453. if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
  6454. ExplicitSpecKind::ResolvedFalse) {
  6455. Candidate.Viable = false;
  6456. Candidate.FailureKind = ovl_fail_explicit_resolved;
  6457. return;
  6458. }
  6459. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6460. Candidate.Viable = false;
  6461. Candidate.FailureKind = ovl_fail_enable_if;
  6462. Candidate.DeductionFailure.Data = FailedAttr;
  6463. return;
  6464. }
  6465. if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
  6466. !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
  6467. Candidate.Viable = false;
  6468. Candidate.FailureKind = ovl_non_default_multiversion_function;
  6469. }
  6470. }
  6471. /// Adds a conversion function template specialization
  6472. /// candidate to the overload set, using template argument deduction
  6473. /// to deduce the template arguments of the conversion function
  6474. /// template from the type that we are converting to (C++
  6475. /// [temp.deduct.conv]).
  6476. void Sema::AddTemplateConversionCandidate(
  6477. FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
  6478. CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
  6479. OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
  6480. bool AllowExplicit, bool AllowResultConversion) {
  6481. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  6482. "Only conversion function templates permitted here");
  6483. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  6484. return;
  6485. TemplateDeductionInfo Info(CandidateSet.getLocation());
  6486. CXXConversionDecl *Specialization = nullptr;
  6487. if (TemplateDeductionResult Result
  6488. = DeduceTemplateArguments(FunctionTemplate, ToType,
  6489. Specialization, Info)) {
  6490. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  6491. Candidate.FoundDecl = FoundDecl;
  6492. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  6493. Candidate.Viable = false;
  6494. Candidate.FailureKind = ovl_fail_bad_deduction;
  6495. Candidate.IsSurrogate = false;
  6496. Candidate.IgnoreObjectArgument = false;
  6497. Candidate.ExplicitCallArguments = 1;
  6498. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  6499. Info);
  6500. return;
  6501. }
  6502. // Add the conversion function template specialization produced by
  6503. // template argument deduction as a candidate.
  6504. assert(Specialization && "Missing function template specialization?");
  6505. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  6506. CandidateSet, AllowObjCConversionOnExplicit,
  6507. AllowExplicit, AllowResultConversion);
  6508. }
  6509. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  6510. /// converts the given @c Object to a function pointer via the
  6511. /// conversion function @c Conversion, and then attempts to call it
  6512. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  6513. /// the type of function that we'll eventually be calling.
  6514. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  6515. DeclAccessPair FoundDecl,
  6516. CXXRecordDecl *ActingContext,
  6517. const FunctionProtoType *Proto,
  6518. Expr *Object,
  6519. ArrayRef<Expr *> Args,
  6520. OverloadCandidateSet& CandidateSet) {
  6521. if (!CandidateSet.isNewCandidate(Conversion))
  6522. return;
  6523. // Overload resolution is always an unevaluated context.
  6524. EnterExpressionEvaluationContext Unevaluated(
  6525. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6526. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  6527. Candidate.FoundDecl = FoundDecl;
  6528. Candidate.Function = nullptr;
  6529. Candidate.Surrogate = Conversion;
  6530. Candidate.Viable = true;
  6531. Candidate.IsSurrogate = true;
  6532. Candidate.IgnoreObjectArgument = false;
  6533. Candidate.ExplicitCallArguments = Args.size();
  6534. // Determine the implicit conversion sequence for the implicit
  6535. // object parameter.
  6536. ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
  6537. *this, CandidateSet.getLocation(), Object->getType(),
  6538. Object->Classify(Context), Conversion, ActingContext);
  6539. if (ObjectInit.isBad()) {
  6540. Candidate.Viable = false;
  6541. Candidate.FailureKind = ovl_fail_bad_conversion;
  6542. Candidate.Conversions[0] = ObjectInit;
  6543. return;
  6544. }
  6545. // The first conversion is actually a user-defined conversion whose
  6546. // first conversion is ObjectInit's standard conversion (which is
  6547. // effectively a reference binding). Record it as such.
  6548. Candidate.Conversions[0].setUserDefined();
  6549. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  6550. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  6551. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  6552. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  6553. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  6554. Candidate.Conversions[0].UserDefined.After
  6555. = Candidate.Conversions[0].UserDefined.Before;
  6556. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  6557. // Find the
  6558. unsigned NumParams = Proto->getNumParams();
  6559. // (C++ 13.3.2p2): A candidate function having fewer than m
  6560. // parameters is viable only if it has an ellipsis in its parameter
  6561. // list (8.3.5).
  6562. if (Args.size() > NumParams && !Proto->isVariadic()) {
  6563. Candidate.Viable = false;
  6564. Candidate.FailureKind = ovl_fail_too_many_arguments;
  6565. return;
  6566. }
  6567. // Function types don't have any default arguments, so just check if
  6568. // we have enough arguments.
  6569. if (Args.size() < NumParams) {
  6570. // Not enough arguments.
  6571. Candidate.Viable = false;
  6572. Candidate.FailureKind = ovl_fail_too_few_arguments;
  6573. return;
  6574. }
  6575. // Determine the implicit conversion sequences for each of the
  6576. // arguments.
  6577. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6578. if (ArgIdx < NumParams) {
  6579. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6580. // exist for each argument an implicit conversion sequence
  6581. // (13.3.3.1) that converts that argument to the corresponding
  6582. // parameter of F.
  6583. QualType ParamType = Proto->getParamType(ArgIdx);
  6584. Candidate.Conversions[ArgIdx + 1]
  6585. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6586. /*SuppressUserConversions=*/false,
  6587. /*InOverloadResolution=*/false,
  6588. /*AllowObjCWritebackConversion=*/
  6589. getLangOpts().ObjCAutoRefCount);
  6590. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6591. Candidate.Viable = false;
  6592. Candidate.FailureKind = ovl_fail_bad_conversion;
  6593. return;
  6594. }
  6595. } else {
  6596. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6597. // argument for which there is no corresponding parameter is
  6598. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6599. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6600. }
  6601. }
  6602. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6603. Candidate.Viable = false;
  6604. Candidate.FailureKind = ovl_fail_enable_if;
  6605. Candidate.DeductionFailure.Data = FailedAttr;
  6606. return;
  6607. }
  6608. }
  6609. /// Add all of the non-member operator function declarations in the given
  6610. /// function set to the overload candidate set.
  6611. void Sema::AddNonMemberOperatorCandidates(
  6612. const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
  6613. OverloadCandidateSet &CandidateSet,
  6614. TemplateArgumentListInfo *ExplicitTemplateArgs) {
  6615. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  6616. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  6617. ArrayRef<Expr *> FunctionArgs = Args;
  6618. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  6619. FunctionDecl *FD =
  6620. FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
  6621. // Don't consider rewritten functions if we're not rewriting.
  6622. if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
  6623. continue;
  6624. assert(!isa<CXXMethodDecl>(FD) &&
  6625. "unqualified operator lookup found a member function");
  6626. if (FunTmpl) {
  6627. AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
  6628. FunctionArgs, CandidateSet);
  6629. if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
  6630. AddTemplateOverloadCandidate(
  6631. FunTmpl, F.getPair(), ExplicitTemplateArgs,
  6632. {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
  6633. true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
  6634. } else {
  6635. if (ExplicitTemplateArgs)
  6636. continue;
  6637. AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
  6638. if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
  6639. AddOverloadCandidate(FD, F.getPair(),
  6640. {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
  6641. false, false, true, false, ADLCallKind::NotADL,
  6642. None, OverloadCandidateParamOrder::Reversed);
  6643. }
  6644. }
  6645. }
  6646. /// Add overload candidates for overloaded operators that are
  6647. /// member functions.
  6648. ///
  6649. /// Add the overloaded operator candidates that are member functions
  6650. /// for the operator Op that was used in an operator expression such
  6651. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6652. /// CandidateSet will store the added overload candidates. (C++
  6653. /// [over.match.oper]).
  6654. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6655. SourceLocation OpLoc,
  6656. ArrayRef<Expr *> Args,
  6657. OverloadCandidateSet &CandidateSet,
  6658. OverloadCandidateParamOrder PO) {
  6659. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6660. // C++ [over.match.oper]p3:
  6661. // For a unary operator @ with an operand of a type whose
  6662. // cv-unqualified version is T1, and for a binary operator @ with
  6663. // a left operand of a type whose cv-unqualified version is T1 and
  6664. // a right operand of a type whose cv-unqualified version is T2,
  6665. // three sets of candidate functions, designated member
  6666. // candidates, non-member candidates and built-in candidates, are
  6667. // constructed as follows:
  6668. QualType T1 = Args[0]->getType();
  6669. // -- If T1 is a complete class type or a class currently being
  6670. // defined, the set of member candidates is the result of the
  6671. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6672. // the set of member candidates is empty.
  6673. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6674. // Complete the type if it can be completed.
  6675. if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
  6676. return;
  6677. // If the type is neither complete nor being defined, bail out now.
  6678. if (!T1Rec->getDecl()->getDefinition())
  6679. return;
  6680. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6681. LookupQualifiedName(Operators, T1Rec->getDecl());
  6682. Operators.suppressDiagnostics();
  6683. for (LookupResult::iterator Oper = Operators.begin(),
  6684. OperEnd = Operators.end();
  6685. Oper != OperEnd;
  6686. ++Oper)
  6687. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6688. Args[0]->Classify(Context), Args.slice(1),
  6689. CandidateSet, /*SuppressUserConversion=*/false, PO);
  6690. }
  6691. }
  6692. /// AddBuiltinCandidate - Add a candidate for a built-in
  6693. /// operator. ResultTy and ParamTys are the result and parameter types
  6694. /// of the built-in candidate, respectively. Args and NumArgs are the
  6695. /// arguments being passed to the candidate. IsAssignmentOperator
  6696. /// should be true when this built-in candidate is an assignment
  6697. /// operator. NumContextualBoolArguments is the number of arguments
  6698. /// (at the beginning of the argument list) that will be contextually
  6699. /// converted to bool.
  6700. void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
  6701. OverloadCandidateSet& CandidateSet,
  6702. bool IsAssignmentOperator,
  6703. unsigned NumContextualBoolArguments) {
  6704. // Overload resolution is always an unevaluated context.
  6705. EnterExpressionEvaluationContext Unevaluated(
  6706. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6707. // Add this candidate
  6708. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6709. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6710. Candidate.Function = nullptr;
  6711. Candidate.IsSurrogate = false;
  6712. Candidate.IgnoreObjectArgument = false;
  6713. std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
  6714. // Determine the implicit conversion sequences for each of the
  6715. // arguments.
  6716. Candidate.Viable = true;
  6717. Candidate.ExplicitCallArguments = Args.size();
  6718. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6719. // C++ [over.match.oper]p4:
  6720. // For the built-in assignment operators, conversions of the
  6721. // left operand are restricted as follows:
  6722. // -- no temporaries are introduced to hold the left operand, and
  6723. // -- no user-defined conversions are applied to the left
  6724. // operand to achieve a type match with the left-most
  6725. // parameter of a built-in candidate.
  6726. //
  6727. // We block these conversions by turning off user-defined
  6728. // conversions, since that is the only way that initialization of
  6729. // a reference to a non-class type can occur from something that
  6730. // is not of the same type.
  6731. if (ArgIdx < NumContextualBoolArguments) {
  6732. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6733. "Contextual conversion to bool requires bool type");
  6734. Candidate.Conversions[ArgIdx]
  6735. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6736. } else {
  6737. Candidate.Conversions[ArgIdx]
  6738. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6739. ArgIdx == 0 && IsAssignmentOperator,
  6740. /*InOverloadResolution=*/false,
  6741. /*AllowObjCWritebackConversion=*/
  6742. getLangOpts().ObjCAutoRefCount);
  6743. }
  6744. if (Candidate.Conversions[ArgIdx].isBad()) {
  6745. Candidate.Viable = false;
  6746. Candidate.FailureKind = ovl_fail_bad_conversion;
  6747. break;
  6748. }
  6749. }
  6750. }
  6751. namespace {
  6752. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6753. /// candidate operator functions for built-in operators (C++
  6754. /// [over.built]). The types are separated into pointer types and
  6755. /// enumeration types.
  6756. class BuiltinCandidateTypeSet {
  6757. /// TypeSet - A set of types.
  6758. typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
  6759. llvm::SmallPtrSet<QualType, 8>> TypeSet;
  6760. /// PointerTypes - The set of pointer types that will be used in the
  6761. /// built-in candidates.
  6762. TypeSet PointerTypes;
  6763. /// MemberPointerTypes - The set of member pointer types that will be
  6764. /// used in the built-in candidates.
  6765. TypeSet MemberPointerTypes;
  6766. /// EnumerationTypes - The set of enumeration types that will be
  6767. /// used in the built-in candidates.
  6768. TypeSet EnumerationTypes;
  6769. /// The set of vector types that will be used in the built-in
  6770. /// candidates.
  6771. TypeSet VectorTypes;
  6772. /// A flag indicating non-record types are viable candidates
  6773. bool HasNonRecordTypes;
  6774. /// A flag indicating whether either arithmetic or enumeration types
  6775. /// were present in the candidate set.
  6776. bool HasArithmeticOrEnumeralTypes;
  6777. /// A flag indicating whether the nullptr type was present in the
  6778. /// candidate set.
  6779. bool HasNullPtrType;
  6780. /// Sema - The semantic analysis instance where we are building the
  6781. /// candidate type set.
  6782. Sema &SemaRef;
  6783. /// Context - The AST context in which we will build the type sets.
  6784. ASTContext &Context;
  6785. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6786. const Qualifiers &VisibleQuals);
  6787. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6788. public:
  6789. /// iterator - Iterates through the types that are part of the set.
  6790. typedef TypeSet::iterator iterator;
  6791. BuiltinCandidateTypeSet(Sema &SemaRef)
  6792. : HasNonRecordTypes(false),
  6793. HasArithmeticOrEnumeralTypes(false),
  6794. HasNullPtrType(false),
  6795. SemaRef(SemaRef),
  6796. Context(SemaRef.Context) { }
  6797. void AddTypesConvertedFrom(QualType Ty,
  6798. SourceLocation Loc,
  6799. bool AllowUserConversions,
  6800. bool AllowExplicitConversions,
  6801. const Qualifiers &VisibleTypeConversionsQuals);
  6802. /// pointer_begin - First pointer type found;
  6803. iterator pointer_begin() { return PointerTypes.begin(); }
  6804. /// pointer_end - Past the last pointer type found;
  6805. iterator pointer_end() { return PointerTypes.end(); }
  6806. /// member_pointer_begin - First member pointer type found;
  6807. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6808. /// member_pointer_end - Past the last member pointer type found;
  6809. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6810. /// enumeration_begin - First enumeration type found;
  6811. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6812. /// enumeration_end - Past the last enumeration type found;
  6813. iterator enumeration_end() { return EnumerationTypes.end(); }
  6814. iterator vector_begin() { return VectorTypes.begin(); }
  6815. iterator vector_end() { return VectorTypes.end(); }
  6816. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6817. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6818. bool hasNullPtrType() const { return HasNullPtrType; }
  6819. };
  6820. } // end anonymous namespace
  6821. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6822. /// the set of pointer types along with any more-qualified variants of
  6823. /// that type. For example, if @p Ty is "int const *", this routine
  6824. /// will add "int const *", "int const volatile *", "int const
  6825. /// restrict *", and "int const volatile restrict *" to the set of
  6826. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6827. /// false otherwise.
  6828. ///
  6829. /// FIXME: what to do about extended qualifiers?
  6830. bool
  6831. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6832. const Qualifiers &VisibleQuals) {
  6833. // Insert this type.
  6834. if (!PointerTypes.insert(Ty))
  6835. return false;
  6836. QualType PointeeTy;
  6837. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6838. bool buildObjCPtr = false;
  6839. if (!PointerTy) {
  6840. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6841. PointeeTy = PTy->getPointeeType();
  6842. buildObjCPtr = true;
  6843. } else {
  6844. PointeeTy = PointerTy->getPointeeType();
  6845. }
  6846. // Don't add qualified variants of arrays. For one, they're not allowed
  6847. // (the qualifier would sink to the element type), and for another, the
  6848. // only overload situation where it matters is subscript or pointer +- int,
  6849. // and those shouldn't have qualifier variants anyway.
  6850. if (PointeeTy->isArrayType())
  6851. return true;
  6852. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6853. bool hasVolatile = VisibleQuals.hasVolatile();
  6854. bool hasRestrict = VisibleQuals.hasRestrict();
  6855. // Iterate through all strict supersets of BaseCVR.
  6856. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6857. if ((CVR | BaseCVR) != CVR) continue;
  6858. // Skip over volatile if no volatile found anywhere in the types.
  6859. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6860. // Skip over restrict if no restrict found anywhere in the types, or if
  6861. // the type cannot be restrict-qualified.
  6862. if ((CVR & Qualifiers::Restrict) &&
  6863. (!hasRestrict ||
  6864. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6865. continue;
  6866. // Build qualified pointee type.
  6867. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6868. // Build qualified pointer type.
  6869. QualType QPointerTy;
  6870. if (!buildObjCPtr)
  6871. QPointerTy = Context.getPointerType(QPointeeTy);
  6872. else
  6873. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6874. // Insert qualified pointer type.
  6875. PointerTypes.insert(QPointerTy);
  6876. }
  6877. return true;
  6878. }
  6879. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6880. /// to the set of pointer types along with any more-qualified variants of
  6881. /// that type. For example, if @p Ty is "int const *", this routine
  6882. /// will add "int const *", "int const volatile *", "int const
  6883. /// restrict *", and "int const volatile restrict *" to the set of
  6884. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6885. /// false otherwise.
  6886. ///
  6887. /// FIXME: what to do about extended qualifiers?
  6888. bool
  6889. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6890. QualType Ty) {
  6891. // Insert this type.
  6892. if (!MemberPointerTypes.insert(Ty))
  6893. return false;
  6894. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6895. assert(PointerTy && "type was not a member pointer type!");
  6896. QualType PointeeTy = PointerTy->getPointeeType();
  6897. // Don't add qualified variants of arrays. For one, they're not allowed
  6898. // (the qualifier would sink to the element type), and for another, the
  6899. // only overload situation where it matters is subscript or pointer +- int,
  6900. // and those shouldn't have qualifier variants anyway.
  6901. if (PointeeTy->isArrayType())
  6902. return true;
  6903. const Type *ClassTy = PointerTy->getClass();
  6904. // Iterate through all strict supersets of the pointee type's CVR
  6905. // qualifiers.
  6906. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6907. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6908. if ((CVR | BaseCVR) != CVR) continue;
  6909. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6910. MemberPointerTypes.insert(
  6911. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6912. }
  6913. return true;
  6914. }
  6915. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6916. /// Ty can be implicit converted to the given set of @p Types. We're
  6917. /// primarily interested in pointer types and enumeration types. We also
  6918. /// take member pointer types, for the conditional operator.
  6919. /// AllowUserConversions is true if we should look at the conversion
  6920. /// functions of a class type, and AllowExplicitConversions if we
  6921. /// should also include the explicit conversion functions of a class
  6922. /// type.
  6923. void
  6924. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6925. SourceLocation Loc,
  6926. bool AllowUserConversions,
  6927. bool AllowExplicitConversions,
  6928. const Qualifiers &VisibleQuals) {
  6929. // Only deal with canonical types.
  6930. Ty = Context.getCanonicalType(Ty);
  6931. // Look through reference types; they aren't part of the type of an
  6932. // expression for the purposes of conversions.
  6933. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6934. Ty = RefTy->getPointeeType();
  6935. // If we're dealing with an array type, decay to the pointer.
  6936. if (Ty->isArrayType())
  6937. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6938. // Otherwise, we don't care about qualifiers on the type.
  6939. Ty = Ty.getLocalUnqualifiedType();
  6940. // Flag if we ever add a non-record type.
  6941. const RecordType *TyRec = Ty->getAs<RecordType>();
  6942. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6943. // Flag if we encounter an arithmetic type.
  6944. HasArithmeticOrEnumeralTypes =
  6945. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6946. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6947. PointerTypes.insert(Ty);
  6948. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6949. // Insert our type, and its more-qualified variants, into the set
  6950. // of types.
  6951. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6952. return;
  6953. } else if (Ty->isMemberPointerType()) {
  6954. // Member pointers are far easier, since the pointee can't be converted.
  6955. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6956. return;
  6957. } else if (Ty->isEnumeralType()) {
  6958. HasArithmeticOrEnumeralTypes = true;
  6959. EnumerationTypes.insert(Ty);
  6960. } else if (Ty->isVectorType()) {
  6961. // We treat vector types as arithmetic types in many contexts as an
  6962. // extension.
  6963. HasArithmeticOrEnumeralTypes = true;
  6964. VectorTypes.insert(Ty);
  6965. } else if (Ty->isNullPtrType()) {
  6966. HasNullPtrType = true;
  6967. } else if (AllowUserConversions && TyRec) {
  6968. // No conversion functions in incomplete types.
  6969. if (!SemaRef.isCompleteType(Loc, Ty))
  6970. return;
  6971. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6972. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6973. if (isa<UsingShadowDecl>(D))
  6974. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6975. // Skip conversion function templates; they don't tell us anything
  6976. // about which builtin types we can convert to.
  6977. if (isa<FunctionTemplateDecl>(D))
  6978. continue;
  6979. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6980. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6981. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6982. VisibleQuals);
  6983. }
  6984. }
  6985. }
  6986. }
  6987. /// Helper function for adjusting address spaces for the pointer or reference
  6988. /// operands of builtin operators depending on the argument.
  6989. static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
  6990. Expr *Arg) {
  6991. return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
  6992. }
  6993. /// Helper function for AddBuiltinOperatorCandidates() that adds
  6994. /// the volatile- and non-volatile-qualified assignment operators for the
  6995. /// given type to the candidate set.
  6996. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  6997. QualType T,
  6998. ArrayRef<Expr *> Args,
  6999. OverloadCandidateSet &CandidateSet) {
  7000. QualType ParamTypes[2];
  7001. // T& operator=(T&, T)
  7002. ParamTypes[0] = S.Context.getLValueReferenceType(
  7003. AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
  7004. ParamTypes[1] = T;
  7005. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7006. /*IsAssignmentOperator=*/true);
  7007. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  7008. // volatile T& operator=(volatile T&, T)
  7009. ParamTypes[0] = S.Context.getLValueReferenceType(
  7010. AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
  7011. Args[0]));
  7012. ParamTypes[1] = T;
  7013. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7014. /*IsAssignmentOperator=*/true);
  7015. }
  7016. }
  7017. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  7018. /// if any, found in visible type conversion functions found in ArgExpr's type.
  7019. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  7020. Qualifiers VRQuals;
  7021. const RecordType *TyRec;
  7022. if (const MemberPointerType *RHSMPType =
  7023. ArgExpr->getType()->getAs<MemberPointerType>())
  7024. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  7025. else
  7026. TyRec = ArgExpr->getType()->getAs<RecordType>();
  7027. if (!TyRec) {
  7028. // Just to be safe, assume the worst case.
  7029. VRQuals.addVolatile();
  7030. VRQuals.addRestrict();
  7031. return VRQuals;
  7032. }
  7033. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  7034. if (!ClassDecl->hasDefinition())
  7035. return VRQuals;
  7036. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  7037. if (isa<UsingShadowDecl>(D))
  7038. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  7039. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  7040. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  7041. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  7042. CanTy = ResTypeRef->getPointeeType();
  7043. // Need to go down the pointer/mempointer chain and add qualifiers
  7044. // as see them.
  7045. bool done = false;
  7046. while (!done) {
  7047. if (CanTy.isRestrictQualified())
  7048. VRQuals.addRestrict();
  7049. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  7050. CanTy = ResTypePtr->getPointeeType();
  7051. else if (const MemberPointerType *ResTypeMPtr =
  7052. CanTy->getAs<MemberPointerType>())
  7053. CanTy = ResTypeMPtr->getPointeeType();
  7054. else
  7055. done = true;
  7056. if (CanTy.isVolatileQualified())
  7057. VRQuals.addVolatile();
  7058. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  7059. return VRQuals;
  7060. }
  7061. }
  7062. }
  7063. return VRQuals;
  7064. }
  7065. namespace {
  7066. /// Helper class to manage the addition of builtin operator overload
  7067. /// candidates. It provides shared state and utility methods used throughout
  7068. /// the process, as well as a helper method to add each group of builtin
  7069. /// operator overloads from the standard to a candidate set.
  7070. class BuiltinOperatorOverloadBuilder {
  7071. // Common instance state available to all overload candidate addition methods.
  7072. Sema &S;
  7073. ArrayRef<Expr *> Args;
  7074. Qualifiers VisibleTypeConversionsQuals;
  7075. bool HasArithmeticOrEnumeralCandidateType;
  7076. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  7077. OverloadCandidateSet &CandidateSet;
  7078. static constexpr int ArithmeticTypesCap = 24;
  7079. SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
  7080. // Define some indices used to iterate over the arithmetic types in
  7081. // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
  7082. // types are that preserved by promotion (C++ [over.built]p2).
  7083. unsigned FirstIntegralType,
  7084. LastIntegralType;
  7085. unsigned FirstPromotedIntegralType,
  7086. LastPromotedIntegralType;
  7087. unsigned FirstPromotedArithmeticType,
  7088. LastPromotedArithmeticType;
  7089. unsigned NumArithmeticTypes;
  7090. void InitArithmeticTypes() {
  7091. // Start of promoted types.
  7092. FirstPromotedArithmeticType = 0;
  7093. ArithmeticTypes.push_back(S.Context.FloatTy);
  7094. ArithmeticTypes.push_back(S.Context.DoubleTy);
  7095. ArithmeticTypes.push_back(S.Context.LongDoubleTy);
  7096. if (S.Context.getTargetInfo().hasFloat128Type())
  7097. ArithmeticTypes.push_back(S.Context.Float128Ty);
  7098. // Start of integral types.
  7099. FirstIntegralType = ArithmeticTypes.size();
  7100. FirstPromotedIntegralType = ArithmeticTypes.size();
  7101. ArithmeticTypes.push_back(S.Context.IntTy);
  7102. ArithmeticTypes.push_back(S.Context.LongTy);
  7103. ArithmeticTypes.push_back(S.Context.LongLongTy);
  7104. if (S.Context.getTargetInfo().hasInt128Type())
  7105. ArithmeticTypes.push_back(S.Context.Int128Ty);
  7106. ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
  7107. ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
  7108. ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
  7109. if (S.Context.getTargetInfo().hasInt128Type())
  7110. ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
  7111. LastPromotedIntegralType = ArithmeticTypes.size();
  7112. LastPromotedArithmeticType = ArithmeticTypes.size();
  7113. // End of promoted types.
  7114. ArithmeticTypes.push_back(S.Context.BoolTy);
  7115. ArithmeticTypes.push_back(S.Context.CharTy);
  7116. ArithmeticTypes.push_back(S.Context.WCharTy);
  7117. if (S.Context.getLangOpts().Char8)
  7118. ArithmeticTypes.push_back(S.Context.Char8Ty);
  7119. ArithmeticTypes.push_back(S.Context.Char16Ty);
  7120. ArithmeticTypes.push_back(S.Context.Char32Ty);
  7121. ArithmeticTypes.push_back(S.Context.SignedCharTy);
  7122. ArithmeticTypes.push_back(S.Context.ShortTy);
  7123. ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
  7124. ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
  7125. LastIntegralType = ArithmeticTypes.size();
  7126. NumArithmeticTypes = ArithmeticTypes.size();
  7127. // End of integral types.
  7128. // FIXME: What about complex? What about half?
  7129. assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
  7130. "Enough inline storage for all arithmetic types.");
  7131. }
  7132. /// Helper method to factor out the common pattern of adding overloads
  7133. /// for '++' and '--' builtin operators.
  7134. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  7135. bool HasVolatile,
  7136. bool HasRestrict) {
  7137. QualType ParamTypes[2] = {
  7138. S.Context.getLValueReferenceType(CandidateTy),
  7139. S.Context.IntTy
  7140. };
  7141. // Non-volatile version.
  7142. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7143. // Use a heuristic to reduce number of builtin candidates in the set:
  7144. // add volatile version only if there are conversions to a volatile type.
  7145. if (HasVolatile) {
  7146. ParamTypes[0] =
  7147. S.Context.getLValueReferenceType(
  7148. S.Context.getVolatileType(CandidateTy));
  7149. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7150. }
  7151. // Add restrict version only if there are conversions to a restrict type
  7152. // and our candidate type is a non-restrict-qualified pointer.
  7153. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  7154. !CandidateTy.isRestrictQualified()) {
  7155. ParamTypes[0]
  7156. = S.Context.getLValueReferenceType(
  7157. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  7158. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7159. if (HasVolatile) {
  7160. ParamTypes[0]
  7161. = S.Context.getLValueReferenceType(
  7162. S.Context.getCVRQualifiedType(CandidateTy,
  7163. (Qualifiers::Volatile |
  7164. Qualifiers::Restrict)));
  7165. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7166. }
  7167. }
  7168. }
  7169. public:
  7170. BuiltinOperatorOverloadBuilder(
  7171. Sema &S, ArrayRef<Expr *> Args,
  7172. Qualifiers VisibleTypeConversionsQuals,
  7173. bool HasArithmeticOrEnumeralCandidateType,
  7174. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  7175. OverloadCandidateSet &CandidateSet)
  7176. : S(S), Args(Args),
  7177. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  7178. HasArithmeticOrEnumeralCandidateType(
  7179. HasArithmeticOrEnumeralCandidateType),
  7180. CandidateTypes(CandidateTypes),
  7181. CandidateSet(CandidateSet) {
  7182. InitArithmeticTypes();
  7183. }
  7184. // Increment is deprecated for bool since C++17.
  7185. //
  7186. // C++ [over.built]p3:
  7187. //
  7188. // For every pair (T, VQ), where T is an arithmetic type other
  7189. // than bool, and VQ is either volatile or empty, there exist
  7190. // candidate operator functions of the form
  7191. //
  7192. // VQ T& operator++(VQ T&);
  7193. // T operator++(VQ T&, int);
  7194. //
  7195. // C++ [over.built]p4:
  7196. //
  7197. // For every pair (T, VQ), where T is an arithmetic type other
  7198. // than bool, and VQ is either volatile or empty, there exist
  7199. // candidate operator functions of the form
  7200. //
  7201. // VQ T& operator--(VQ T&);
  7202. // T operator--(VQ T&, int);
  7203. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  7204. if (!HasArithmeticOrEnumeralCandidateType)
  7205. return;
  7206. for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
  7207. const auto TypeOfT = ArithmeticTypes[Arith];
  7208. if (TypeOfT == S.Context.BoolTy) {
  7209. if (Op == OO_MinusMinus)
  7210. continue;
  7211. if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
  7212. continue;
  7213. }
  7214. addPlusPlusMinusMinusStyleOverloads(
  7215. TypeOfT,
  7216. VisibleTypeConversionsQuals.hasVolatile(),
  7217. VisibleTypeConversionsQuals.hasRestrict());
  7218. }
  7219. }
  7220. // C++ [over.built]p5:
  7221. //
  7222. // For every pair (T, VQ), where T is a cv-qualified or
  7223. // cv-unqualified object type, and VQ is either volatile or
  7224. // empty, there exist candidate operator functions of the form
  7225. //
  7226. // T*VQ& operator++(T*VQ&);
  7227. // T*VQ& operator--(T*VQ&);
  7228. // T* operator++(T*VQ&, int);
  7229. // T* operator--(T*VQ&, int);
  7230. void addPlusPlusMinusMinusPointerOverloads() {
  7231. for (BuiltinCandidateTypeSet::iterator
  7232. Ptr = CandidateTypes[0].pointer_begin(),
  7233. PtrEnd = CandidateTypes[0].pointer_end();
  7234. Ptr != PtrEnd; ++Ptr) {
  7235. // Skip pointer types that aren't pointers to object types.
  7236. if (!(*Ptr)->getPointeeType()->isObjectType())
  7237. continue;
  7238. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  7239. (!(*Ptr).isVolatileQualified() &&
  7240. VisibleTypeConversionsQuals.hasVolatile()),
  7241. (!(*Ptr).isRestrictQualified() &&
  7242. VisibleTypeConversionsQuals.hasRestrict()));
  7243. }
  7244. }
  7245. // C++ [over.built]p6:
  7246. // For every cv-qualified or cv-unqualified object type T, there
  7247. // exist candidate operator functions of the form
  7248. //
  7249. // T& operator*(T*);
  7250. //
  7251. // C++ [over.built]p7:
  7252. // For every function type T that does not have cv-qualifiers or a
  7253. // ref-qualifier, there exist candidate operator functions of the form
  7254. // T& operator*(T*);
  7255. void addUnaryStarPointerOverloads() {
  7256. for (BuiltinCandidateTypeSet::iterator
  7257. Ptr = CandidateTypes[0].pointer_begin(),
  7258. PtrEnd = CandidateTypes[0].pointer_end();
  7259. Ptr != PtrEnd; ++Ptr) {
  7260. QualType ParamTy = *Ptr;
  7261. QualType PointeeTy = ParamTy->getPointeeType();
  7262. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  7263. continue;
  7264. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  7265. if (Proto->getMethodQuals() || Proto->getRefQualifier())
  7266. continue;
  7267. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7268. }
  7269. }
  7270. // C++ [over.built]p9:
  7271. // For every promoted arithmetic type T, there exist candidate
  7272. // operator functions of the form
  7273. //
  7274. // T operator+(T);
  7275. // T operator-(T);
  7276. void addUnaryPlusOrMinusArithmeticOverloads() {
  7277. if (!HasArithmeticOrEnumeralCandidateType)
  7278. return;
  7279. for (unsigned Arith = FirstPromotedArithmeticType;
  7280. Arith < LastPromotedArithmeticType; ++Arith) {
  7281. QualType ArithTy = ArithmeticTypes[Arith];
  7282. S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
  7283. }
  7284. // Extension: We also add these operators for vector types.
  7285. for (BuiltinCandidateTypeSet::iterator
  7286. Vec = CandidateTypes[0].vector_begin(),
  7287. VecEnd = CandidateTypes[0].vector_end();
  7288. Vec != VecEnd; ++Vec) {
  7289. QualType VecTy = *Vec;
  7290. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7291. }
  7292. }
  7293. // C++ [over.built]p8:
  7294. // For every type T, there exist candidate operator functions of
  7295. // the form
  7296. //
  7297. // T* operator+(T*);
  7298. void addUnaryPlusPointerOverloads() {
  7299. for (BuiltinCandidateTypeSet::iterator
  7300. Ptr = CandidateTypes[0].pointer_begin(),
  7301. PtrEnd = CandidateTypes[0].pointer_end();
  7302. Ptr != PtrEnd; ++Ptr) {
  7303. QualType ParamTy = *Ptr;
  7304. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
  7305. }
  7306. }
  7307. // C++ [over.built]p10:
  7308. // For every promoted integral type T, there exist candidate
  7309. // operator functions of the form
  7310. //
  7311. // T operator~(T);
  7312. void addUnaryTildePromotedIntegralOverloads() {
  7313. if (!HasArithmeticOrEnumeralCandidateType)
  7314. return;
  7315. for (unsigned Int = FirstPromotedIntegralType;
  7316. Int < LastPromotedIntegralType; ++Int) {
  7317. QualType IntTy = ArithmeticTypes[Int];
  7318. S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
  7319. }
  7320. // Extension: We also add this operator for vector types.
  7321. for (BuiltinCandidateTypeSet::iterator
  7322. Vec = CandidateTypes[0].vector_begin(),
  7323. VecEnd = CandidateTypes[0].vector_end();
  7324. Vec != VecEnd; ++Vec) {
  7325. QualType VecTy = *Vec;
  7326. S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
  7327. }
  7328. }
  7329. // C++ [over.match.oper]p16:
  7330. // For every pointer to member type T or type std::nullptr_t, there
  7331. // exist candidate operator functions of the form
  7332. //
  7333. // bool operator==(T,T);
  7334. // bool operator!=(T,T);
  7335. void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
  7336. /// Set of (canonical) types that we've already handled.
  7337. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7338. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7339. for (BuiltinCandidateTypeSet::iterator
  7340. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7341. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7342. MemPtr != MemPtrEnd;
  7343. ++MemPtr) {
  7344. // Don't add the same builtin candidate twice.
  7345. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7346. continue;
  7347. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7348. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7349. }
  7350. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  7351. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  7352. if (AddedTypes.insert(NullPtrTy).second) {
  7353. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  7354. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7355. }
  7356. }
  7357. }
  7358. }
  7359. // C++ [over.built]p15:
  7360. //
  7361. // For every T, where T is an enumeration type or a pointer type,
  7362. // there exist candidate operator functions of the form
  7363. //
  7364. // bool operator<(T, T);
  7365. // bool operator>(T, T);
  7366. // bool operator<=(T, T);
  7367. // bool operator>=(T, T);
  7368. // bool operator==(T, T);
  7369. // bool operator!=(T, T);
  7370. // R operator<=>(T, T)
  7371. void addGenericBinaryPointerOrEnumeralOverloads() {
  7372. // C++ [over.match.oper]p3:
  7373. // [...]the built-in candidates include all of the candidate operator
  7374. // functions defined in 13.6 that, compared to the given operator, [...]
  7375. // do not have the same parameter-type-list as any non-template non-member
  7376. // candidate.
  7377. //
  7378. // Note that in practice, this only affects enumeration types because there
  7379. // aren't any built-in candidates of record type, and a user-defined operator
  7380. // must have an operand of record or enumeration type. Also, the only other
  7381. // overloaded operator with enumeration arguments, operator=,
  7382. // cannot be overloaded for enumeration types, so this is the only place
  7383. // where we must suppress candidates like this.
  7384. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  7385. UserDefinedBinaryOperators;
  7386. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7387. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  7388. CandidateTypes[ArgIdx].enumeration_end()) {
  7389. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  7390. CEnd = CandidateSet.end();
  7391. C != CEnd; ++C) {
  7392. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  7393. continue;
  7394. if (C->Function->isFunctionTemplateSpecialization())
  7395. continue;
  7396. // We interpret "same parameter-type-list" as applying to the
  7397. // "synthesized candidate, with the order of the two parameters
  7398. // reversed", not to the original function.
  7399. bool Reversed = C->RewriteKind & CRK_Reversed;
  7400. QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
  7401. ->getType()
  7402. .getUnqualifiedType();
  7403. QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
  7404. ->getType()
  7405. .getUnqualifiedType();
  7406. // Skip if either parameter isn't of enumeral type.
  7407. if (!FirstParamType->isEnumeralType() ||
  7408. !SecondParamType->isEnumeralType())
  7409. continue;
  7410. // Add this operator to the set of known user-defined operators.
  7411. UserDefinedBinaryOperators.insert(
  7412. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  7413. S.Context.getCanonicalType(SecondParamType)));
  7414. }
  7415. }
  7416. }
  7417. /// Set of (canonical) types that we've already handled.
  7418. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7419. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7420. for (BuiltinCandidateTypeSet::iterator
  7421. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7422. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7423. Ptr != PtrEnd; ++Ptr) {
  7424. // Don't add the same builtin candidate twice.
  7425. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7426. continue;
  7427. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7428. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7429. }
  7430. for (BuiltinCandidateTypeSet::iterator
  7431. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7432. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7433. Enum != EnumEnd; ++Enum) {
  7434. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  7435. // Don't add the same builtin candidate twice, or if a user defined
  7436. // candidate exists.
  7437. if (!AddedTypes.insert(CanonType).second ||
  7438. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  7439. CanonType)))
  7440. continue;
  7441. QualType ParamTypes[2] = { *Enum, *Enum };
  7442. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7443. }
  7444. }
  7445. }
  7446. // C++ [over.built]p13:
  7447. //
  7448. // For every cv-qualified or cv-unqualified object type T
  7449. // there exist candidate operator functions of the form
  7450. //
  7451. // T* operator+(T*, ptrdiff_t);
  7452. // T& operator[](T*, ptrdiff_t); [BELOW]
  7453. // T* operator-(T*, ptrdiff_t);
  7454. // T* operator+(ptrdiff_t, T*);
  7455. // T& operator[](ptrdiff_t, T*); [BELOW]
  7456. //
  7457. // C++ [over.built]p14:
  7458. //
  7459. // For every T, where T is a pointer to object type, there
  7460. // exist candidate operator functions of the form
  7461. //
  7462. // ptrdiff_t operator-(T, T);
  7463. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  7464. /// Set of (canonical) types that we've already handled.
  7465. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7466. for (int Arg = 0; Arg < 2; ++Arg) {
  7467. QualType AsymmetricParamTypes[2] = {
  7468. S.Context.getPointerDiffType(),
  7469. S.Context.getPointerDiffType(),
  7470. };
  7471. for (BuiltinCandidateTypeSet::iterator
  7472. Ptr = CandidateTypes[Arg].pointer_begin(),
  7473. PtrEnd = CandidateTypes[Arg].pointer_end();
  7474. Ptr != PtrEnd; ++Ptr) {
  7475. QualType PointeeTy = (*Ptr)->getPointeeType();
  7476. if (!PointeeTy->isObjectType())
  7477. continue;
  7478. AsymmetricParamTypes[Arg] = *Ptr;
  7479. if (Arg == 0 || Op == OO_Plus) {
  7480. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  7481. // T* operator+(ptrdiff_t, T*);
  7482. S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
  7483. }
  7484. if (Op == OO_Minus) {
  7485. // ptrdiff_t operator-(T, T);
  7486. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7487. continue;
  7488. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7489. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7490. }
  7491. }
  7492. }
  7493. }
  7494. // C++ [over.built]p12:
  7495. //
  7496. // For every pair of promoted arithmetic types L and R, there
  7497. // exist candidate operator functions of the form
  7498. //
  7499. // LR operator*(L, R);
  7500. // LR operator/(L, R);
  7501. // LR operator+(L, R);
  7502. // LR operator-(L, R);
  7503. // bool operator<(L, R);
  7504. // bool operator>(L, R);
  7505. // bool operator<=(L, R);
  7506. // bool operator>=(L, R);
  7507. // bool operator==(L, R);
  7508. // bool operator!=(L, R);
  7509. //
  7510. // where LR is the result of the usual arithmetic conversions
  7511. // between types L and R.
  7512. //
  7513. // C++ [over.built]p24:
  7514. //
  7515. // For every pair of promoted arithmetic types L and R, there exist
  7516. // candidate operator functions of the form
  7517. //
  7518. // LR operator?(bool, L, R);
  7519. //
  7520. // where LR is the result of the usual arithmetic conversions
  7521. // between types L and R.
  7522. // Our candidates ignore the first parameter.
  7523. void addGenericBinaryArithmeticOverloads() {
  7524. if (!HasArithmeticOrEnumeralCandidateType)
  7525. return;
  7526. for (unsigned Left = FirstPromotedArithmeticType;
  7527. Left < LastPromotedArithmeticType; ++Left) {
  7528. for (unsigned Right = FirstPromotedArithmeticType;
  7529. Right < LastPromotedArithmeticType; ++Right) {
  7530. QualType LandR[2] = { ArithmeticTypes[Left],
  7531. ArithmeticTypes[Right] };
  7532. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7533. }
  7534. }
  7535. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  7536. // conditional operator for vector types.
  7537. for (BuiltinCandidateTypeSet::iterator
  7538. Vec1 = CandidateTypes[0].vector_begin(),
  7539. Vec1End = CandidateTypes[0].vector_end();
  7540. Vec1 != Vec1End; ++Vec1) {
  7541. for (BuiltinCandidateTypeSet::iterator
  7542. Vec2 = CandidateTypes[1].vector_begin(),
  7543. Vec2End = CandidateTypes[1].vector_end();
  7544. Vec2 != Vec2End; ++Vec2) {
  7545. QualType LandR[2] = { *Vec1, *Vec2 };
  7546. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7547. }
  7548. }
  7549. }
  7550. // C++2a [over.built]p14:
  7551. //
  7552. // For every integral type T there exists a candidate operator function
  7553. // of the form
  7554. //
  7555. // std::strong_ordering operator<=>(T, T)
  7556. //
  7557. // C++2a [over.built]p15:
  7558. //
  7559. // For every pair of floating-point types L and R, there exists a candidate
  7560. // operator function of the form
  7561. //
  7562. // std::partial_ordering operator<=>(L, R);
  7563. //
  7564. // FIXME: The current specification for integral types doesn't play nice with
  7565. // the direction of p0946r0, which allows mixed integral and unscoped-enum
  7566. // comparisons. Under the current spec this can lead to ambiguity during
  7567. // overload resolution. For example:
  7568. //
  7569. // enum A : int {a};
  7570. // auto x = (a <=> (long)42);
  7571. //
  7572. // error: call is ambiguous for arguments 'A' and 'long'.
  7573. // note: candidate operator<=>(int, int)
  7574. // note: candidate operator<=>(long, long)
  7575. //
  7576. // To avoid this error, this function deviates from the specification and adds
  7577. // the mixed overloads `operator<=>(L, R)` where L and R are promoted
  7578. // arithmetic types (the same as the generic relational overloads).
  7579. //
  7580. // For now this function acts as a placeholder.
  7581. void addThreeWayArithmeticOverloads() {
  7582. addGenericBinaryArithmeticOverloads();
  7583. }
  7584. // C++ [over.built]p17:
  7585. //
  7586. // For every pair of promoted integral types L and R, there
  7587. // exist candidate operator functions of the form
  7588. //
  7589. // LR operator%(L, R);
  7590. // LR operator&(L, R);
  7591. // LR operator^(L, R);
  7592. // LR operator|(L, R);
  7593. // L operator<<(L, R);
  7594. // L operator>>(L, R);
  7595. //
  7596. // where LR is the result of the usual arithmetic conversions
  7597. // between types L and R.
  7598. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7599. if (!HasArithmeticOrEnumeralCandidateType)
  7600. return;
  7601. for (unsigned Left = FirstPromotedIntegralType;
  7602. Left < LastPromotedIntegralType; ++Left) {
  7603. for (unsigned Right = FirstPromotedIntegralType;
  7604. Right < LastPromotedIntegralType; ++Right) {
  7605. QualType LandR[2] = { ArithmeticTypes[Left],
  7606. ArithmeticTypes[Right] };
  7607. S.AddBuiltinCandidate(LandR, Args, CandidateSet);
  7608. }
  7609. }
  7610. }
  7611. // C++ [over.built]p20:
  7612. //
  7613. // For every pair (T, VQ), where T is an enumeration or
  7614. // pointer to member type and VQ is either volatile or
  7615. // empty, there exist candidate operator functions of the form
  7616. //
  7617. // VQ T& operator=(VQ T&, T);
  7618. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7619. /// Set of (canonical) types that we've already handled.
  7620. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7621. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7622. for (BuiltinCandidateTypeSet::iterator
  7623. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7624. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7625. Enum != EnumEnd; ++Enum) {
  7626. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7627. continue;
  7628. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7629. }
  7630. for (BuiltinCandidateTypeSet::iterator
  7631. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7632. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7633. MemPtr != MemPtrEnd; ++MemPtr) {
  7634. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7635. continue;
  7636. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7637. }
  7638. }
  7639. }
  7640. // C++ [over.built]p19:
  7641. //
  7642. // For every pair (T, VQ), where T is any type and VQ is either
  7643. // volatile or empty, there exist candidate operator functions
  7644. // of the form
  7645. //
  7646. // T*VQ& operator=(T*VQ&, T*);
  7647. //
  7648. // C++ [over.built]p21:
  7649. //
  7650. // For every pair (T, VQ), where T is a cv-qualified or
  7651. // cv-unqualified object type and VQ is either volatile or
  7652. // empty, there exist candidate operator functions of the form
  7653. //
  7654. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7655. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7656. void addAssignmentPointerOverloads(bool isEqualOp) {
  7657. /// Set of (canonical) types that we've already handled.
  7658. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7659. for (BuiltinCandidateTypeSet::iterator
  7660. Ptr = CandidateTypes[0].pointer_begin(),
  7661. PtrEnd = CandidateTypes[0].pointer_end();
  7662. Ptr != PtrEnd; ++Ptr) {
  7663. // If this is operator=, keep track of the builtin candidates we added.
  7664. if (isEqualOp)
  7665. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7666. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7667. continue;
  7668. // non-volatile version
  7669. QualType ParamTypes[2] = {
  7670. S.Context.getLValueReferenceType(*Ptr),
  7671. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7672. };
  7673. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7674. /*IsAssignmentOperator=*/ isEqualOp);
  7675. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7676. VisibleTypeConversionsQuals.hasVolatile();
  7677. if (NeedVolatile) {
  7678. // volatile version
  7679. ParamTypes[0] =
  7680. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7681. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7682. /*IsAssignmentOperator=*/isEqualOp);
  7683. }
  7684. if (!(*Ptr).isRestrictQualified() &&
  7685. VisibleTypeConversionsQuals.hasRestrict()) {
  7686. // restrict version
  7687. ParamTypes[0]
  7688. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7689. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7690. /*IsAssignmentOperator=*/isEqualOp);
  7691. if (NeedVolatile) {
  7692. // volatile restrict version
  7693. ParamTypes[0]
  7694. = S.Context.getLValueReferenceType(
  7695. S.Context.getCVRQualifiedType(*Ptr,
  7696. (Qualifiers::Volatile |
  7697. Qualifiers::Restrict)));
  7698. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7699. /*IsAssignmentOperator=*/isEqualOp);
  7700. }
  7701. }
  7702. }
  7703. if (isEqualOp) {
  7704. for (BuiltinCandidateTypeSet::iterator
  7705. Ptr = CandidateTypes[1].pointer_begin(),
  7706. PtrEnd = CandidateTypes[1].pointer_end();
  7707. Ptr != PtrEnd; ++Ptr) {
  7708. // Make sure we don't add the same candidate twice.
  7709. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7710. continue;
  7711. QualType ParamTypes[2] = {
  7712. S.Context.getLValueReferenceType(*Ptr),
  7713. *Ptr,
  7714. };
  7715. // non-volatile version
  7716. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7717. /*IsAssignmentOperator=*/true);
  7718. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7719. VisibleTypeConversionsQuals.hasVolatile();
  7720. if (NeedVolatile) {
  7721. // volatile version
  7722. ParamTypes[0] =
  7723. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7724. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7725. /*IsAssignmentOperator=*/true);
  7726. }
  7727. if (!(*Ptr).isRestrictQualified() &&
  7728. VisibleTypeConversionsQuals.hasRestrict()) {
  7729. // restrict version
  7730. ParamTypes[0]
  7731. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7732. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7733. /*IsAssignmentOperator=*/true);
  7734. if (NeedVolatile) {
  7735. // volatile restrict version
  7736. ParamTypes[0]
  7737. = S.Context.getLValueReferenceType(
  7738. S.Context.getCVRQualifiedType(*Ptr,
  7739. (Qualifiers::Volatile |
  7740. Qualifiers::Restrict)));
  7741. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7742. /*IsAssignmentOperator=*/true);
  7743. }
  7744. }
  7745. }
  7746. }
  7747. }
  7748. // C++ [over.built]p18:
  7749. //
  7750. // For every triple (L, VQ, R), where L is an arithmetic type,
  7751. // VQ is either volatile or empty, and R is a promoted
  7752. // arithmetic type, there exist candidate operator functions of
  7753. // the form
  7754. //
  7755. // VQ L& operator=(VQ L&, R);
  7756. // VQ L& operator*=(VQ L&, R);
  7757. // VQ L& operator/=(VQ L&, R);
  7758. // VQ L& operator+=(VQ L&, R);
  7759. // VQ L& operator-=(VQ L&, R);
  7760. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7761. if (!HasArithmeticOrEnumeralCandidateType)
  7762. return;
  7763. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7764. for (unsigned Right = FirstPromotedArithmeticType;
  7765. Right < LastPromotedArithmeticType; ++Right) {
  7766. QualType ParamTypes[2];
  7767. ParamTypes[1] = ArithmeticTypes[Right];
  7768. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  7769. S, ArithmeticTypes[Left], Args[0]);
  7770. // Add this built-in operator as a candidate (VQ is empty).
  7771. ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
  7772. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7773. /*IsAssignmentOperator=*/isEqualOp);
  7774. // Add this built-in operator as a candidate (VQ is 'volatile').
  7775. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7776. ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
  7777. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7778. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7779. /*IsAssignmentOperator=*/isEqualOp);
  7780. }
  7781. }
  7782. }
  7783. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7784. for (BuiltinCandidateTypeSet::iterator
  7785. Vec1 = CandidateTypes[0].vector_begin(),
  7786. Vec1End = CandidateTypes[0].vector_end();
  7787. Vec1 != Vec1End; ++Vec1) {
  7788. for (BuiltinCandidateTypeSet::iterator
  7789. Vec2 = CandidateTypes[1].vector_begin(),
  7790. Vec2End = CandidateTypes[1].vector_end();
  7791. Vec2 != Vec2End; ++Vec2) {
  7792. QualType ParamTypes[2];
  7793. ParamTypes[1] = *Vec2;
  7794. // Add this built-in operator as a candidate (VQ is empty).
  7795. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7796. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7797. /*IsAssignmentOperator=*/isEqualOp);
  7798. // Add this built-in operator as a candidate (VQ is 'volatile').
  7799. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7800. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7801. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7802. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7803. /*IsAssignmentOperator=*/isEqualOp);
  7804. }
  7805. }
  7806. }
  7807. }
  7808. // C++ [over.built]p22:
  7809. //
  7810. // For every triple (L, VQ, R), where L is an integral type, VQ
  7811. // is either volatile or empty, and R is a promoted integral
  7812. // type, there exist candidate operator functions of the form
  7813. //
  7814. // VQ L& operator%=(VQ L&, R);
  7815. // VQ L& operator<<=(VQ L&, R);
  7816. // VQ L& operator>>=(VQ L&, R);
  7817. // VQ L& operator&=(VQ L&, R);
  7818. // VQ L& operator^=(VQ L&, R);
  7819. // VQ L& operator|=(VQ L&, R);
  7820. void addAssignmentIntegralOverloads() {
  7821. if (!HasArithmeticOrEnumeralCandidateType)
  7822. return;
  7823. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7824. for (unsigned Right = FirstPromotedIntegralType;
  7825. Right < LastPromotedIntegralType; ++Right) {
  7826. QualType ParamTypes[2];
  7827. ParamTypes[1] = ArithmeticTypes[Right];
  7828. auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
  7829. S, ArithmeticTypes[Left], Args[0]);
  7830. // Add this built-in operator as a candidate (VQ is empty).
  7831. ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
  7832. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7833. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7834. // Add this built-in operator as a candidate (VQ is 'volatile').
  7835. ParamTypes[0] = LeftBaseTy;
  7836. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7837. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7838. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7839. }
  7840. }
  7841. }
  7842. }
  7843. // C++ [over.operator]p23:
  7844. //
  7845. // There also exist candidate operator functions of the form
  7846. //
  7847. // bool operator!(bool);
  7848. // bool operator&&(bool, bool);
  7849. // bool operator||(bool, bool);
  7850. void addExclaimOverload() {
  7851. QualType ParamTy = S.Context.BoolTy;
  7852. S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
  7853. /*IsAssignmentOperator=*/false,
  7854. /*NumContextualBoolArguments=*/1);
  7855. }
  7856. void addAmpAmpOrPipePipeOverload() {
  7857. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7858. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
  7859. /*IsAssignmentOperator=*/false,
  7860. /*NumContextualBoolArguments=*/2);
  7861. }
  7862. // C++ [over.built]p13:
  7863. //
  7864. // For every cv-qualified or cv-unqualified object type T there
  7865. // exist candidate operator functions of the form
  7866. //
  7867. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7868. // T& operator[](T*, ptrdiff_t);
  7869. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7870. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7871. // T& operator[](ptrdiff_t, T*);
  7872. void addSubscriptOverloads() {
  7873. for (BuiltinCandidateTypeSet::iterator
  7874. Ptr = CandidateTypes[0].pointer_begin(),
  7875. PtrEnd = CandidateTypes[0].pointer_end();
  7876. Ptr != PtrEnd; ++Ptr) {
  7877. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7878. QualType PointeeType = (*Ptr)->getPointeeType();
  7879. if (!PointeeType->isObjectType())
  7880. continue;
  7881. // T& operator[](T*, ptrdiff_t)
  7882. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7883. }
  7884. for (BuiltinCandidateTypeSet::iterator
  7885. Ptr = CandidateTypes[1].pointer_begin(),
  7886. PtrEnd = CandidateTypes[1].pointer_end();
  7887. Ptr != PtrEnd; ++Ptr) {
  7888. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7889. QualType PointeeType = (*Ptr)->getPointeeType();
  7890. if (!PointeeType->isObjectType())
  7891. continue;
  7892. // T& operator[](ptrdiff_t, T*)
  7893. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7894. }
  7895. }
  7896. // C++ [over.built]p11:
  7897. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7898. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7899. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7900. // there exist candidate operator functions of the form
  7901. //
  7902. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7903. //
  7904. // where CV12 is the union of CV1 and CV2.
  7905. void addArrowStarOverloads() {
  7906. for (BuiltinCandidateTypeSet::iterator
  7907. Ptr = CandidateTypes[0].pointer_begin(),
  7908. PtrEnd = CandidateTypes[0].pointer_end();
  7909. Ptr != PtrEnd; ++Ptr) {
  7910. QualType C1Ty = (*Ptr);
  7911. QualType C1;
  7912. QualifierCollector Q1;
  7913. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7914. if (!isa<RecordType>(C1))
  7915. continue;
  7916. // heuristic to reduce number of builtin candidates in the set.
  7917. // Add volatile/restrict version only if there are conversions to a
  7918. // volatile/restrict type.
  7919. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7920. continue;
  7921. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7922. continue;
  7923. for (BuiltinCandidateTypeSet::iterator
  7924. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7925. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7926. MemPtr != MemPtrEnd; ++MemPtr) {
  7927. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7928. QualType C2 = QualType(mptr->getClass(), 0);
  7929. C2 = C2.getUnqualifiedType();
  7930. if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
  7931. break;
  7932. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7933. // build CV12 T&
  7934. QualType T = mptr->getPointeeType();
  7935. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7936. T.isVolatileQualified())
  7937. continue;
  7938. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7939. T.isRestrictQualified())
  7940. continue;
  7941. T = Q1.apply(S.Context, T);
  7942. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7943. }
  7944. }
  7945. }
  7946. // Note that we don't consider the first argument, since it has been
  7947. // contextually converted to bool long ago. The candidates below are
  7948. // therefore added as binary.
  7949. //
  7950. // C++ [over.built]p25:
  7951. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7952. // enumeration type, there exist candidate operator functions of the form
  7953. //
  7954. // T operator?(bool, T, T);
  7955. //
  7956. void addConditionalOperatorOverloads() {
  7957. /// Set of (canonical) types that we've already handled.
  7958. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7959. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7960. for (BuiltinCandidateTypeSet::iterator
  7961. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7962. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7963. Ptr != PtrEnd; ++Ptr) {
  7964. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7965. continue;
  7966. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7967. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7968. }
  7969. for (BuiltinCandidateTypeSet::iterator
  7970. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7971. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7972. MemPtr != MemPtrEnd; ++MemPtr) {
  7973. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7974. continue;
  7975. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7976. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7977. }
  7978. if (S.getLangOpts().CPlusPlus11) {
  7979. for (BuiltinCandidateTypeSet::iterator
  7980. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7981. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7982. Enum != EnumEnd; ++Enum) {
  7983. if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
  7984. continue;
  7985. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7986. continue;
  7987. QualType ParamTypes[2] = { *Enum, *Enum };
  7988. S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
  7989. }
  7990. }
  7991. }
  7992. }
  7993. };
  7994. } // end anonymous namespace
  7995. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  7996. /// operator overloads to the candidate set (C++ [over.built]), based
  7997. /// on the operator @p Op and the arguments given. For example, if the
  7998. /// operator is a binary '+', this routine might add "int
  7999. /// operator+(int, int)" to cover integer addition.
  8000. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  8001. SourceLocation OpLoc,
  8002. ArrayRef<Expr *> Args,
  8003. OverloadCandidateSet &CandidateSet) {
  8004. // Find all of the types that the arguments can convert to, but only
  8005. // if the operator we're looking at has built-in operator candidates
  8006. // that make use of these types. Also record whether we encounter non-record
  8007. // candidate types or either arithmetic or enumeral candidate types.
  8008. Qualifiers VisibleTypeConversionsQuals;
  8009. VisibleTypeConversionsQuals.addConst();
  8010. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  8011. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  8012. bool HasNonRecordCandidateType = false;
  8013. bool HasArithmeticOrEnumeralCandidateType = false;
  8014. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  8015. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  8016. CandidateTypes.emplace_back(*this);
  8017. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  8018. OpLoc,
  8019. true,
  8020. (Op == OO_Exclaim ||
  8021. Op == OO_AmpAmp ||
  8022. Op == OO_PipePipe),
  8023. VisibleTypeConversionsQuals);
  8024. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  8025. CandidateTypes[ArgIdx].hasNonRecordTypes();
  8026. HasArithmeticOrEnumeralCandidateType =
  8027. HasArithmeticOrEnumeralCandidateType ||
  8028. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  8029. }
  8030. // Exit early when no non-record types have been added to the candidate set
  8031. // for any of the arguments to the operator.
  8032. //
  8033. // We can't exit early for !, ||, or &&, since there we have always have
  8034. // 'bool' overloads.
  8035. if (!HasNonRecordCandidateType &&
  8036. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  8037. return;
  8038. // Setup an object to manage the common state for building overloads.
  8039. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  8040. VisibleTypeConversionsQuals,
  8041. HasArithmeticOrEnumeralCandidateType,
  8042. CandidateTypes, CandidateSet);
  8043. // Dispatch over the operation to add in only those overloads which apply.
  8044. switch (Op) {
  8045. case OO_None:
  8046. case NUM_OVERLOADED_OPERATORS:
  8047. llvm_unreachable("Expected an overloaded operator");
  8048. case OO_New:
  8049. case OO_Delete:
  8050. case OO_Array_New:
  8051. case OO_Array_Delete:
  8052. case OO_Call:
  8053. llvm_unreachable(
  8054. "Special operators don't use AddBuiltinOperatorCandidates");
  8055. case OO_Comma:
  8056. case OO_Arrow:
  8057. case OO_Coawait:
  8058. // C++ [over.match.oper]p3:
  8059. // -- For the operator ',', the unary operator '&', the
  8060. // operator '->', or the operator 'co_await', the
  8061. // built-in candidates set is empty.
  8062. break;
  8063. case OO_Plus: // '+' is either unary or binary
  8064. if (Args.size() == 1)
  8065. OpBuilder.addUnaryPlusPointerOverloads();
  8066. LLVM_FALLTHROUGH;
  8067. case OO_Minus: // '-' is either unary or binary
  8068. if (Args.size() == 1) {
  8069. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  8070. } else {
  8071. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  8072. OpBuilder.addGenericBinaryArithmeticOverloads();
  8073. }
  8074. break;
  8075. case OO_Star: // '*' is either unary or binary
  8076. if (Args.size() == 1)
  8077. OpBuilder.addUnaryStarPointerOverloads();
  8078. else
  8079. OpBuilder.addGenericBinaryArithmeticOverloads();
  8080. break;
  8081. case OO_Slash:
  8082. OpBuilder.addGenericBinaryArithmeticOverloads();
  8083. break;
  8084. case OO_PlusPlus:
  8085. case OO_MinusMinus:
  8086. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  8087. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  8088. break;
  8089. case OO_EqualEqual:
  8090. case OO_ExclaimEqual:
  8091. OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
  8092. LLVM_FALLTHROUGH;
  8093. case OO_Less:
  8094. case OO_Greater:
  8095. case OO_LessEqual:
  8096. case OO_GreaterEqual:
  8097. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
  8098. OpBuilder.addGenericBinaryArithmeticOverloads();
  8099. break;
  8100. case OO_Spaceship:
  8101. OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
  8102. OpBuilder.addThreeWayArithmeticOverloads();
  8103. break;
  8104. case OO_Percent:
  8105. case OO_Caret:
  8106. case OO_Pipe:
  8107. case OO_LessLess:
  8108. case OO_GreaterGreater:
  8109. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  8110. break;
  8111. case OO_Amp: // '&' is either unary or binary
  8112. if (Args.size() == 1)
  8113. // C++ [over.match.oper]p3:
  8114. // -- For the operator ',', the unary operator '&', or the
  8115. // operator '->', the built-in candidates set is empty.
  8116. break;
  8117. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  8118. break;
  8119. case OO_Tilde:
  8120. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  8121. break;
  8122. case OO_Equal:
  8123. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  8124. LLVM_FALLTHROUGH;
  8125. case OO_PlusEqual:
  8126. case OO_MinusEqual:
  8127. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  8128. LLVM_FALLTHROUGH;
  8129. case OO_StarEqual:
  8130. case OO_SlashEqual:
  8131. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  8132. break;
  8133. case OO_PercentEqual:
  8134. case OO_LessLessEqual:
  8135. case OO_GreaterGreaterEqual:
  8136. case OO_AmpEqual:
  8137. case OO_CaretEqual:
  8138. case OO_PipeEqual:
  8139. OpBuilder.addAssignmentIntegralOverloads();
  8140. break;
  8141. case OO_Exclaim:
  8142. OpBuilder.addExclaimOverload();
  8143. break;
  8144. case OO_AmpAmp:
  8145. case OO_PipePipe:
  8146. OpBuilder.addAmpAmpOrPipePipeOverload();
  8147. break;
  8148. case OO_Subscript:
  8149. OpBuilder.addSubscriptOverloads();
  8150. break;
  8151. case OO_ArrowStar:
  8152. OpBuilder.addArrowStarOverloads();
  8153. break;
  8154. case OO_Conditional:
  8155. OpBuilder.addConditionalOperatorOverloads();
  8156. OpBuilder.addGenericBinaryArithmeticOverloads();
  8157. break;
  8158. }
  8159. }
  8160. /// Add function candidates found via argument-dependent lookup
  8161. /// to the set of overloading candidates.
  8162. ///
  8163. /// This routine performs argument-dependent name lookup based on the
  8164. /// given function name (which may also be an operator name) and adds
  8165. /// all of the overload candidates found by ADL to the overload
  8166. /// candidate set (C++ [basic.lookup.argdep]).
  8167. void
  8168. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  8169. SourceLocation Loc,
  8170. ArrayRef<Expr *> Args,
  8171. TemplateArgumentListInfo *ExplicitTemplateArgs,
  8172. OverloadCandidateSet& CandidateSet,
  8173. bool PartialOverloading) {
  8174. ADLResult Fns;
  8175. // FIXME: This approach for uniquing ADL results (and removing
  8176. // redundant candidates from the set) relies on pointer-equality,
  8177. // which means we need to key off the canonical decl. However,
  8178. // always going back to the canonical decl might not get us the
  8179. // right set of default arguments. What default arguments are
  8180. // we supposed to consider on ADL candidates, anyway?
  8181. // FIXME: Pass in the explicit template arguments?
  8182. ArgumentDependentLookup(Name, Loc, Args, Fns);
  8183. // Erase all of the candidates we already knew about.
  8184. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  8185. CandEnd = CandidateSet.end();
  8186. Cand != CandEnd; ++Cand)
  8187. if (Cand->Function) {
  8188. Fns.erase(Cand->Function);
  8189. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  8190. Fns.erase(FunTmpl);
  8191. }
  8192. // For each of the ADL candidates we found, add it to the overload
  8193. // set.
  8194. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  8195. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  8196. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  8197. if (ExplicitTemplateArgs)
  8198. continue;
  8199. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
  8200. /*SuppressUserConversions=*/false, PartialOverloading,
  8201. /*AllowExplicit*/ true,
  8202. /*AllowExplicitConversions*/ false,
  8203. ADLCallKind::UsesADL);
  8204. } else {
  8205. AddTemplateOverloadCandidate(
  8206. cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
  8207. CandidateSet,
  8208. /*SuppressUserConversions=*/false, PartialOverloading,
  8209. /*AllowExplicit*/true, ADLCallKind::UsesADL);
  8210. }
  8211. }
  8212. }
  8213. namespace {
  8214. enum class Comparison { Equal, Better, Worse };
  8215. }
  8216. /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
  8217. /// overload resolution.
  8218. ///
  8219. /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
  8220. /// Cand1's first N enable_if attributes have precisely the same conditions as
  8221. /// Cand2's first N enable_if attributes (where N = the number of enable_if
  8222. /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
  8223. ///
  8224. /// Note that you can have a pair of candidates such that Cand1's enable_if
  8225. /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
  8226. /// worse than Cand1's.
  8227. static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
  8228. const FunctionDecl *Cand2) {
  8229. // Common case: One (or both) decls don't have enable_if attrs.
  8230. bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
  8231. bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
  8232. if (!Cand1Attr || !Cand2Attr) {
  8233. if (Cand1Attr == Cand2Attr)
  8234. return Comparison::Equal;
  8235. return Cand1Attr ? Comparison::Better : Comparison::Worse;
  8236. }
  8237. auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
  8238. auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
  8239. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  8240. for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
  8241. Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  8242. Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  8243. // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
  8244. // has fewer enable_if attributes than Cand2, and vice versa.
  8245. if (!Cand1A)
  8246. return Comparison::Worse;
  8247. if (!Cand2A)
  8248. return Comparison::Better;
  8249. Cand1ID.clear();
  8250. Cand2ID.clear();
  8251. (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
  8252. (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
  8253. if (Cand1ID != Cand2ID)
  8254. return Comparison::Worse;
  8255. }
  8256. return Comparison::Equal;
  8257. }
  8258. static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
  8259. const OverloadCandidate &Cand2) {
  8260. if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
  8261. !Cand2.Function->isMultiVersion())
  8262. return false;
  8263. // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
  8264. // is obviously better.
  8265. if (Cand1.Function->isInvalidDecl()) return false;
  8266. if (Cand2.Function->isInvalidDecl()) return true;
  8267. // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
  8268. // cpu_dispatch, else arbitrarily based on the identifiers.
  8269. bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
  8270. bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
  8271. const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
  8272. const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
  8273. if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
  8274. return false;
  8275. if (Cand1CPUDisp && !Cand2CPUDisp)
  8276. return true;
  8277. if (Cand2CPUDisp && !Cand1CPUDisp)
  8278. return false;
  8279. if (Cand1CPUSpec && Cand2CPUSpec) {
  8280. if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
  8281. return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
  8282. std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
  8283. FirstDiff = std::mismatch(
  8284. Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
  8285. Cand2CPUSpec->cpus_begin(),
  8286. [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
  8287. return LHS->getName() == RHS->getName();
  8288. });
  8289. assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
  8290. "Two different cpu-specific versions should not have the same "
  8291. "identifier list, otherwise they'd be the same decl!");
  8292. return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
  8293. }
  8294. llvm_unreachable("No way to get here unless both had cpu_dispatch");
  8295. }
  8296. /// isBetterOverloadCandidate - Determines whether the first overload
  8297. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  8298. bool clang::isBetterOverloadCandidate(
  8299. Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
  8300. SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
  8301. // Define viable functions to be better candidates than non-viable
  8302. // functions.
  8303. if (!Cand2.Viable)
  8304. return Cand1.Viable;
  8305. else if (!Cand1.Viable)
  8306. return false;
  8307. // C++ [over.match.best]p1:
  8308. //
  8309. // -- if F is a static member function, ICS1(F) is defined such
  8310. // that ICS1(F) is neither better nor worse than ICS1(G) for
  8311. // any function G, and, symmetrically, ICS1(G) is neither
  8312. // better nor worse than ICS1(F).
  8313. unsigned StartArg = 0;
  8314. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  8315. StartArg = 1;
  8316. auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
  8317. // We don't allow incompatible pointer conversions in C++.
  8318. if (!S.getLangOpts().CPlusPlus)
  8319. return ICS.isStandard() &&
  8320. ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
  8321. // The only ill-formed conversion we allow in C++ is the string literal to
  8322. // char* conversion, which is only considered ill-formed after C++11.
  8323. return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  8324. hasDeprecatedStringLiteralToCharPtrConversion(ICS);
  8325. };
  8326. // Define functions that don't require ill-formed conversions for a given
  8327. // argument to be better candidates than functions that do.
  8328. unsigned NumArgs = Cand1.Conversions.size();
  8329. assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
  8330. bool HasBetterConversion = false;
  8331. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8332. bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
  8333. bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
  8334. if (Cand1Bad != Cand2Bad) {
  8335. if (Cand1Bad)
  8336. return false;
  8337. HasBetterConversion = true;
  8338. }
  8339. }
  8340. if (HasBetterConversion)
  8341. return true;
  8342. // C++ [over.match.best]p1:
  8343. // A viable function F1 is defined to be a better function than another
  8344. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  8345. // conversion sequence than ICSi(F2), and then...
  8346. bool HasWorseConversion = false;
  8347. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  8348. switch (CompareImplicitConversionSequences(S, Loc,
  8349. Cand1.Conversions[ArgIdx],
  8350. Cand2.Conversions[ArgIdx])) {
  8351. case ImplicitConversionSequence::Better:
  8352. // Cand1 has a better conversion sequence.
  8353. HasBetterConversion = true;
  8354. break;
  8355. case ImplicitConversionSequence::Worse:
  8356. if (Cand1.Function && Cand1.Function == Cand2.Function &&
  8357. (Cand2.RewriteKind & CRK_Reversed) != 0) {
  8358. // Work around large-scale breakage caused by considering reversed
  8359. // forms of operator== in C++20:
  8360. //
  8361. // When comparing a function against its reversed form, if we have a
  8362. // better conversion for one argument and a worse conversion for the
  8363. // other, we prefer the non-reversed form.
  8364. //
  8365. // This prevents a conversion function from being considered ambiguous
  8366. // with its own reversed form in various where it's only incidentally
  8367. // heterogeneous.
  8368. //
  8369. // We diagnose this as an extension from CreateOverloadedBinOp.
  8370. HasWorseConversion = true;
  8371. break;
  8372. }
  8373. // Cand1 can't be better than Cand2.
  8374. return false;
  8375. case ImplicitConversionSequence::Indistinguishable:
  8376. // Do nothing.
  8377. break;
  8378. }
  8379. }
  8380. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  8381. // ICSj(F2), or, if not that,
  8382. if (HasBetterConversion)
  8383. return true;
  8384. if (HasWorseConversion)
  8385. return false;
  8386. // -- the context is an initialization by user-defined conversion
  8387. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  8388. // from the return type of F1 to the destination type (i.e.,
  8389. // the type of the entity being initialized) is a better
  8390. // conversion sequence than the standard conversion sequence
  8391. // from the return type of F2 to the destination type.
  8392. if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
  8393. Cand1.Function && Cand2.Function &&
  8394. isa<CXXConversionDecl>(Cand1.Function) &&
  8395. isa<CXXConversionDecl>(Cand2.Function)) {
  8396. // First check whether we prefer one of the conversion functions over the
  8397. // other. This only distinguishes the results in non-standard, extension
  8398. // cases such as the conversion from a lambda closure type to a function
  8399. // pointer or block.
  8400. ImplicitConversionSequence::CompareKind Result =
  8401. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  8402. if (Result == ImplicitConversionSequence::Indistinguishable)
  8403. Result = CompareStandardConversionSequences(S, Loc,
  8404. Cand1.FinalConversion,
  8405. Cand2.FinalConversion);
  8406. if (Result != ImplicitConversionSequence::Indistinguishable)
  8407. return Result == ImplicitConversionSequence::Better;
  8408. // FIXME: Compare kind of reference binding if conversion functions
  8409. // convert to a reference type used in direct reference binding, per
  8410. // C++14 [over.match.best]p1 section 2 bullet 3.
  8411. }
  8412. // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
  8413. // as combined with the resolution to CWG issue 243.
  8414. //
  8415. // When the context is initialization by constructor ([over.match.ctor] or
  8416. // either phase of [over.match.list]), a constructor is preferred over
  8417. // a conversion function.
  8418. if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
  8419. Cand1.Function && Cand2.Function &&
  8420. isa<CXXConstructorDecl>(Cand1.Function) !=
  8421. isa<CXXConstructorDecl>(Cand2.Function))
  8422. return isa<CXXConstructorDecl>(Cand1.Function);
  8423. // -- F1 is a non-template function and F2 is a function template
  8424. // specialization, or, if not that,
  8425. bool Cand1IsSpecialization = Cand1.Function &&
  8426. Cand1.Function->getPrimaryTemplate();
  8427. bool Cand2IsSpecialization = Cand2.Function &&
  8428. Cand2.Function->getPrimaryTemplate();
  8429. if (Cand1IsSpecialization != Cand2IsSpecialization)
  8430. return Cand2IsSpecialization;
  8431. // -- F1 and F2 are function template specializations, and the function
  8432. // template for F1 is more specialized than the template for F2
  8433. // according to the partial ordering rules described in 14.5.5.2, or,
  8434. // if not that,
  8435. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  8436. if (FunctionTemplateDecl *BetterTemplate
  8437. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  8438. Cand2.Function->getPrimaryTemplate(),
  8439. Loc,
  8440. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  8441. : TPOC_Call,
  8442. Cand1.ExplicitCallArguments,
  8443. Cand2.ExplicitCallArguments))
  8444. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  8445. }
  8446. // -- F1 is a constructor for a class D, F2 is a constructor for a base
  8447. // class B of D, and for all arguments the corresponding parameters of
  8448. // F1 and F2 have the same type.
  8449. // FIXME: Implement the "all parameters have the same type" check.
  8450. bool Cand1IsInherited =
  8451. dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
  8452. bool Cand2IsInherited =
  8453. dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
  8454. if (Cand1IsInherited != Cand2IsInherited)
  8455. return Cand2IsInherited;
  8456. else if (Cand1IsInherited) {
  8457. assert(Cand2IsInherited);
  8458. auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
  8459. auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
  8460. if (Cand1Class->isDerivedFrom(Cand2Class))
  8461. return true;
  8462. if (Cand2Class->isDerivedFrom(Cand1Class))
  8463. return false;
  8464. // Inherited from sibling base classes: still ambiguous.
  8465. }
  8466. // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
  8467. // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
  8468. // with reversed order of parameters and F1 is not
  8469. //
  8470. // We rank reversed + different operator as worse than just reversed, but
  8471. // that comparison can never happen, because we only consider reversing for
  8472. // the maximally-rewritten operator (== or <=>).
  8473. if (Cand1.RewriteKind != Cand2.RewriteKind)
  8474. return Cand1.RewriteKind < Cand2.RewriteKind;
  8475. // Check C++17 tie-breakers for deduction guides.
  8476. {
  8477. auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
  8478. auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
  8479. if (Guide1 && Guide2) {
  8480. // -- F1 is generated from a deduction-guide and F2 is not
  8481. if (Guide1->isImplicit() != Guide2->isImplicit())
  8482. return Guide2->isImplicit();
  8483. // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
  8484. if (Guide1->isCopyDeductionCandidate())
  8485. return true;
  8486. }
  8487. }
  8488. // Check for enable_if value-based overload resolution.
  8489. if (Cand1.Function && Cand2.Function) {
  8490. Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
  8491. if (Cmp != Comparison::Equal)
  8492. return Cmp == Comparison::Better;
  8493. }
  8494. if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
  8495. FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
  8496. return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
  8497. S.IdentifyCUDAPreference(Caller, Cand2.Function);
  8498. }
  8499. bool HasPS1 = Cand1.Function != nullptr &&
  8500. functionHasPassObjectSizeParams(Cand1.Function);
  8501. bool HasPS2 = Cand2.Function != nullptr &&
  8502. functionHasPassObjectSizeParams(Cand2.Function);
  8503. if (HasPS1 != HasPS2 && HasPS1)
  8504. return true;
  8505. return isBetterMultiversionCandidate(Cand1, Cand2);
  8506. }
  8507. /// Determine whether two declarations are "equivalent" for the purposes of
  8508. /// name lookup and overload resolution. This applies when the same internal/no
  8509. /// linkage entity is defined by two modules (probably by textually including
  8510. /// the same header). In such a case, we don't consider the declarations to
  8511. /// declare the same entity, but we also don't want lookups with both
  8512. /// declarations visible to be ambiguous in some cases (this happens when using
  8513. /// a modularized libstdc++).
  8514. bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
  8515. const NamedDecl *B) {
  8516. auto *VA = dyn_cast_or_null<ValueDecl>(A);
  8517. auto *VB = dyn_cast_or_null<ValueDecl>(B);
  8518. if (!VA || !VB)
  8519. return false;
  8520. // The declarations must be declaring the same name as an internal linkage
  8521. // entity in different modules.
  8522. if (!VA->getDeclContext()->getRedeclContext()->Equals(
  8523. VB->getDeclContext()->getRedeclContext()) ||
  8524. getOwningModule(const_cast<ValueDecl *>(VA)) ==
  8525. getOwningModule(const_cast<ValueDecl *>(VB)) ||
  8526. VA->isExternallyVisible() || VB->isExternallyVisible())
  8527. return false;
  8528. // Check that the declarations appear to be equivalent.
  8529. //
  8530. // FIXME: Checking the type isn't really enough to resolve the ambiguity.
  8531. // For constants and functions, we should check the initializer or body is
  8532. // the same. For non-constant variables, we shouldn't allow it at all.
  8533. if (Context.hasSameType(VA->getType(), VB->getType()))
  8534. return true;
  8535. // Enum constants within unnamed enumerations will have different types, but
  8536. // may still be similar enough to be interchangeable for our purposes.
  8537. if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
  8538. if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
  8539. // Only handle anonymous enums. If the enumerations were named and
  8540. // equivalent, they would have been merged to the same type.
  8541. auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
  8542. auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
  8543. if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
  8544. !Context.hasSameType(EnumA->getIntegerType(),
  8545. EnumB->getIntegerType()))
  8546. return false;
  8547. // Allow this only if the value is the same for both enumerators.
  8548. return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
  8549. }
  8550. }
  8551. // Nothing else is sufficiently similar.
  8552. return false;
  8553. }
  8554. void Sema::diagnoseEquivalentInternalLinkageDeclarations(
  8555. SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
  8556. Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
  8557. Module *M = getOwningModule(const_cast<NamedDecl*>(D));
  8558. Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
  8559. << !M << (M ? M->getFullModuleName() : "");
  8560. for (auto *E : Equiv) {
  8561. Module *M = getOwningModule(const_cast<NamedDecl*>(E));
  8562. Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
  8563. << !M << (M ? M->getFullModuleName() : "");
  8564. }
  8565. }
  8566. /// Computes the best viable function (C++ 13.3.3)
  8567. /// within an overload candidate set.
  8568. ///
  8569. /// \param Loc The location of the function name (or operator symbol) for
  8570. /// which overload resolution occurs.
  8571. ///
  8572. /// \param Best If overload resolution was successful or found a deleted
  8573. /// function, \p Best points to the candidate function found.
  8574. ///
  8575. /// \returns The result of overload resolution.
  8576. OverloadingResult
  8577. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  8578. iterator &Best) {
  8579. llvm::SmallVector<OverloadCandidate *, 16> Candidates;
  8580. std::transform(begin(), end(), std::back_inserter(Candidates),
  8581. [](OverloadCandidate &Cand) { return &Cand; });
  8582. // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
  8583. // are accepted by both clang and NVCC. However, during a particular
  8584. // compilation mode only one call variant is viable. We need to
  8585. // exclude non-viable overload candidates from consideration based
  8586. // only on their host/device attributes. Specifically, if one
  8587. // candidate call is WrongSide and the other is SameSide, we ignore
  8588. // the WrongSide candidate.
  8589. if (S.getLangOpts().CUDA) {
  8590. const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
  8591. bool ContainsSameSideCandidate =
  8592. llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
  8593. // Check viable function only.
  8594. return Cand->Viable && Cand->Function &&
  8595. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  8596. Sema::CFP_SameSide;
  8597. });
  8598. if (ContainsSameSideCandidate) {
  8599. auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
  8600. // Check viable function only to avoid unnecessary data copying/moving.
  8601. return Cand->Viable && Cand->Function &&
  8602. S.IdentifyCUDAPreference(Caller, Cand->Function) ==
  8603. Sema::CFP_WrongSide;
  8604. };
  8605. llvm::erase_if(Candidates, IsWrongSideCandidate);
  8606. }
  8607. }
  8608. // Find the best viable function.
  8609. Best = end();
  8610. for (auto *Cand : Candidates)
  8611. if (Cand->Viable)
  8612. if (Best == end() ||
  8613. isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
  8614. Best = Cand;
  8615. // If we didn't find any viable functions, abort.
  8616. if (Best == end())
  8617. return OR_No_Viable_Function;
  8618. llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
  8619. // Make sure that this function is better than every other viable
  8620. // function. If not, we have an ambiguity.
  8621. for (auto *Cand : Candidates) {
  8622. if (Cand->Viable && Cand != Best &&
  8623. !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
  8624. if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
  8625. Cand->Function)) {
  8626. EquivalentCands.push_back(Cand->Function);
  8627. continue;
  8628. }
  8629. Best = end();
  8630. return OR_Ambiguous;
  8631. }
  8632. }
  8633. // Best is the best viable function.
  8634. if (Best->Function && Best->Function->isDeleted())
  8635. return OR_Deleted;
  8636. if (!EquivalentCands.empty())
  8637. S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
  8638. EquivalentCands);
  8639. return OR_Success;
  8640. }
  8641. namespace {
  8642. enum OverloadCandidateKind {
  8643. oc_function,
  8644. oc_method,
  8645. oc_reversed_binary_operator,
  8646. oc_constructor,
  8647. oc_implicit_default_constructor,
  8648. oc_implicit_copy_constructor,
  8649. oc_implicit_move_constructor,
  8650. oc_implicit_copy_assignment,
  8651. oc_implicit_move_assignment,
  8652. oc_inherited_constructor
  8653. };
  8654. enum OverloadCandidateSelect {
  8655. ocs_non_template,
  8656. ocs_template,
  8657. ocs_described_template,
  8658. };
  8659. static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
  8660. ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
  8661. OverloadCandidateRewriteKind CRK,
  8662. std::string &Description) {
  8663. bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
  8664. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  8665. isTemplate = true;
  8666. Description = S.getTemplateArgumentBindingsText(
  8667. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  8668. }
  8669. OverloadCandidateSelect Select = [&]() {
  8670. if (!Description.empty())
  8671. return ocs_described_template;
  8672. return isTemplate ? ocs_template : ocs_non_template;
  8673. }();
  8674. OverloadCandidateKind Kind = [&]() {
  8675. if (CRK & CRK_Reversed)
  8676. return oc_reversed_binary_operator;
  8677. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  8678. if (!Ctor->isImplicit()) {
  8679. if (isa<ConstructorUsingShadowDecl>(Found))
  8680. return oc_inherited_constructor;
  8681. else
  8682. return oc_constructor;
  8683. }
  8684. if (Ctor->isDefaultConstructor())
  8685. return oc_implicit_default_constructor;
  8686. if (Ctor->isMoveConstructor())
  8687. return oc_implicit_move_constructor;
  8688. assert(Ctor->isCopyConstructor() &&
  8689. "unexpected sort of implicit constructor");
  8690. return oc_implicit_copy_constructor;
  8691. }
  8692. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  8693. // This actually gets spelled 'candidate function' for now, but
  8694. // it doesn't hurt to split it out.
  8695. if (!Meth->isImplicit())
  8696. return oc_method;
  8697. if (Meth->isMoveAssignmentOperator())
  8698. return oc_implicit_move_assignment;
  8699. if (Meth->isCopyAssignmentOperator())
  8700. return oc_implicit_copy_assignment;
  8701. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  8702. return oc_method;
  8703. }
  8704. return oc_function;
  8705. }();
  8706. return std::make_pair(Kind, Select);
  8707. }
  8708. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
  8709. // FIXME: It'd be nice to only emit a note once per using-decl per overload
  8710. // set.
  8711. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
  8712. S.Diag(FoundDecl->getLocation(),
  8713. diag::note_ovl_candidate_inherited_constructor)
  8714. << Shadow->getNominatedBaseClass();
  8715. }
  8716. } // end anonymous namespace
  8717. static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
  8718. const FunctionDecl *FD) {
  8719. for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
  8720. bool AlwaysTrue;
  8721. if (EnableIf->getCond()->isValueDependent() ||
  8722. !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
  8723. return false;
  8724. if (!AlwaysTrue)
  8725. return false;
  8726. }
  8727. return true;
  8728. }
  8729. /// Returns true if we can take the address of the function.
  8730. ///
  8731. /// \param Complain - If true, we'll emit a diagnostic
  8732. /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
  8733. /// we in overload resolution?
  8734. /// \param Loc - The location of the statement we're complaining about. Ignored
  8735. /// if we're not complaining, or if we're in overload resolution.
  8736. static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
  8737. bool Complain,
  8738. bool InOverloadResolution,
  8739. SourceLocation Loc) {
  8740. if (!isFunctionAlwaysEnabled(S.Context, FD)) {
  8741. if (Complain) {
  8742. if (InOverloadResolution)
  8743. S.Diag(FD->getBeginLoc(),
  8744. diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
  8745. else
  8746. S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
  8747. }
  8748. return false;
  8749. }
  8750. auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
  8751. return P->hasAttr<PassObjectSizeAttr>();
  8752. });
  8753. if (I == FD->param_end())
  8754. return true;
  8755. if (Complain) {
  8756. // Add one to ParamNo because it's user-facing
  8757. unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
  8758. if (InOverloadResolution)
  8759. S.Diag(FD->getLocation(),
  8760. diag::note_ovl_candidate_has_pass_object_size_params)
  8761. << ParamNo;
  8762. else
  8763. S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
  8764. << FD << ParamNo;
  8765. }
  8766. return false;
  8767. }
  8768. static bool checkAddressOfCandidateIsAvailable(Sema &S,
  8769. const FunctionDecl *FD) {
  8770. return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
  8771. /*InOverloadResolution=*/true,
  8772. /*Loc=*/SourceLocation());
  8773. }
  8774. bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
  8775. bool Complain,
  8776. SourceLocation Loc) {
  8777. return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
  8778. /*InOverloadResolution=*/false,
  8779. Loc);
  8780. }
  8781. // Notes the location of an overload candidate.
  8782. void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
  8783. OverloadCandidateRewriteKind RewriteKind,
  8784. QualType DestType, bool TakingAddress) {
  8785. if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
  8786. return;
  8787. if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
  8788. !Fn->getAttr<TargetAttr>()->isDefaultVersion())
  8789. return;
  8790. std::string FnDesc;
  8791. std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
  8792. ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
  8793. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  8794. << (unsigned)KSPair.first << (unsigned)KSPair.second
  8795. << Fn << FnDesc;
  8796. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  8797. Diag(Fn->getLocation(), PD);
  8798. MaybeEmitInheritedConstructorNote(*this, Found);
  8799. }
  8800. // Notes the location of all overload candidates designated through
  8801. // OverloadedExpr
  8802. void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
  8803. bool TakingAddress) {
  8804. assert(OverloadedExpr->getType() == Context.OverloadTy);
  8805. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  8806. OverloadExpr *OvlExpr = Ovl.Expression;
  8807. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  8808. IEnd = OvlExpr->decls_end();
  8809. I != IEnd; ++I) {
  8810. if (FunctionTemplateDecl *FunTmpl =
  8811. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  8812. NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
  8813. TakingAddress);
  8814. } else if (FunctionDecl *Fun
  8815. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  8816. NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
  8817. }
  8818. }
  8819. }
  8820. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  8821. /// "lead" diagnostic; it will be given two arguments, the source and
  8822. /// target types of the conversion.
  8823. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  8824. Sema &S,
  8825. SourceLocation CaretLoc,
  8826. const PartialDiagnostic &PDiag) const {
  8827. S.Diag(CaretLoc, PDiag)
  8828. << Ambiguous.getFromType() << Ambiguous.getToType();
  8829. // FIXME: The note limiting machinery is borrowed from
  8830. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  8831. // refactoring here.
  8832. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8833. unsigned CandsShown = 0;
  8834. AmbiguousConversionSequence::const_iterator I, E;
  8835. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  8836. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8837. break;
  8838. ++CandsShown;
  8839. S.NoteOverloadCandidate(I->first, I->second);
  8840. }
  8841. if (I != E)
  8842. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  8843. }
  8844. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  8845. unsigned I, bool TakingCandidateAddress) {
  8846. const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  8847. assert(Conv.isBad());
  8848. assert(Cand->Function && "for now, candidate must be a function");
  8849. FunctionDecl *Fn = Cand->Function;
  8850. // There's a conversion slot for the object argument if this is a
  8851. // non-constructor method. Note that 'I' corresponds the
  8852. // conversion-slot index.
  8853. bool isObjectArgument = false;
  8854. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  8855. if (I == 0)
  8856. isObjectArgument = true;
  8857. else
  8858. I--;
  8859. }
  8860. std::string FnDesc;
  8861. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  8862. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind,
  8863. FnDesc);
  8864. Expr *FromExpr = Conv.Bad.FromExpr;
  8865. QualType FromTy = Conv.Bad.getFromType();
  8866. QualType ToTy = Conv.Bad.getToType();
  8867. if (FromTy == S.Context.OverloadTy) {
  8868. assert(FromExpr && "overload set argument came from implicit argument?");
  8869. Expr *E = FromExpr->IgnoreParens();
  8870. if (isa<UnaryOperator>(E))
  8871. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  8872. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  8873. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
  8874. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8875. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
  8876. << Name << I + 1;
  8877. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8878. return;
  8879. }
  8880. // Do some hand-waving analysis to see if the non-viability is due
  8881. // to a qualifier mismatch.
  8882. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  8883. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  8884. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  8885. CToTy = RT->getPointeeType();
  8886. else {
  8887. // TODO: detect and diagnose the full richness of const mismatches.
  8888. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  8889. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
  8890. CFromTy = FromPT->getPointeeType();
  8891. CToTy = ToPT->getPointeeType();
  8892. }
  8893. }
  8894. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  8895. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  8896. Qualifiers FromQs = CFromTy.getQualifiers();
  8897. Qualifiers ToQs = CToTy.getQualifiers();
  8898. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  8899. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
  8900. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8901. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8902. << ToTy << (unsigned)isObjectArgument << I + 1;
  8903. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8904. return;
  8905. }
  8906. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8907. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
  8908. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8909. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8910. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  8911. << (unsigned)isObjectArgument << I + 1;
  8912. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8913. return;
  8914. }
  8915. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  8916. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
  8917. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8918. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8919. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  8920. << (unsigned)isObjectArgument << I + 1;
  8921. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8922. return;
  8923. }
  8924. if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
  8925. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
  8926. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8927. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8928. << FromQs.hasUnaligned() << I + 1;
  8929. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8930. return;
  8931. }
  8932. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  8933. assert(CVR && "unexpected qualifiers mismatch");
  8934. if (isObjectArgument) {
  8935. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
  8936. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8937. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8938. << (CVR - 1);
  8939. } else {
  8940. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
  8941. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8942. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8943. << (CVR - 1) << I + 1;
  8944. }
  8945. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8946. return;
  8947. }
  8948. // Special diagnostic for failure to convert an initializer list, since
  8949. // telling the user that it has type void is not useful.
  8950. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8951. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
  8952. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8953. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8954. << ToTy << (unsigned)isObjectArgument << I + 1;
  8955. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8956. return;
  8957. }
  8958. // Diagnose references or pointers to incomplete types differently,
  8959. // since it's far from impossible that the incompleteness triggered
  8960. // the failure.
  8961. QualType TempFromTy = FromTy.getNonReferenceType();
  8962. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8963. TempFromTy = PTy->getPointeeType();
  8964. if (TempFromTy->isIncompleteType()) {
  8965. // Emit the generic diagnostic and, optionally, add the hints to it.
  8966. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
  8967. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  8968. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  8969. << ToTy << (unsigned)isObjectArgument << I + 1
  8970. << (unsigned)(Cand->Fix.Kind);
  8971. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  8972. return;
  8973. }
  8974. // Diagnose base -> derived pointer conversions.
  8975. unsigned BaseToDerivedConversion = 0;
  8976. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8977. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8978. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8979. FromPtrTy->getPointeeType()) &&
  8980. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8981. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8982. S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
  8983. FromPtrTy->getPointeeType()))
  8984. BaseToDerivedConversion = 1;
  8985. }
  8986. } else if (const ObjCObjectPointerType *FromPtrTy
  8987. = FromTy->getAs<ObjCObjectPointerType>()) {
  8988. if (const ObjCObjectPointerType *ToPtrTy
  8989. = ToTy->getAs<ObjCObjectPointerType>())
  8990. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8991. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8992. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8993. FromPtrTy->getPointeeType()) &&
  8994. FromIface->isSuperClassOf(ToIface))
  8995. BaseToDerivedConversion = 2;
  8996. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  8997. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  8998. !FromTy->isIncompleteType() &&
  8999. !ToRefTy->getPointeeType()->isIncompleteType() &&
  9000. S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
  9001. BaseToDerivedConversion = 3;
  9002. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  9003. ToTy.getNonReferenceType().getCanonicalType() ==
  9004. FromTy.getNonReferenceType().getCanonicalType()) {
  9005. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
  9006. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9007. << (unsigned)isObjectArgument << I + 1
  9008. << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
  9009. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9010. return;
  9011. }
  9012. }
  9013. if (BaseToDerivedConversion) {
  9014. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
  9015. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9016. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9017. << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
  9018. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9019. return;
  9020. }
  9021. if (isa<ObjCObjectPointerType>(CFromTy) &&
  9022. isa<PointerType>(CToTy)) {
  9023. Qualifiers FromQs = CFromTy.getQualifiers();
  9024. Qualifiers ToQs = CToTy.getQualifiers();
  9025. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  9026. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
  9027. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9028. << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  9029. << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
  9030. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9031. return;
  9032. }
  9033. }
  9034. if (TakingCandidateAddress &&
  9035. !checkAddressOfCandidateIsAvailable(S, Cand->Function))
  9036. return;
  9037. // Emit the generic diagnostic and, optionally, add the hints to it.
  9038. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  9039. FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9040. << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
  9041. << ToTy << (unsigned)isObjectArgument << I + 1
  9042. << (unsigned)(Cand->Fix.Kind);
  9043. // If we can fix the conversion, suggest the FixIts.
  9044. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  9045. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  9046. FDiag << *HI;
  9047. S.Diag(Fn->getLocation(), FDiag);
  9048. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9049. }
  9050. /// Additional arity mismatch diagnosis specific to a function overload
  9051. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  9052. /// over a candidate in any candidate set.
  9053. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  9054. unsigned NumArgs) {
  9055. FunctionDecl *Fn = Cand->Function;
  9056. unsigned MinParams = Fn->getMinRequiredArguments();
  9057. // With invalid overloaded operators, it's possible that we think we
  9058. // have an arity mismatch when in fact it looks like we have the
  9059. // right number of arguments, because only overloaded operators have
  9060. // the weird behavior of overloading member and non-member functions.
  9061. // Just don't report anything.
  9062. if (Fn->isInvalidDecl() &&
  9063. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  9064. return true;
  9065. if (NumArgs < MinParams) {
  9066. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  9067. (Cand->FailureKind == ovl_fail_bad_deduction &&
  9068. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  9069. } else {
  9070. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  9071. (Cand->FailureKind == ovl_fail_bad_deduction &&
  9072. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  9073. }
  9074. return false;
  9075. }
  9076. /// General arity mismatch diagnosis over a candidate in a candidate set.
  9077. static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
  9078. unsigned NumFormalArgs) {
  9079. assert(isa<FunctionDecl>(D) &&
  9080. "The templated declaration should at least be a function"
  9081. " when diagnosing bad template argument deduction due to too many"
  9082. " or too few arguments");
  9083. FunctionDecl *Fn = cast<FunctionDecl>(D);
  9084. // TODO: treat calls to a missing default constructor as a special case
  9085. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  9086. unsigned MinParams = Fn->getMinRequiredArguments();
  9087. // at least / at most / exactly
  9088. unsigned mode, modeCount;
  9089. if (NumFormalArgs < MinParams) {
  9090. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  9091. FnTy->isTemplateVariadic())
  9092. mode = 0; // "at least"
  9093. else
  9094. mode = 2; // "exactly"
  9095. modeCount = MinParams;
  9096. } else {
  9097. if (MinParams != FnTy->getNumParams())
  9098. mode = 1; // "at most"
  9099. else
  9100. mode = 2; // "exactly"
  9101. modeCount = FnTy->getNumParams();
  9102. }
  9103. std::string Description;
  9104. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9105. ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
  9106. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  9107. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
  9108. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9109. << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
  9110. else
  9111. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
  9112. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
  9113. << Description << mode << modeCount << NumFormalArgs;
  9114. MaybeEmitInheritedConstructorNote(S, Found);
  9115. }
  9116. /// Arity mismatch diagnosis specific to a function overload candidate.
  9117. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  9118. unsigned NumFormalArgs) {
  9119. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  9120. DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
  9121. }
  9122. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  9123. if (TemplateDecl *TD = Templated->getDescribedTemplate())
  9124. return TD;
  9125. llvm_unreachable("Unsupported: Getting the described template declaration"
  9126. " for bad deduction diagnosis");
  9127. }
  9128. /// Diagnose a failed template-argument deduction.
  9129. static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
  9130. DeductionFailureInfo &DeductionFailure,
  9131. unsigned NumArgs,
  9132. bool TakingCandidateAddress) {
  9133. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  9134. NamedDecl *ParamD;
  9135. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  9136. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  9137. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  9138. switch (DeductionFailure.Result) {
  9139. case Sema::TDK_Success:
  9140. llvm_unreachable("TDK_success while diagnosing bad deduction");
  9141. case Sema::TDK_Incomplete: {
  9142. assert(ParamD && "no parameter found for incomplete deduction result");
  9143. S.Diag(Templated->getLocation(),
  9144. diag::note_ovl_candidate_incomplete_deduction)
  9145. << ParamD->getDeclName();
  9146. MaybeEmitInheritedConstructorNote(S, Found);
  9147. return;
  9148. }
  9149. case Sema::TDK_IncompletePack: {
  9150. assert(ParamD && "no parameter found for incomplete deduction result");
  9151. S.Diag(Templated->getLocation(),
  9152. diag::note_ovl_candidate_incomplete_deduction_pack)
  9153. << ParamD->getDeclName()
  9154. << (DeductionFailure.getFirstArg()->pack_size() + 1)
  9155. << *DeductionFailure.getFirstArg();
  9156. MaybeEmitInheritedConstructorNote(S, Found);
  9157. return;
  9158. }
  9159. case Sema::TDK_Underqualified: {
  9160. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  9161. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  9162. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  9163. // Param will have been canonicalized, but it should just be a
  9164. // qualified version of ParamD, so move the qualifiers to that.
  9165. QualifierCollector Qs;
  9166. Qs.strip(Param);
  9167. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  9168. assert(S.Context.hasSameType(Param, NonCanonParam));
  9169. // Arg has also been canonicalized, but there's nothing we can do
  9170. // about that. It also doesn't matter as much, because it won't
  9171. // have any template parameters in it (because deduction isn't
  9172. // done on dependent types).
  9173. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  9174. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  9175. << ParamD->getDeclName() << Arg << NonCanonParam;
  9176. MaybeEmitInheritedConstructorNote(S, Found);
  9177. return;
  9178. }
  9179. case Sema::TDK_Inconsistent: {
  9180. assert(ParamD && "no parameter found for inconsistent deduction result");
  9181. int which = 0;
  9182. if (isa<TemplateTypeParmDecl>(ParamD))
  9183. which = 0;
  9184. else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
  9185. // Deduction might have failed because we deduced arguments of two
  9186. // different types for a non-type template parameter.
  9187. // FIXME: Use a different TDK value for this.
  9188. QualType T1 =
  9189. DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
  9190. QualType T2 =
  9191. DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
  9192. if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
  9193. S.Diag(Templated->getLocation(),
  9194. diag::note_ovl_candidate_inconsistent_deduction_types)
  9195. << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
  9196. << *DeductionFailure.getSecondArg() << T2;
  9197. MaybeEmitInheritedConstructorNote(S, Found);
  9198. return;
  9199. }
  9200. which = 1;
  9201. } else {
  9202. which = 2;
  9203. }
  9204. S.Diag(Templated->getLocation(),
  9205. diag::note_ovl_candidate_inconsistent_deduction)
  9206. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  9207. << *DeductionFailure.getSecondArg();
  9208. MaybeEmitInheritedConstructorNote(S, Found);
  9209. return;
  9210. }
  9211. case Sema::TDK_InvalidExplicitArguments:
  9212. assert(ParamD && "no parameter found for invalid explicit arguments");
  9213. if (ParamD->getDeclName())
  9214. S.Diag(Templated->getLocation(),
  9215. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  9216. << ParamD->getDeclName();
  9217. else {
  9218. int index = 0;
  9219. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  9220. index = TTP->getIndex();
  9221. else if (NonTypeTemplateParmDecl *NTTP
  9222. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  9223. index = NTTP->getIndex();
  9224. else
  9225. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  9226. S.Diag(Templated->getLocation(),
  9227. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  9228. << (index + 1);
  9229. }
  9230. MaybeEmitInheritedConstructorNote(S, Found);
  9231. return;
  9232. case Sema::TDK_TooManyArguments:
  9233. case Sema::TDK_TooFewArguments:
  9234. DiagnoseArityMismatch(S, Found, Templated, NumArgs);
  9235. return;
  9236. case Sema::TDK_InstantiationDepth:
  9237. S.Diag(Templated->getLocation(),
  9238. diag::note_ovl_candidate_instantiation_depth);
  9239. MaybeEmitInheritedConstructorNote(S, Found);
  9240. return;
  9241. case Sema::TDK_SubstitutionFailure: {
  9242. // Format the template argument list into the argument string.
  9243. SmallString<128> TemplateArgString;
  9244. if (TemplateArgumentList *Args =
  9245. DeductionFailure.getTemplateArgumentList()) {
  9246. TemplateArgString = " ";
  9247. TemplateArgString += S.getTemplateArgumentBindingsText(
  9248. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9249. }
  9250. // If this candidate was disabled by enable_if, say so.
  9251. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  9252. if (PDiag && PDiag->second.getDiagID() ==
  9253. diag::err_typename_nested_not_found_enable_if) {
  9254. // FIXME: Use the source range of the condition, and the fully-qualified
  9255. // name of the enable_if template. These are both present in PDiag.
  9256. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  9257. << "'enable_if'" << TemplateArgString;
  9258. return;
  9259. }
  9260. // We found a specific requirement that disabled the enable_if.
  9261. if (PDiag && PDiag->second.getDiagID() ==
  9262. diag::err_typename_nested_not_found_requirement) {
  9263. S.Diag(Templated->getLocation(),
  9264. diag::note_ovl_candidate_disabled_by_requirement)
  9265. << PDiag->second.getStringArg(0) << TemplateArgString;
  9266. return;
  9267. }
  9268. // Format the SFINAE diagnostic into the argument string.
  9269. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  9270. // formatted message in another diagnostic.
  9271. SmallString<128> SFINAEArgString;
  9272. SourceRange R;
  9273. if (PDiag) {
  9274. SFINAEArgString = ": ";
  9275. R = SourceRange(PDiag->first, PDiag->first);
  9276. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  9277. }
  9278. S.Diag(Templated->getLocation(),
  9279. diag::note_ovl_candidate_substitution_failure)
  9280. << TemplateArgString << SFINAEArgString << R;
  9281. MaybeEmitInheritedConstructorNote(S, Found);
  9282. return;
  9283. }
  9284. case Sema::TDK_DeducedMismatch:
  9285. case Sema::TDK_DeducedMismatchNested: {
  9286. // Format the template argument list into the argument string.
  9287. SmallString<128> TemplateArgString;
  9288. if (TemplateArgumentList *Args =
  9289. DeductionFailure.getTemplateArgumentList()) {
  9290. TemplateArgString = " ";
  9291. TemplateArgString += S.getTemplateArgumentBindingsText(
  9292. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  9293. }
  9294. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
  9295. << (*DeductionFailure.getCallArgIndex() + 1)
  9296. << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
  9297. << TemplateArgString
  9298. << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
  9299. break;
  9300. }
  9301. case Sema::TDK_NonDeducedMismatch: {
  9302. // FIXME: Provide a source location to indicate what we couldn't match.
  9303. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  9304. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  9305. if (FirstTA.getKind() == TemplateArgument::Template &&
  9306. SecondTA.getKind() == TemplateArgument::Template) {
  9307. TemplateName FirstTN = FirstTA.getAsTemplate();
  9308. TemplateName SecondTN = SecondTA.getAsTemplate();
  9309. if (FirstTN.getKind() == TemplateName::Template &&
  9310. SecondTN.getKind() == TemplateName::Template) {
  9311. if (FirstTN.getAsTemplateDecl()->getName() ==
  9312. SecondTN.getAsTemplateDecl()->getName()) {
  9313. // FIXME: This fixes a bad diagnostic where both templates are named
  9314. // the same. This particular case is a bit difficult since:
  9315. // 1) It is passed as a string to the diagnostic printer.
  9316. // 2) The diagnostic printer only attempts to find a better
  9317. // name for types, not decls.
  9318. // Ideally, this should folded into the diagnostic printer.
  9319. S.Diag(Templated->getLocation(),
  9320. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  9321. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  9322. return;
  9323. }
  9324. }
  9325. }
  9326. if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
  9327. !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
  9328. return;
  9329. // FIXME: For generic lambda parameters, check if the function is a lambda
  9330. // call operator, and if so, emit a prettier and more informative
  9331. // diagnostic that mentions 'auto' and lambda in addition to
  9332. // (or instead of?) the canonical template type parameters.
  9333. S.Diag(Templated->getLocation(),
  9334. diag::note_ovl_candidate_non_deduced_mismatch)
  9335. << FirstTA << SecondTA;
  9336. return;
  9337. }
  9338. // TODO: diagnose these individually, then kill off
  9339. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  9340. case Sema::TDK_MiscellaneousDeductionFailure:
  9341. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  9342. MaybeEmitInheritedConstructorNote(S, Found);
  9343. return;
  9344. case Sema::TDK_CUDATargetMismatch:
  9345. S.Diag(Templated->getLocation(),
  9346. diag::note_cuda_ovl_candidate_target_mismatch);
  9347. return;
  9348. }
  9349. }
  9350. /// Diagnose a failed template-argument deduction, for function calls.
  9351. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  9352. unsigned NumArgs,
  9353. bool TakingCandidateAddress) {
  9354. unsigned TDK = Cand->DeductionFailure.Result;
  9355. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  9356. if (CheckArityMismatch(S, Cand, NumArgs))
  9357. return;
  9358. }
  9359. DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
  9360. Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
  9361. }
  9362. /// CUDA: diagnose an invalid call across targets.
  9363. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  9364. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  9365. FunctionDecl *Callee = Cand->Function;
  9366. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  9367. CalleeTarget = S.IdentifyCUDATarget(Callee);
  9368. std::string FnDesc;
  9369. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9370. ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, Cand->RewriteKind,
  9371. FnDesc);
  9372. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  9373. << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
  9374. << FnDesc /* Ignored */
  9375. << CalleeTarget << CallerTarget;
  9376. // This could be an implicit constructor for which we could not infer the
  9377. // target due to a collsion. Diagnose that case.
  9378. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  9379. if (Meth != nullptr && Meth->isImplicit()) {
  9380. CXXRecordDecl *ParentClass = Meth->getParent();
  9381. Sema::CXXSpecialMember CSM;
  9382. switch (FnKindPair.first) {
  9383. default:
  9384. return;
  9385. case oc_implicit_default_constructor:
  9386. CSM = Sema::CXXDefaultConstructor;
  9387. break;
  9388. case oc_implicit_copy_constructor:
  9389. CSM = Sema::CXXCopyConstructor;
  9390. break;
  9391. case oc_implicit_move_constructor:
  9392. CSM = Sema::CXXMoveConstructor;
  9393. break;
  9394. case oc_implicit_copy_assignment:
  9395. CSM = Sema::CXXCopyAssignment;
  9396. break;
  9397. case oc_implicit_move_assignment:
  9398. CSM = Sema::CXXMoveAssignment;
  9399. break;
  9400. };
  9401. bool ConstRHS = false;
  9402. if (Meth->getNumParams()) {
  9403. if (const ReferenceType *RT =
  9404. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  9405. ConstRHS = RT->getPointeeType().isConstQualified();
  9406. }
  9407. }
  9408. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  9409. /* ConstRHS */ ConstRHS,
  9410. /* Diagnose */ true);
  9411. }
  9412. }
  9413. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  9414. FunctionDecl *Callee = Cand->Function;
  9415. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  9416. S.Diag(Callee->getLocation(),
  9417. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  9418. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  9419. }
  9420. static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
  9421. ExplicitSpecifier ES;
  9422. const char *DeclName;
  9423. switch (Cand->Function->getDeclKind()) {
  9424. case Decl::Kind::CXXConstructor:
  9425. ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
  9426. DeclName = "constructor";
  9427. break;
  9428. case Decl::Kind::CXXConversion:
  9429. ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
  9430. DeclName = "conversion operator";
  9431. break;
  9432. case Decl::Kind::CXXDeductionGuide:
  9433. ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
  9434. DeclName = "deductiong guide";
  9435. break;
  9436. default:
  9437. llvm_unreachable("invalid Decl");
  9438. }
  9439. assert(ES.getExpr() && "null expression should be handled before");
  9440. S.Diag(Cand->Function->getLocation(),
  9441. diag::note_ovl_candidate_explicit_forbidden)
  9442. << DeclName;
  9443. S.Diag(ES.getExpr()->getBeginLoc(),
  9444. diag::note_explicit_bool_resolved_to_true);
  9445. }
  9446. static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
  9447. FunctionDecl *Callee = Cand->Function;
  9448. S.Diag(Callee->getLocation(),
  9449. diag::note_ovl_candidate_disabled_by_extension)
  9450. << S.getOpenCLExtensionsFromDeclExtMap(Callee);
  9451. }
  9452. /// Generates a 'note' diagnostic for an overload candidate. We've
  9453. /// already generated a primary error at the call site.
  9454. ///
  9455. /// It really does need to be a single diagnostic with its caret
  9456. /// pointed at the candidate declaration. Yes, this creates some
  9457. /// major challenges of technical writing. Yes, this makes pointing
  9458. /// out problems with specific arguments quite awkward. It's still
  9459. /// better than generating twenty screens of text for every failed
  9460. /// overload.
  9461. ///
  9462. /// It would be great to be able to express per-candidate problems
  9463. /// more richly for those diagnostic clients that cared, but we'd
  9464. /// still have to be just as careful with the default diagnostics.
  9465. /// \param CtorDestAS Addr space of object being constructed (for ctor
  9466. /// candidates only).
  9467. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  9468. unsigned NumArgs,
  9469. bool TakingCandidateAddress,
  9470. LangAS CtorDestAS = LangAS::Default) {
  9471. FunctionDecl *Fn = Cand->Function;
  9472. // Note deleted candidates, but only if they're viable.
  9473. if (Cand->Viable) {
  9474. if (Fn->isDeleted()) {
  9475. std::string FnDesc;
  9476. std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
  9477. ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind,
  9478. FnDesc);
  9479. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  9480. << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
  9481. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  9482. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9483. return;
  9484. }
  9485. // We don't really have anything else to say about viable candidates.
  9486. S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind);
  9487. return;
  9488. }
  9489. switch (Cand->FailureKind) {
  9490. case ovl_fail_too_many_arguments:
  9491. case ovl_fail_too_few_arguments:
  9492. return DiagnoseArityMismatch(S, Cand, NumArgs);
  9493. case ovl_fail_bad_deduction:
  9494. return DiagnoseBadDeduction(S, Cand, NumArgs,
  9495. TakingCandidateAddress);
  9496. case ovl_fail_illegal_constructor: {
  9497. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  9498. << (Fn->getPrimaryTemplate() ? 1 : 0);
  9499. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9500. return;
  9501. }
  9502. case ovl_fail_object_addrspace_mismatch: {
  9503. Qualifiers QualsForPrinting;
  9504. QualsForPrinting.setAddressSpace(CtorDestAS);
  9505. S.Diag(Fn->getLocation(),
  9506. diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
  9507. << QualsForPrinting;
  9508. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9509. return;
  9510. }
  9511. case ovl_fail_trivial_conversion:
  9512. case ovl_fail_bad_final_conversion:
  9513. case ovl_fail_final_conversion_not_exact:
  9514. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind);
  9515. case ovl_fail_bad_conversion: {
  9516. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  9517. for (unsigned N = Cand->Conversions.size(); I != N; ++I)
  9518. if (Cand->Conversions[I].isBad())
  9519. return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
  9520. // FIXME: this currently happens when we're called from SemaInit
  9521. // when user-conversion overload fails. Figure out how to handle
  9522. // those conditions and diagnose them well.
  9523. return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind);
  9524. }
  9525. case ovl_fail_bad_target:
  9526. return DiagnoseBadTarget(S, Cand);
  9527. case ovl_fail_enable_if:
  9528. return DiagnoseFailedEnableIfAttr(S, Cand);
  9529. case ovl_fail_explicit_resolved:
  9530. return DiagnoseFailedExplicitSpec(S, Cand);
  9531. case ovl_fail_ext_disabled:
  9532. return DiagnoseOpenCLExtensionDisabled(S, Cand);
  9533. case ovl_fail_inhctor_slice:
  9534. // It's generally not interesting to note copy/move constructors here.
  9535. if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
  9536. return;
  9537. S.Diag(Fn->getLocation(),
  9538. diag::note_ovl_candidate_inherited_constructor_slice)
  9539. << (Fn->getPrimaryTemplate() ? 1 : 0)
  9540. << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
  9541. MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
  9542. return;
  9543. case ovl_fail_addr_not_available: {
  9544. bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
  9545. (void)Available;
  9546. assert(!Available);
  9547. break;
  9548. }
  9549. case ovl_non_default_multiversion_function:
  9550. // Do nothing, these should simply be ignored.
  9551. break;
  9552. }
  9553. }
  9554. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  9555. // Desugar the type of the surrogate down to a function type,
  9556. // retaining as many typedefs as possible while still showing
  9557. // the function type (and, therefore, its parameter types).
  9558. QualType FnType = Cand->Surrogate->getConversionType();
  9559. bool isLValueReference = false;
  9560. bool isRValueReference = false;
  9561. bool isPointer = false;
  9562. if (const LValueReferenceType *FnTypeRef =
  9563. FnType->getAs<LValueReferenceType>()) {
  9564. FnType = FnTypeRef->getPointeeType();
  9565. isLValueReference = true;
  9566. } else if (const RValueReferenceType *FnTypeRef =
  9567. FnType->getAs<RValueReferenceType>()) {
  9568. FnType = FnTypeRef->getPointeeType();
  9569. isRValueReference = true;
  9570. }
  9571. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  9572. FnType = FnTypePtr->getPointeeType();
  9573. isPointer = true;
  9574. }
  9575. // Desugar down to a function type.
  9576. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  9577. // Reconstruct the pointer/reference as appropriate.
  9578. if (isPointer) FnType = S.Context.getPointerType(FnType);
  9579. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  9580. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  9581. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  9582. << FnType;
  9583. }
  9584. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  9585. SourceLocation OpLoc,
  9586. OverloadCandidate *Cand) {
  9587. assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
  9588. std::string TypeStr("operator");
  9589. TypeStr += Opc;
  9590. TypeStr += "(";
  9591. TypeStr += Cand->BuiltinParamTypes[0].getAsString();
  9592. if (Cand->Conversions.size() == 1) {
  9593. TypeStr += ")";
  9594. S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
  9595. } else {
  9596. TypeStr += ", ";
  9597. TypeStr += Cand->BuiltinParamTypes[1].getAsString();
  9598. TypeStr += ")";
  9599. S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
  9600. }
  9601. }
  9602. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  9603. OverloadCandidate *Cand) {
  9604. for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
  9605. if (ICS.isBad()) break; // all meaningless after first invalid
  9606. if (!ICS.isAmbiguous()) continue;
  9607. ICS.DiagnoseAmbiguousConversion(
  9608. S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
  9609. }
  9610. }
  9611. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  9612. if (Cand->Function)
  9613. return Cand->Function->getLocation();
  9614. if (Cand->IsSurrogate)
  9615. return Cand->Surrogate->getLocation();
  9616. return SourceLocation();
  9617. }
  9618. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  9619. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  9620. case Sema::TDK_Success:
  9621. case Sema::TDK_NonDependentConversionFailure:
  9622. llvm_unreachable("non-deduction failure while diagnosing bad deduction");
  9623. case Sema::TDK_Invalid:
  9624. case Sema::TDK_Incomplete:
  9625. case Sema::TDK_IncompletePack:
  9626. return 1;
  9627. case Sema::TDK_Underqualified:
  9628. case Sema::TDK_Inconsistent:
  9629. return 2;
  9630. case Sema::TDK_SubstitutionFailure:
  9631. case Sema::TDK_DeducedMismatch:
  9632. case Sema::TDK_DeducedMismatchNested:
  9633. case Sema::TDK_NonDeducedMismatch:
  9634. case Sema::TDK_MiscellaneousDeductionFailure:
  9635. case Sema::TDK_CUDATargetMismatch:
  9636. return 3;
  9637. case Sema::TDK_InstantiationDepth:
  9638. return 4;
  9639. case Sema::TDK_InvalidExplicitArguments:
  9640. return 5;
  9641. case Sema::TDK_TooManyArguments:
  9642. case Sema::TDK_TooFewArguments:
  9643. return 6;
  9644. }
  9645. llvm_unreachable("Unhandled deduction result");
  9646. }
  9647. namespace {
  9648. struct CompareOverloadCandidatesForDisplay {
  9649. Sema &S;
  9650. SourceLocation Loc;
  9651. size_t NumArgs;
  9652. OverloadCandidateSet::CandidateSetKind CSK;
  9653. CompareOverloadCandidatesForDisplay(
  9654. Sema &S, SourceLocation Loc, size_t NArgs,
  9655. OverloadCandidateSet::CandidateSetKind CSK)
  9656. : S(S), NumArgs(NArgs), CSK(CSK) {}
  9657. bool operator()(const OverloadCandidate *L,
  9658. const OverloadCandidate *R) {
  9659. // Fast-path this check.
  9660. if (L == R) return false;
  9661. // Order first by viability.
  9662. if (L->Viable) {
  9663. if (!R->Viable) return true;
  9664. // TODO: introduce a tri-valued comparison for overload
  9665. // candidates. Would be more worthwhile if we had a sort
  9666. // that could exploit it.
  9667. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
  9668. return true;
  9669. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
  9670. return false;
  9671. } else if (R->Viable)
  9672. return false;
  9673. assert(L->Viable == R->Viable);
  9674. // Criteria by which we can sort non-viable candidates:
  9675. if (!L->Viable) {
  9676. // 1. Arity mismatches come after other candidates.
  9677. if (L->FailureKind == ovl_fail_too_many_arguments ||
  9678. L->FailureKind == ovl_fail_too_few_arguments) {
  9679. if (R->FailureKind == ovl_fail_too_many_arguments ||
  9680. R->FailureKind == ovl_fail_too_few_arguments) {
  9681. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  9682. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  9683. if (LDist == RDist) {
  9684. if (L->FailureKind == R->FailureKind)
  9685. // Sort non-surrogates before surrogates.
  9686. return !L->IsSurrogate && R->IsSurrogate;
  9687. // Sort candidates requiring fewer parameters than there were
  9688. // arguments given after candidates requiring more parameters
  9689. // than there were arguments given.
  9690. return L->FailureKind == ovl_fail_too_many_arguments;
  9691. }
  9692. return LDist < RDist;
  9693. }
  9694. return false;
  9695. }
  9696. if (R->FailureKind == ovl_fail_too_many_arguments ||
  9697. R->FailureKind == ovl_fail_too_few_arguments)
  9698. return true;
  9699. // 2. Bad conversions come first and are ordered by the number
  9700. // of bad conversions and quality of good conversions.
  9701. if (L->FailureKind == ovl_fail_bad_conversion) {
  9702. if (R->FailureKind != ovl_fail_bad_conversion)
  9703. return true;
  9704. // The conversion that can be fixed with a smaller number of changes,
  9705. // comes first.
  9706. unsigned numLFixes = L->Fix.NumConversionsFixed;
  9707. unsigned numRFixes = R->Fix.NumConversionsFixed;
  9708. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  9709. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  9710. if (numLFixes != numRFixes) {
  9711. return numLFixes < numRFixes;
  9712. }
  9713. // If there's any ordering between the defined conversions...
  9714. // FIXME: this might not be transitive.
  9715. assert(L->Conversions.size() == R->Conversions.size());
  9716. int leftBetter = 0;
  9717. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  9718. for (unsigned E = L->Conversions.size(); I != E; ++I) {
  9719. switch (CompareImplicitConversionSequences(S, Loc,
  9720. L->Conversions[I],
  9721. R->Conversions[I])) {
  9722. case ImplicitConversionSequence::Better:
  9723. leftBetter++;
  9724. break;
  9725. case ImplicitConversionSequence::Worse:
  9726. leftBetter--;
  9727. break;
  9728. case ImplicitConversionSequence::Indistinguishable:
  9729. break;
  9730. }
  9731. }
  9732. if (leftBetter > 0) return true;
  9733. if (leftBetter < 0) return false;
  9734. } else if (R->FailureKind == ovl_fail_bad_conversion)
  9735. return false;
  9736. if (L->FailureKind == ovl_fail_bad_deduction) {
  9737. if (R->FailureKind != ovl_fail_bad_deduction)
  9738. return true;
  9739. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  9740. return RankDeductionFailure(L->DeductionFailure)
  9741. < RankDeductionFailure(R->DeductionFailure);
  9742. } else if (R->FailureKind == ovl_fail_bad_deduction)
  9743. return false;
  9744. // TODO: others?
  9745. }
  9746. // Sort everything else by location.
  9747. SourceLocation LLoc = GetLocationForCandidate(L);
  9748. SourceLocation RLoc = GetLocationForCandidate(R);
  9749. // Put candidates without locations (e.g. builtins) at the end.
  9750. if (LLoc.isInvalid()) return false;
  9751. if (RLoc.isInvalid()) return true;
  9752. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  9753. }
  9754. };
  9755. }
  9756. /// CompleteNonViableCandidate - Normally, overload resolution only
  9757. /// computes up to the first bad conversion. Produces the FixIt set if
  9758. /// possible.
  9759. static void
  9760. CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  9761. ArrayRef<Expr *> Args,
  9762. OverloadCandidateSet::CandidateSetKind CSK) {
  9763. assert(!Cand->Viable);
  9764. // Don't do anything on failures other than bad conversion.
  9765. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  9766. // We only want the FixIts if all the arguments can be corrected.
  9767. bool Unfixable = false;
  9768. // Use a implicit copy initialization to check conversion fixes.
  9769. Cand->Fix.setConversionChecker(TryCopyInitialization);
  9770. // Attempt to fix the bad conversion.
  9771. unsigned ConvCount = Cand->Conversions.size();
  9772. for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
  9773. ++ConvIdx) {
  9774. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  9775. if (Cand->Conversions[ConvIdx].isInitialized() &&
  9776. Cand->Conversions[ConvIdx].isBad()) {
  9777. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  9778. break;
  9779. }
  9780. }
  9781. // FIXME: this should probably be preserved from the overload
  9782. // operation somehow.
  9783. bool SuppressUserConversions = false;
  9784. unsigned ConvIdx = 0;
  9785. unsigned ArgIdx = 0;
  9786. ArrayRef<QualType> ParamTypes;
  9787. if (Cand->IsSurrogate) {
  9788. QualType ConvType
  9789. = Cand->Surrogate->getConversionType().getNonReferenceType();
  9790. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  9791. ConvType = ConvPtrType->getPointeeType();
  9792. ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
  9793. // Conversion 0 is 'this', which doesn't have a corresponding parameter.
  9794. ConvIdx = 1;
  9795. } else if (Cand->Function) {
  9796. ParamTypes =
  9797. Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
  9798. if (isa<CXXMethodDecl>(Cand->Function) &&
  9799. !isa<CXXConstructorDecl>(Cand->Function)) {
  9800. // Conversion 0 is 'this', which doesn't have a corresponding parameter.
  9801. ConvIdx = 1;
  9802. if (CSK == OverloadCandidateSet::CSK_Operator)
  9803. // Argument 0 is 'this', which doesn't have a corresponding parameter.
  9804. ArgIdx = 1;
  9805. }
  9806. } else {
  9807. // Builtin operator.
  9808. assert(ConvCount <= 3);
  9809. ParamTypes = Cand->BuiltinParamTypes;
  9810. }
  9811. // Fill in the rest of the conversions.
  9812. bool Reversed = Cand->RewriteKind & CRK_Reversed;
  9813. for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
  9814. ConvIdx != ConvCount;
  9815. ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
  9816. if (Cand->Conversions[ConvIdx].isInitialized()) {
  9817. // We've already checked this conversion.
  9818. } else if (ArgIdx < ParamTypes.size()) {
  9819. if (ParamTypes[ParamIdx]->isDependentType())
  9820. Cand->Conversions[ConvIdx].setAsIdentityConversion(
  9821. Args[ArgIdx]->getType());
  9822. else {
  9823. Cand->Conversions[ConvIdx] =
  9824. TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
  9825. SuppressUserConversions,
  9826. /*InOverloadResolution=*/true,
  9827. /*AllowObjCWritebackConversion=*/
  9828. S.getLangOpts().ObjCAutoRefCount);
  9829. // Store the FixIt in the candidate if it exists.
  9830. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  9831. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  9832. }
  9833. } else
  9834. Cand->Conversions[ConvIdx].setEllipsis();
  9835. }
  9836. }
  9837. SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
  9838. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  9839. SourceLocation OpLoc,
  9840. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  9841. // Sort the candidates by viability and position. Sorting directly would
  9842. // be prohibitive, so we make a set of pointers and sort those.
  9843. SmallVector<OverloadCandidate*, 32> Cands;
  9844. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  9845. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  9846. if (!Filter(*Cand))
  9847. continue;
  9848. if (Cand->Viable)
  9849. Cands.push_back(Cand);
  9850. else if (OCD == OCD_AllCandidates) {
  9851. CompleteNonViableCandidate(S, Cand, Args, Kind);
  9852. if (Cand->Function || Cand->IsSurrogate)
  9853. Cands.push_back(Cand);
  9854. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  9855. // want to list every possible builtin candidate.
  9856. }
  9857. }
  9858. llvm::stable_sort(
  9859. Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
  9860. return Cands;
  9861. }
  9862. /// When overload resolution fails, prints diagnostic messages containing the
  9863. /// candidates in the candidate set.
  9864. void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
  9865. Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
  9866. StringRef Opc, SourceLocation OpLoc,
  9867. llvm::function_ref<bool(OverloadCandidate &)> Filter) {
  9868. auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
  9869. S.Diag(PD.first, PD.second);
  9870. NoteCandidates(S, Args, Cands, Opc, OpLoc);
  9871. }
  9872. void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
  9873. ArrayRef<OverloadCandidate *> Cands,
  9874. StringRef Opc, SourceLocation OpLoc) {
  9875. bool ReportedAmbiguousConversions = false;
  9876. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  9877. unsigned CandsShown = 0;
  9878. auto I = Cands.begin(), E = Cands.end();
  9879. for (; I != E; ++I) {
  9880. OverloadCandidate *Cand = *I;
  9881. // Set an arbitrary limit on the number of candidate functions we'll spam
  9882. // the user with. FIXME: This limit should depend on details of the
  9883. // candidate list.
  9884. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  9885. break;
  9886. }
  9887. ++CandsShown;
  9888. if (Cand->Function)
  9889. NoteFunctionCandidate(S, Cand, Args.size(),
  9890. /*TakingCandidateAddress=*/false, DestAS);
  9891. else if (Cand->IsSurrogate)
  9892. NoteSurrogateCandidate(S, Cand);
  9893. else {
  9894. assert(Cand->Viable &&
  9895. "Non-viable built-in candidates are not added to Cands.");
  9896. // Generally we only see ambiguities including viable builtin
  9897. // operators if overload resolution got screwed up by an
  9898. // ambiguous user-defined conversion.
  9899. //
  9900. // FIXME: It's quite possible for different conversions to see
  9901. // different ambiguities, though.
  9902. if (!ReportedAmbiguousConversions) {
  9903. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  9904. ReportedAmbiguousConversions = true;
  9905. }
  9906. // If this is a viable builtin, print it.
  9907. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  9908. }
  9909. }
  9910. if (I != E)
  9911. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  9912. }
  9913. static SourceLocation
  9914. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  9915. return Cand->Specialization ? Cand->Specialization->getLocation()
  9916. : SourceLocation();
  9917. }
  9918. namespace {
  9919. struct CompareTemplateSpecCandidatesForDisplay {
  9920. Sema &S;
  9921. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  9922. bool operator()(const TemplateSpecCandidate *L,
  9923. const TemplateSpecCandidate *R) {
  9924. // Fast-path this check.
  9925. if (L == R)
  9926. return false;
  9927. // Assuming that both candidates are not matches...
  9928. // Sort by the ranking of deduction failures.
  9929. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  9930. return RankDeductionFailure(L->DeductionFailure) <
  9931. RankDeductionFailure(R->DeductionFailure);
  9932. // Sort everything else by location.
  9933. SourceLocation LLoc = GetLocationForCandidate(L);
  9934. SourceLocation RLoc = GetLocationForCandidate(R);
  9935. // Put candidates without locations (e.g. builtins) at the end.
  9936. if (LLoc.isInvalid())
  9937. return false;
  9938. if (RLoc.isInvalid())
  9939. return true;
  9940. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  9941. }
  9942. };
  9943. }
  9944. /// Diagnose a template argument deduction failure.
  9945. /// We are treating these failures as overload failures due to bad
  9946. /// deductions.
  9947. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
  9948. bool ForTakingAddress) {
  9949. DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
  9950. DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
  9951. }
  9952. void TemplateSpecCandidateSet::destroyCandidates() {
  9953. for (iterator i = begin(), e = end(); i != e; ++i) {
  9954. i->DeductionFailure.Destroy();
  9955. }
  9956. }
  9957. void TemplateSpecCandidateSet::clear() {
  9958. destroyCandidates();
  9959. Candidates.clear();
  9960. }
  9961. /// NoteCandidates - When no template specialization match is found, prints
  9962. /// diagnostic messages containing the non-matching specializations that form
  9963. /// the candidate set.
  9964. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  9965. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  9966. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  9967. // Sort the candidates by position (assuming no candidate is a match).
  9968. // Sorting directly would be prohibitive, so we make a set of pointers
  9969. // and sort those.
  9970. SmallVector<TemplateSpecCandidate *, 32> Cands;
  9971. Cands.reserve(size());
  9972. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  9973. if (Cand->Specialization)
  9974. Cands.push_back(Cand);
  9975. // Otherwise, this is a non-matching builtin candidate. We do not,
  9976. // in general, want to list every possible builtin candidate.
  9977. }
  9978. llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
  9979. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  9980. // for generalization purposes (?).
  9981. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  9982. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  9983. unsigned CandsShown = 0;
  9984. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  9985. TemplateSpecCandidate *Cand = *I;
  9986. // Set an arbitrary limit on the number of candidates we'll spam
  9987. // the user with. FIXME: This limit should depend on details of the
  9988. // candidate list.
  9989. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  9990. break;
  9991. ++CandsShown;
  9992. assert(Cand->Specialization &&
  9993. "Non-matching built-in candidates are not added to Cands.");
  9994. Cand->NoteDeductionFailure(S, ForTakingAddress);
  9995. }
  9996. if (I != E)
  9997. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  9998. }
  9999. // [PossiblyAFunctionType] --> [Return]
  10000. // NonFunctionType --> NonFunctionType
  10001. // R (A) --> R(A)
  10002. // R (*)(A) --> R (A)
  10003. // R (&)(A) --> R (A)
  10004. // R (S::*)(A) --> R (A)
  10005. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  10006. QualType Ret = PossiblyAFunctionType;
  10007. if (const PointerType *ToTypePtr =
  10008. PossiblyAFunctionType->getAs<PointerType>())
  10009. Ret = ToTypePtr->getPointeeType();
  10010. else if (const ReferenceType *ToTypeRef =
  10011. PossiblyAFunctionType->getAs<ReferenceType>())
  10012. Ret = ToTypeRef->getPointeeType();
  10013. else if (const MemberPointerType *MemTypePtr =
  10014. PossiblyAFunctionType->getAs<MemberPointerType>())
  10015. Ret = MemTypePtr->getPointeeType();
  10016. Ret =
  10017. Context.getCanonicalType(Ret).getUnqualifiedType();
  10018. return Ret;
  10019. }
  10020. static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
  10021. bool Complain = true) {
  10022. if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  10023. S.DeduceReturnType(FD, Loc, Complain))
  10024. return true;
  10025. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  10026. if (S.getLangOpts().CPlusPlus17 &&
  10027. isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  10028. !S.ResolveExceptionSpec(Loc, FPT))
  10029. return true;
  10030. return false;
  10031. }
  10032. namespace {
  10033. // A helper class to help with address of function resolution
  10034. // - allows us to avoid passing around all those ugly parameters
  10035. class AddressOfFunctionResolver {
  10036. Sema& S;
  10037. Expr* SourceExpr;
  10038. const QualType& TargetType;
  10039. QualType TargetFunctionType; // Extracted function type from target type
  10040. bool Complain;
  10041. //DeclAccessPair& ResultFunctionAccessPair;
  10042. ASTContext& Context;
  10043. bool TargetTypeIsNonStaticMemberFunction;
  10044. bool FoundNonTemplateFunction;
  10045. bool StaticMemberFunctionFromBoundPointer;
  10046. bool HasComplained;
  10047. OverloadExpr::FindResult OvlExprInfo;
  10048. OverloadExpr *OvlExpr;
  10049. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  10050. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  10051. TemplateSpecCandidateSet FailedCandidates;
  10052. public:
  10053. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  10054. const QualType &TargetType, bool Complain)
  10055. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  10056. Complain(Complain), Context(S.getASTContext()),
  10057. TargetTypeIsNonStaticMemberFunction(
  10058. !!TargetType->getAs<MemberPointerType>()),
  10059. FoundNonTemplateFunction(false),
  10060. StaticMemberFunctionFromBoundPointer(false),
  10061. HasComplained(false),
  10062. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  10063. OvlExpr(OvlExprInfo.Expression),
  10064. FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
  10065. ExtractUnqualifiedFunctionTypeFromTargetType();
  10066. if (TargetFunctionType->isFunctionType()) {
  10067. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  10068. if (!UME->isImplicitAccess() &&
  10069. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  10070. StaticMemberFunctionFromBoundPointer = true;
  10071. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  10072. DeclAccessPair dap;
  10073. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  10074. OvlExpr, false, &dap)) {
  10075. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  10076. if (!Method->isStatic()) {
  10077. // If the target type is a non-function type and the function found
  10078. // is a non-static member function, pretend as if that was the
  10079. // target, it's the only possible type to end up with.
  10080. TargetTypeIsNonStaticMemberFunction = true;
  10081. // And skip adding the function if its not in the proper form.
  10082. // We'll diagnose this due to an empty set of functions.
  10083. if (!OvlExprInfo.HasFormOfMemberPointer)
  10084. return;
  10085. }
  10086. Matches.push_back(std::make_pair(dap, Fn));
  10087. }
  10088. return;
  10089. }
  10090. if (OvlExpr->hasExplicitTemplateArgs())
  10091. OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
  10092. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  10093. // C++ [over.over]p4:
  10094. // If more than one function is selected, [...]
  10095. if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
  10096. if (FoundNonTemplateFunction)
  10097. EliminateAllTemplateMatches();
  10098. else
  10099. EliminateAllExceptMostSpecializedTemplate();
  10100. }
  10101. }
  10102. if (S.getLangOpts().CUDA && Matches.size() > 1)
  10103. EliminateSuboptimalCudaMatches();
  10104. }
  10105. bool hasComplained() const { return HasComplained; }
  10106. private:
  10107. bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
  10108. QualType Discard;
  10109. return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
  10110. S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
  10111. }
  10112. /// \return true if A is considered a better overload candidate for the
  10113. /// desired type than B.
  10114. bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
  10115. // If A doesn't have exactly the correct type, we don't want to classify it
  10116. // as "better" than anything else. This way, the user is required to
  10117. // disambiguate for us if there are multiple candidates and no exact match.
  10118. return candidateHasExactlyCorrectType(A) &&
  10119. (!candidateHasExactlyCorrectType(B) ||
  10120. compareEnableIfAttrs(S, A, B) == Comparison::Better);
  10121. }
  10122. /// \return true if we were able to eliminate all but one overload candidate,
  10123. /// false otherwise.
  10124. bool eliminiateSuboptimalOverloadCandidates() {
  10125. // Same algorithm as overload resolution -- one pass to pick the "best",
  10126. // another pass to be sure that nothing is better than the best.
  10127. auto Best = Matches.begin();
  10128. for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
  10129. if (isBetterCandidate(I->second, Best->second))
  10130. Best = I;
  10131. const FunctionDecl *BestFn = Best->second;
  10132. auto IsBestOrInferiorToBest = [this, BestFn](
  10133. const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
  10134. return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
  10135. };
  10136. // Note: We explicitly leave Matches unmodified if there isn't a clear best
  10137. // option, so we can potentially give the user a better error
  10138. if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
  10139. return false;
  10140. Matches[0] = *Best;
  10141. Matches.resize(1);
  10142. return true;
  10143. }
  10144. bool isTargetTypeAFunction() const {
  10145. return TargetFunctionType->isFunctionType();
  10146. }
  10147. // [ToType] [Return]
  10148. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  10149. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  10150. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  10151. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  10152. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  10153. }
  10154. // return true if any matching specializations were found
  10155. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  10156. const DeclAccessPair& CurAccessFunPair) {
  10157. if (CXXMethodDecl *Method
  10158. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  10159. // Skip non-static function templates when converting to pointer, and
  10160. // static when converting to member pointer.
  10161. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  10162. return false;
  10163. }
  10164. else if (TargetTypeIsNonStaticMemberFunction)
  10165. return false;
  10166. // C++ [over.over]p2:
  10167. // If the name is a function template, template argument deduction is
  10168. // done (14.8.2.2), and if the argument deduction succeeds, the
  10169. // resulting template argument list is used to generate a single
  10170. // function template specialization, which is added to the set of
  10171. // overloaded functions considered.
  10172. FunctionDecl *Specialization = nullptr;
  10173. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  10174. if (Sema::TemplateDeductionResult Result
  10175. = S.DeduceTemplateArguments(FunctionTemplate,
  10176. &OvlExplicitTemplateArgs,
  10177. TargetFunctionType, Specialization,
  10178. Info, /*IsAddressOfFunction*/true)) {
  10179. // Make a note of the failed deduction for diagnostics.
  10180. FailedCandidates.addCandidate()
  10181. .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
  10182. MakeDeductionFailureInfo(Context, Result, Info));
  10183. return false;
  10184. }
  10185. // Template argument deduction ensures that we have an exact match or
  10186. // compatible pointer-to-function arguments that would be adjusted by ICS.
  10187. // This function template specicalization works.
  10188. assert(S.isSameOrCompatibleFunctionType(
  10189. Context.getCanonicalType(Specialization->getType()),
  10190. Context.getCanonicalType(TargetFunctionType)));
  10191. if (!S.checkAddressOfFunctionIsAvailable(Specialization))
  10192. return false;
  10193. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  10194. return true;
  10195. }
  10196. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  10197. const DeclAccessPair& CurAccessFunPair) {
  10198. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  10199. // Skip non-static functions when converting to pointer, and static
  10200. // when converting to member pointer.
  10201. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  10202. return false;
  10203. }
  10204. else if (TargetTypeIsNonStaticMemberFunction)
  10205. return false;
  10206. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  10207. if (S.getLangOpts().CUDA)
  10208. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  10209. if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
  10210. return false;
  10211. if (FunDecl->isMultiVersion()) {
  10212. const auto *TA = FunDecl->getAttr<TargetAttr>();
  10213. if (TA && !TA->isDefaultVersion())
  10214. return false;
  10215. }
  10216. // If any candidate has a placeholder return type, trigger its deduction
  10217. // now.
  10218. if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
  10219. Complain)) {
  10220. HasComplained |= Complain;
  10221. return false;
  10222. }
  10223. if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
  10224. return false;
  10225. // If we're in C, we need to support types that aren't exactly identical.
  10226. if (!S.getLangOpts().CPlusPlus ||
  10227. candidateHasExactlyCorrectType(FunDecl)) {
  10228. Matches.push_back(std::make_pair(
  10229. CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  10230. FoundNonTemplateFunction = true;
  10231. return true;
  10232. }
  10233. }
  10234. return false;
  10235. }
  10236. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  10237. bool Ret = false;
  10238. // If the overload expression doesn't have the form of a pointer to
  10239. // member, don't try to convert it to a pointer-to-member type.
  10240. if (IsInvalidFormOfPointerToMemberFunction())
  10241. return false;
  10242. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  10243. E = OvlExpr->decls_end();
  10244. I != E; ++I) {
  10245. // Look through any using declarations to find the underlying function.
  10246. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  10247. // C++ [over.over]p3:
  10248. // Non-member functions and static member functions match
  10249. // targets of type "pointer-to-function" or "reference-to-function."
  10250. // Nonstatic member functions match targets of
  10251. // type "pointer-to-member-function."
  10252. // Note that according to DR 247, the containing class does not matter.
  10253. if (FunctionTemplateDecl *FunctionTemplate
  10254. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  10255. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  10256. Ret = true;
  10257. }
  10258. // If we have explicit template arguments supplied, skip non-templates.
  10259. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  10260. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  10261. Ret = true;
  10262. }
  10263. assert(Ret || Matches.empty());
  10264. return Ret;
  10265. }
  10266. void EliminateAllExceptMostSpecializedTemplate() {
  10267. // [...] and any given function template specialization F1 is
  10268. // eliminated if the set contains a second function template
  10269. // specialization whose function template is more specialized
  10270. // than the function template of F1 according to the partial
  10271. // ordering rules of 14.5.5.2.
  10272. // The algorithm specified above is quadratic. We instead use a
  10273. // two-pass algorithm (similar to the one used to identify the
  10274. // best viable function in an overload set) that identifies the
  10275. // best function template (if it exists).
  10276. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  10277. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  10278. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  10279. // TODO: It looks like FailedCandidates does not serve much purpose
  10280. // here, since the no_viable diagnostic has index 0.
  10281. UnresolvedSetIterator Result = S.getMostSpecialized(
  10282. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  10283. SourceExpr->getBeginLoc(), S.PDiag(),
  10284. S.PDiag(diag::err_addr_ovl_ambiguous)
  10285. << Matches[0].second->getDeclName(),
  10286. S.PDiag(diag::note_ovl_candidate)
  10287. << (unsigned)oc_function << (unsigned)ocs_described_template,
  10288. Complain, TargetFunctionType);
  10289. if (Result != MatchesCopy.end()) {
  10290. // Make it the first and only element
  10291. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  10292. Matches[0].second = cast<FunctionDecl>(*Result);
  10293. Matches.resize(1);
  10294. } else
  10295. HasComplained |= Complain;
  10296. }
  10297. void EliminateAllTemplateMatches() {
  10298. // [...] any function template specializations in the set are
  10299. // eliminated if the set also contains a non-template function, [...]
  10300. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  10301. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  10302. ++I;
  10303. else {
  10304. Matches[I] = Matches[--N];
  10305. Matches.resize(N);
  10306. }
  10307. }
  10308. }
  10309. void EliminateSuboptimalCudaMatches() {
  10310. S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
  10311. }
  10312. public:
  10313. void ComplainNoMatchesFound() const {
  10314. assert(Matches.empty());
  10315. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
  10316. << OvlExpr->getName() << TargetFunctionType
  10317. << OvlExpr->getSourceRange();
  10318. if (FailedCandidates.empty())
  10319. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  10320. /*TakingAddress=*/true);
  10321. else {
  10322. // We have some deduction failure messages. Use them to diagnose
  10323. // the function templates, and diagnose the non-template candidates
  10324. // normally.
  10325. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  10326. IEnd = OvlExpr->decls_end();
  10327. I != IEnd; ++I)
  10328. if (FunctionDecl *Fun =
  10329. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  10330. if (!functionHasPassObjectSizeParams(Fun))
  10331. S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
  10332. /*TakingAddress=*/true);
  10333. FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
  10334. }
  10335. }
  10336. bool IsInvalidFormOfPointerToMemberFunction() const {
  10337. return TargetTypeIsNonStaticMemberFunction &&
  10338. !OvlExprInfo.HasFormOfMemberPointer;
  10339. }
  10340. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  10341. // TODO: Should we condition this on whether any functions might
  10342. // have matched, or is it more appropriate to do that in callers?
  10343. // TODO: a fixit wouldn't hurt.
  10344. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  10345. << TargetType << OvlExpr->getSourceRange();
  10346. }
  10347. bool IsStaticMemberFunctionFromBoundPointer() const {
  10348. return StaticMemberFunctionFromBoundPointer;
  10349. }
  10350. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  10351. S.Diag(OvlExpr->getBeginLoc(),
  10352. diag::err_invalid_form_pointer_member_function)
  10353. << OvlExpr->getSourceRange();
  10354. }
  10355. void ComplainOfInvalidConversion() const {
  10356. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
  10357. << OvlExpr->getName() << TargetType;
  10358. }
  10359. void ComplainMultipleMatchesFound() const {
  10360. assert(Matches.size() > 1);
  10361. S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
  10362. << OvlExpr->getName() << OvlExpr->getSourceRange();
  10363. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
  10364. /*TakingAddress=*/true);
  10365. }
  10366. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  10367. int getNumMatches() const { return Matches.size(); }
  10368. FunctionDecl* getMatchingFunctionDecl() const {
  10369. if (Matches.size() != 1) return nullptr;
  10370. return Matches[0].second;
  10371. }
  10372. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  10373. if (Matches.size() != 1) return nullptr;
  10374. return &Matches[0].first;
  10375. }
  10376. };
  10377. }
  10378. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  10379. /// an overloaded function (C++ [over.over]), where @p From is an
  10380. /// expression with overloaded function type and @p ToType is the type
  10381. /// we're trying to resolve to. For example:
  10382. ///
  10383. /// @code
  10384. /// int f(double);
  10385. /// int f(int);
  10386. ///
  10387. /// int (*pfd)(double) = f; // selects f(double)
  10388. /// @endcode
  10389. ///
  10390. /// This routine returns the resulting FunctionDecl if it could be
  10391. /// resolved, and NULL otherwise. When @p Complain is true, this
  10392. /// routine will emit diagnostics if there is an error.
  10393. FunctionDecl *
  10394. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  10395. QualType TargetType,
  10396. bool Complain,
  10397. DeclAccessPair &FoundResult,
  10398. bool *pHadMultipleCandidates) {
  10399. assert(AddressOfExpr->getType() == Context.OverloadTy);
  10400. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  10401. Complain);
  10402. int NumMatches = Resolver.getNumMatches();
  10403. FunctionDecl *Fn = nullptr;
  10404. bool ShouldComplain = Complain && !Resolver.hasComplained();
  10405. if (NumMatches == 0 && ShouldComplain) {
  10406. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  10407. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  10408. else
  10409. Resolver.ComplainNoMatchesFound();
  10410. }
  10411. else if (NumMatches > 1 && ShouldComplain)
  10412. Resolver.ComplainMultipleMatchesFound();
  10413. else if (NumMatches == 1) {
  10414. Fn = Resolver.getMatchingFunctionDecl();
  10415. assert(Fn);
  10416. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  10417. ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
  10418. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  10419. if (Complain) {
  10420. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  10421. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  10422. else
  10423. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  10424. }
  10425. }
  10426. if (pHadMultipleCandidates)
  10427. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  10428. return Fn;
  10429. }
  10430. /// Given an expression that refers to an overloaded function, try to
  10431. /// resolve that function to a single function that can have its address taken.
  10432. /// This will modify `Pair` iff it returns non-null.
  10433. ///
  10434. /// This routine can only realistically succeed if all but one candidates in the
  10435. /// overload set for SrcExpr cannot have their addresses taken.
  10436. FunctionDecl *
  10437. Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
  10438. DeclAccessPair &Pair) {
  10439. OverloadExpr::FindResult R = OverloadExpr::find(E);
  10440. OverloadExpr *Ovl = R.Expression;
  10441. FunctionDecl *Result = nullptr;
  10442. DeclAccessPair DAP;
  10443. // Don't use the AddressOfResolver because we're specifically looking for
  10444. // cases where we have one overload candidate that lacks
  10445. // enable_if/pass_object_size/...
  10446. for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
  10447. auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
  10448. if (!FD)
  10449. return nullptr;
  10450. if (!checkAddressOfFunctionIsAvailable(FD))
  10451. continue;
  10452. // We have more than one result; quit.
  10453. if (Result)
  10454. return nullptr;
  10455. DAP = I.getPair();
  10456. Result = FD;
  10457. }
  10458. if (Result)
  10459. Pair = DAP;
  10460. return Result;
  10461. }
  10462. /// Given an overloaded function, tries to turn it into a non-overloaded
  10463. /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
  10464. /// will perform access checks, diagnose the use of the resultant decl, and, if
  10465. /// requested, potentially perform a function-to-pointer decay.
  10466. ///
  10467. /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
  10468. /// Otherwise, returns true. This may emit diagnostics and return true.
  10469. bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
  10470. ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
  10471. Expr *E = SrcExpr.get();
  10472. assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
  10473. DeclAccessPair DAP;
  10474. FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
  10475. if (!Found || Found->isCPUDispatchMultiVersion() ||
  10476. Found->isCPUSpecificMultiVersion())
  10477. return false;
  10478. // Emitting multiple diagnostics for a function that is both inaccessible and
  10479. // unavailable is consistent with our behavior elsewhere. So, always check
  10480. // for both.
  10481. DiagnoseUseOfDecl(Found, E->getExprLoc());
  10482. CheckAddressOfMemberAccess(E, DAP);
  10483. Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
  10484. if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
  10485. SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
  10486. else
  10487. SrcExpr = Fixed;
  10488. return true;
  10489. }
  10490. /// Given an expression that refers to an overloaded function, try to
  10491. /// resolve that overloaded function expression down to a single function.
  10492. ///
  10493. /// This routine can only resolve template-ids that refer to a single function
  10494. /// template, where that template-id refers to a single template whose template
  10495. /// arguments are either provided by the template-id or have defaults,
  10496. /// as described in C++0x [temp.arg.explicit]p3.
  10497. ///
  10498. /// If no template-ids are found, no diagnostics are emitted and NULL is
  10499. /// returned.
  10500. FunctionDecl *
  10501. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  10502. bool Complain,
  10503. DeclAccessPair *FoundResult) {
  10504. // C++ [over.over]p1:
  10505. // [...] [Note: any redundant set of parentheses surrounding the
  10506. // overloaded function name is ignored (5.1). ]
  10507. // C++ [over.over]p1:
  10508. // [...] The overloaded function name can be preceded by the &
  10509. // operator.
  10510. // If we didn't actually find any template-ids, we're done.
  10511. if (!ovl->hasExplicitTemplateArgs())
  10512. return nullptr;
  10513. TemplateArgumentListInfo ExplicitTemplateArgs;
  10514. ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
  10515. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  10516. // Look through all of the overloaded functions, searching for one
  10517. // whose type matches exactly.
  10518. FunctionDecl *Matched = nullptr;
  10519. for (UnresolvedSetIterator I = ovl->decls_begin(),
  10520. E = ovl->decls_end(); I != E; ++I) {
  10521. // C++0x [temp.arg.explicit]p3:
  10522. // [...] In contexts where deduction is done and fails, or in contexts
  10523. // where deduction is not done, if a template argument list is
  10524. // specified and it, along with any default template arguments,
  10525. // identifies a single function template specialization, then the
  10526. // template-id is an lvalue for the function template specialization.
  10527. FunctionTemplateDecl *FunctionTemplate
  10528. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  10529. // C++ [over.over]p2:
  10530. // If the name is a function template, template argument deduction is
  10531. // done (14.8.2.2), and if the argument deduction succeeds, the
  10532. // resulting template argument list is used to generate a single
  10533. // function template specialization, which is added to the set of
  10534. // overloaded functions considered.
  10535. FunctionDecl *Specialization = nullptr;
  10536. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  10537. if (TemplateDeductionResult Result
  10538. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  10539. Specialization, Info,
  10540. /*IsAddressOfFunction*/true)) {
  10541. // Make a note of the failed deduction for diagnostics.
  10542. // TODO: Actually use the failed-deduction info?
  10543. FailedCandidates.addCandidate()
  10544. .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
  10545. MakeDeductionFailureInfo(Context, Result, Info));
  10546. continue;
  10547. }
  10548. assert(Specialization && "no specialization and no error?");
  10549. // Multiple matches; we can't resolve to a single declaration.
  10550. if (Matched) {
  10551. if (Complain) {
  10552. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  10553. << ovl->getName();
  10554. NoteAllOverloadCandidates(ovl);
  10555. }
  10556. return nullptr;
  10557. }
  10558. Matched = Specialization;
  10559. if (FoundResult) *FoundResult = I.getPair();
  10560. }
  10561. if (Matched &&
  10562. completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
  10563. return nullptr;
  10564. return Matched;
  10565. }
  10566. // Resolve and fix an overloaded expression that can be resolved
  10567. // because it identifies a single function template specialization.
  10568. //
  10569. // Last three arguments should only be supplied if Complain = true
  10570. //
  10571. // Return true if it was logically possible to so resolve the
  10572. // expression, regardless of whether or not it succeeded. Always
  10573. // returns true if 'complain' is set.
  10574. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  10575. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  10576. bool complain, SourceRange OpRangeForComplaining,
  10577. QualType DestTypeForComplaining,
  10578. unsigned DiagIDForComplaining) {
  10579. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  10580. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  10581. DeclAccessPair found;
  10582. ExprResult SingleFunctionExpression;
  10583. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  10584. ovl.Expression, /*complain*/ false, &found)) {
  10585. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
  10586. SrcExpr = ExprError();
  10587. return true;
  10588. }
  10589. // It is only correct to resolve to an instance method if we're
  10590. // resolving a form that's permitted to be a pointer to member.
  10591. // Otherwise we'll end up making a bound member expression, which
  10592. // is illegal in all the contexts we resolve like this.
  10593. if (!ovl.HasFormOfMemberPointer &&
  10594. isa<CXXMethodDecl>(fn) &&
  10595. cast<CXXMethodDecl>(fn)->isInstance()) {
  10596. if (!complain) return false;
  10597. Diag(ovl.Expression->getExprLoc(),
  10598. diag::err_bound_member_function)
  10599. << 0 << ovl.Expression->getSourceRange();
  10600. // TODO: I believe we only end up here if there's a mix of
  10601. // static and non-static candidates (otherwise the expression
  10602. // would have 'bound member' type, not 'overload' type).
  10603. // Ideally we would note which candidate was chosen and why
  10604. // the static candidates were rejected.
  10605. SrcExpr = ExprError();
  10606. return true;
  10607. }
  10608. // Fix the expression to refer to 'fn'.
  10609. SingleFunctionExpression =
  10610. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  10611. // If desired, do function-to-pointer decay.
  10612. if (doFunctionPointerConverion) {
  10613. SingleFunctionExpression =
  10614. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  10615. if (SingleFunctionExpression.isInvalid()) {
  10616. SrcExpr = ExprError();
  10617. return true;
  10618. }
  10619. }
  10620. }
  10621. if (!SingleFunctionExpression.isUsable()) {
  10622. if (complain) {
  10623. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  10624. << ovl.Expression->getName()
  10625. << DestTypeForComplaining
  10626. << OpRangeForComplaining
  10627. << ovl.Expression->getQualifierLoc().getSourceRange();
  10628. NoteAllOverloadCandidates(SrcExpr.get());
  10629. SrcExpr = ExprError();
  10630. return true;
  10631. }
  10632. return false;
  10633. }
  10634. SrcExpr = SingleFunctionExpression;
  10635. return true;
  10636. }
  10637. /// Add a single candidate to the overload set.
  10638. static void AddOverloadedCallCandidate(Sema &S,
  10639. DeclAccessPair FoundDecl,
  10640. TemplateArgumentListInfo *ExplicitTemplateArgs,
  10641. ArrayRef<Expr *> Args,
  10642. OverloadCandidateSet &CandidateSet,
  10643. bool PartialOverloading,
  10644. bool KnownValid) {
  10645. NamedDecl *Callee = FoundDecl.getDecl();
  10646. if (isa<UsingShadowDecl>(Callee))
  10647. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  10648. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  10649. if (ExplicitTemplateArgs) {
  10650. assert(!KnownValid && "Explicit template arguments?");
  10651. return;
  10652. }
  10653. // Prevent ill-formed function decls to be added as overload candidates.
  10654. if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
  10655. return;
  10656. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  10657. /*SuppressUserConversions=*/false,
  10658. PartialOverloading);
  10659. return;
  10660. }
  10661. if (FunctionTemplateDecl *FuncTemplate
  10662. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  10663. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  10664. ExplicitTemplateArgs, Args, CandidateSet,
  10665. /*SuppressUserConversions=*/false,
  10666. PartialOverloading);
  10667. return;
  10668. }
  10669. assert(!KnownValid && "unhandled case in overloaded call candidate");
  10670. }
  10671. /// Add the overload candidates named by callee and/or found by argument
  10672. /// dependent lookup to the given overload set.
  10673. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  10674. ArrayRef<Expr *> Args,
  10675. OverloadCandidateSet &CandidateSet,
  10676. bool PartialOverloading) {
  10677. #ifndef NDEBUG
  10678. // Verify that ArgumentDependentLookup is consistent with the rules
  10679. // in C++0x [basic.lookup.argdep]p3:
  10680. //
  10681. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  10682. // and let Y be the lookup set produced by argument dependent
  10683. // lookup (defined as follows). If X contains
  10684. //
  10685. // -- a declaration of a class member, or
  10686. //
  10687. // -- a block-scope function declaration that is not a
  10688. // using-declaration, or
  10689. //
  10690. // -- a declaration that is neither a function or a function
  10691. // template
  10692. //
  10693. // then Y is empty.
  10694. if (ULE->requiresADL()) {
  10695. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  10696. E = ULE->decls_end(); I != E; ++I) {
  10697. assert(!(*I)->getDeclContext()->isRecord());
  10698. assert(isa<UsingShadowDecl>(*I) ||
  10699. !(*I)->getDeclContext()->isFunctionOrMethod());
  10700. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  10701. }
  10702. }
  10703. #endif
  10704. // It would be nice to avoid this copy.
  10705. TemplateArgumentListInfo TABuffer;
  10706. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  10707. if (ULE->hasExplicitTemplateArgs()) {
  10708. ULE->copyTemplateArgumentsInto(TABuffer);
  10709. ExplicitTemplateArgs = &TABuffer;
  10710. }
  10711. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  10712. E = ULE->decls_end(); I != E; ++I)
  10713. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  10714. CandidateSet, PartialOverloading,
  10715. /*KnownValid*/ true);
  10716. if (ULE->requiresADL())
  10717. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  10718. Args, ExplicitTemplateArgs,
  10719. CandidateSet, PartialOverloading);
  10720. }
  10721. /// Determine whether a declaration with the specified name could be moved into
  10722. /// a different namespace.
  10723. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  10724. switch (Name.getCXXOverloadedOperator()) {
  10725. case OO_New: case OO_Array_New:
  10726. case OO_Delete: case OO_Array_Delete:
  10727. return false;
  10728. default:
  10729. return true;
  10730. }
  10731. }
  10732. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  10733. /// template, where the non-dependent name was declared after the template
  10734. /// was defined. This is common in code written for a compilers which do not
  10735. /// correctly implement two-stage name lookup.
  10736. ///
  10737. /// Returns true if a viable candidate was found and a diagnostic was issued.
  10738. static bool
  10739. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  10740. const CXXScopeSpec &SS, LookupResult &R,
  10741. OverloadCandidateSet::CandidateSetKind CSK,
  10742. TemplateArgumentListInfo *ExplicitTemplateArgs,
  10743. ArrayRef<Expr *> Args,
  10744. bool *DoDiagnoseEmptyLookup = nullptr) {
  10745. if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
  10746. return false;
  10747. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  10748. if (DC->isTransparentContext())
  10749. continue;
  10750. SemaRef.LookupQualifiedName(R, DC);
  10751. if (!R.empty()) {
  10752. R.suppressDiagnostics();
  10753. if (isa<CXXRecordDecl>(DC)) {
  10754. // Don't diagnose names we find in classes; we get much better
  10755. // diagnostics for these from DiagnoseEmptyLookup.
  10756. R.clear();
  10757. if (DoDiagnoseEmptyLookup)
  10758. *DoDiagnoseEmptyLookup = true;
  10759. return false;
  10760. }
  10761. OverloadCandidateSet Candidates(FnLoc, CSK);
  10762. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  10763. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  10764. ExplicitTemplateArgs, Args,
  10765. Candidates, false, /*KnownValid*/ false);
  10766. OverloadCandidateSet::iterator Best;
  10767. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  10768. // No viable functions. Don't bother the user with notes for functions
  10769. // which don't work and shouldn't be found anyway.
  10770. R.clear();
  10771. return false;
  10772. }
  10773. // Find the namespaces where ADL would have looked, and suggest
  10774. // declaring the function there instead.
  10775. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  10776. Sema::AssociatedClassSet AssociatedClasses;
  10777. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  10778. AssociatedNamespaces,
  10779. AssociatedClasses);
  10780. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  10781. if (canBeDeclaredInNamespace(R.getLookupName())) {
  10782. DeclContext *Std = SemaRef.getStdNamespace();
  10783. for (Sema::AssociatedNamespaceSet::iterator
  10784. it = AssociatedNamespaces.begin(),
  10785. end = AssociatedNamespaces.end(); it != end; ++it) {
  10786. // Never suggest declaring a function within namespace 'std'.
  10787. if (Std && Std->Encloses(*it))
  10788. continue;
  10789. // Never suggest declaring a function within a namespace with a
  10790. // reserved name, like __gnu_cxx.
  10791. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  10792. if (NS &&
  10793. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  10794. continue;
  10795. SuggestedNamespaces.insert(*it);
  10796. }
  10797. }
  10798. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  10799. << R.getLookupName();
  10800. if (SuggestedNamespaces.empty()) {
  10801. SemaRef.Diag(Best->Function->getLocation(),
  10802. diag::note_not_found_by_two_phase_lookup)
  10803. << R.getLookupName() << 0;
  10804. } else if (SuggestedNamespaces.size() == 1) {
  10805. SemaRef.Diag(Best->Function->getLocation(),
  10806. diag::note_not_found_by_two_phase_lookup)
  10807. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  10808. } else {
  10809. // FIXME: It would be useful to list the associated namespaces here,
  10810. // but the diagnostics infrastructure doesn't provide a way to produce
  10811. // a localized representation of a list of items.
  10812. SemaRef.Diag(Best->Function->getLocation(),
  10813. diag::note_not_found_by_two_phase_lookup)
  10814. << R.getLookupName() << 2;
  10815. }
  10816. // Try to recover by calling this function.
  10817. return true;
  10818. }
  10819. R.clear();
  10820. }
  10821. return false;
  10822. }
  10823. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  10824. /// template, where the non-dependent operator was declared after the template
  10825. /// was defined.
  10826. ///
  10827. /// Returns true if a viable candidate was found and a diagnostic was issued.
  10828. static bool
  10829. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  10830. SourceLocation OpLoc,
  10831. ArrayRef<Expr *> Args) {
  10832. DeclarationName OpName =
  10833. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  10834. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  10835. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  10836. OverloadCandidateSet::CSK_Operator,
  10837. /*ExplicitTemplateArgs=*/nullptr, Args);
  10838. }
  10839. namespace {
  10840. class BuildRecoveryCallExprRAII {
  10841. Sema &SemaRef;
  10842. public:
  10843. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  10844. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  10845. SemaRef.IsBuildingRecoveryCallExpr = true;
  10846. }
  10847. ~BuildRecoveryCallExprRAII() {
  10848. SemaRef.IsBuildingRecoveryCallExpr = false;
  10849. }
  10850. };
  10851. }
  10852. /// Attempts to recover from a call where no functions were found.
  10853. ///
  10854. /// Returns true if new candidates were found.
  10855. static ExprResult
  10856. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  10857. UnresolvedLookupExpr *ULE,
  10858. SourceLocation LParenLoc,
  10859. MutableArrayRef<Expr *> Args,
  10860. SourceLocation RParenLoc,
  10861. bool EmptyLookup, bool AllowTypoCorrection) {
  10862. // Do not try to recover if it is already building a recovery call.
  10863. // This stops infinite loops for template instantiations like
  10864. //
  10865. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  10866. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  10867. //
  10868. if (SemaRef.IsBuildingRecoveryCallExpr)
  10869. return ExprError();
  10870. BuildRecoveryCallExprRAII RCE(SemaRef);
  10871. CXXScopeSpec SS;
  10872. SS.Adopt(ULE->getQualifierLoc());
  10873. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  10874. TemplateArgumentListInfo TABuffer;
  10875. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  10876. if (ULE->hasExplicitTemplateArgs()) {
  10877. ULE->copyTemplateArgumentsInto(TABuffer);
  10878. ExplicitTemplateArgs = &TABuffer;
  10879. }
  10880. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  10881. Sema::LookupOrdinaryName);
  10882. bool DoDiagnoseEmptyLookup = EmptyLookup;
  10883. if (!DiagnoseTwoPhaseLookup(
  10884. SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
  10885. ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
  10886. NoTypoCorrectionCCC NoTypoValidator{};
  10887. FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
  10888. ExplicitTemplateArgs != nullptr,
  10889. dyn_cast<MemberExpr>(Fn));
  10890. CorrectionCandidateCallback &Validator =
  10891. AllowTypoCorrection
  10892. ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
  10893. : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
  10894. if (!DoDiagnoseEmptyLookup ||
  10895. SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
  10896. Args))
  10897. return ExprError();
  10898. }
  10899. assert(!R.empty() && "lookup results empty despite recovery");
  10900. // If recovery created an ambiguity, just bail out.
  10901. if (R.isAmbiguous()) {
  10902. R.suppressDiagnostics();
  10903. return ExprError();
  10904. }
  10905. // Build an implicit member call if appropriate. Just drop the
  10906. // casts and such from the call, we don't really care.
  10907. ExprResult NewFn = ExprError();
  10908. if ((*R.begin())->isCXXClassMember())
  10909. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
  10910. ExplicitTemplateArgs, S);
  10911. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  10912. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  10913. ExplicitTemplateArgs);
  10914. else
  10915. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  10916. if (NewFn.isInvalid())
  10917. return ExprError();
  10918. // This shouldn't cause an infinite loop because we're giving it
  10919. // an expression with viable lookup results, which should never
  10920. // end up here.
  10921. return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  10922. MultiExprArg(Args.data(), Args.size()),
  10923. RParenLoc);
  10924. }
  10925. /// Constructs and populates an OverloadedCandidateSet from
  10926. /// the given function.
  10927. /// \returns true when an the ExprResult output parameter has been set.
  10928. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  10929. UnresolvedLookupExpr *ULE,
  10930. MultiExprArg Args,
  10931. SourceLocation RParenLoc,
  10932. OverloadCandidateSet *CandidateSet,
  10933. ExprResult *Result) {
  10934. #ifndef NDEBUG
  10935. if (ULE->requiresADL()) {
  10936. // To do ADL, we must have found an unqualified name.
  10937. assert(!ULE->getQualifier() && "qualified name with ADL");
  10938. // We don't perform ADL for implicit declarations of builtins.
  10939. // Verify that this was correctly set up.
  10940. FunctionDecl *F;
  10941. if (ULE->decls_begin() != ULE->decls_end() &&
  10942. ULE->decls_begin() + 1 == ULE->decls_end() &&
  10943. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  10944. F->getBuiltinID() && F->isImplicit())
  10945. llvm_unreachable("performing ADL for builtin");
  10946. // We don't perform ADL in C.
  10947. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  10948. }
  10949. #endif
  10950. UnbridgedCastsSet UnbridgedCasts;
  10951. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  10952. *Result = ExprError();
  10953. return true;
  10954. }
  10955. // Add the functions denoted by the callee to the set of candidate
  10956. // functions, including those from argument-dependent lookup.
  10957. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  10958. if (getLangOpts().MSVCCompat &&
  10959. CurContext->isDependentContext() && !isSFINAEContext() &&
  10960. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  10961. OverloadCandidateSet::iterator Best;
  10962. if (CandidateSet->empty() ||
  10963. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
  10964. OR_No_Viable_Function) {
  10965. // In Microsoft mode, if we are inside a template class member function
  10966. // then create a type dependent CallExpr. The goal is to postpone name
  10967. // lookup to instantiation time to be able to search into type dependent
  10968. // base classes.
  10969. CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
  10970. VK_RValue, RParenLoc);
  10971. CE->setTypeDependent(true);
  10972. CE->setValueDependent(true);
  10973. CE->setInstantiationDependent(true);
  10974. *Result = CE;
  10975. return true;
  10976. }
  10977. }
  10978. if (CandidateSet->empty())
  10979. return false;
  10980. UnbridgedCasts.restore();
  10981. return false;
  10982. }
  10983. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  10984. /// the completed call expression. If overload resolution fails, emits
  10985. /// diagnostics and returns ExprError()
  10986. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  10987. UnresolvedLookupExpr *ULE,
  10988. SourceLocation LParenLoc,
  10989. MultiExprArg Args,
  10990. SourceLocation RParenLoc,
  10991. Expr *ExecConfig,
  10992. OverloadCandidateSet *CandidateSet,
  10993. OverloadCandidateSet::iterator *Best,
  10994. OverloadingResult OverloadResult,
  10995. bool AllowTypoCorrection) {
  10996. if (CandidateSet->empty())
  10997. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  10998. RParenLoc, /*EmptyLookup=*/true,
  10999. AllowTypoCorrection);
  11000. switch (OverloadResult) {
  11001. case OR_Success: {
  11002. FunctionDecl *FDecl = (*Best)->Function;
  11003. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  11004. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  11005. return ExprError();
  11006. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  11007. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  11008. ExecConfig, /*IsExecConfig=*/false,
  11009. (*Best)->IsADLCandidate);
  11010. }
  11011. case OR_No_Viable_Function: {
  11012. // Try to recover by looking for viable functions which the user might
  11013. // have meant to call.
  11014. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  11015. Args, RParenLoc,
  11016. /*EmptyLookup=*/false,
  11017. AllowTypoCorrection);
  11018. if (!Recovery.isInvalid())
  11019. return Recovery;
  11020. // If the user passes in a function that we can't take the address of, we
  11021. // generally end up emitting really bad error messages. Here, we attempt to
  11022. // emit better ones.
  11023. for (const Expr *Arg : Args) {
  11024. if (!Arg->getType()->isFunctionType())
  11025. continue;
  11026. if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
  11027. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  11028. if (FD &&
  11029. !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  11030. Arg->getExprLoc()))
  11031. return ExprError();
  11032. }
  11033. }
  11034. CandidateSet->NoteCandidates(
  11035. PartialDiagnosticAt(
  11036. Fn->getBeginLoc(),
  11037. SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
  11038. << ULE->getName() << Fn->getSourceRange()),
  11039. SemaRef, OCD_AllCandidates, Args);
  11040. break;
  11041. }
  11042. case OR_Ambiguous:
  11043. CandidateSet->NoteCandidates(
  11044. PartialDiagnosticAt(Fn->getBeginLoc(),
  11045. SemaRef.PDiag(diag::err_ovl_ambiguous_call)
  11046. << ULE->getName() << Fn->getSourceRange()),
  11047. SemaRef, OCD_ViableCandidates, Args);
  11048. break;
  11049. case OR_Deleted: {
  11050. CandidateSet->NoteCandidates(
  11051. PartialDiagnosticAt(Fn->getBeginLoc(),
  11052. SemaRef.PDiag(diag::err_ovl_deleted_call)
  11053. << ULE->getName() << Fn->getSourceRange()),
  11054. SemaRef, OCD_AllCandidates, Args);
  11055. // We emitted an error for the unavailable/deleted function call but keep
  11056. // the call in the AST.
  11057. FunctionDecl *FDecl = (*Best)->Function;
  11058. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  11059. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  11060. ExecConfig, /*IsExecConfig=*/false,
  11061. (*Best)->IsADLCandidate);
  11062. }
  11063. }
  11064. // Overload resolution failed.
  11065. return ExprError();
  11066. }
  11067. static void markUnaddressableCandidatesUnviable(Sema &S,
  11068. OverloadCandidateSet &CS) {
  11069. for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
  11070. if (I->Viable &&
  11071. !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
  11072. I->Viable = false;
  11073. I->FailureKind = ovl_fail_addr_not_available;
  11074. }
  11075. }
  11076. }
  11077. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  11078. /// (which eventually refers to the declaration Func) and the call
  11079. /// arguments Args/NumArgs, attempt to resolve the function call down
  11080. /// to a specific function. If overload resolution succeeds, returns
  11081. /// the call expression produced by overload resolution.
  11082. /// Otherwise, emits diagnostics and returns ExprError.
  11083. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  11084. UnresolvedLookupExpr *ULE,
  11085. SourceLocation LParenLoc,
  11086. MultiExprArg Args,
  11087. SourceLocation RParenLoc,
  11088. Expr *ExecConfig,
  11089. bool AllowTypoCorrection,
  11090. bool CalleesAddressIsTaken) {
  11091. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  11092. OverloadCandidateSet::CSK_Normal);
  11093. ExprResult result;
  11094. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  11095. &result))
  11096. return result;
  11097. // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
  11098. // functions that aren't addressible are considered unviable.
  11099. if (CalleesAddressIsTaken)
  11100. markUnaddressableCandidatesUnviable(*this, CandidateSet);
  11101. OverloadCandidateSet::iterator Best;
  11102. OverloadingResult OverloadResult =
  11103. CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
  11104. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
  11105. ExecConfig, &CandidateSet, &Best,
  11106. OverloadResult, AllowTypoCorrection);
  11107. }
  11108. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  11109. return Functions.size() > 1 ||
  11110. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  11111. }
  11112. /// Create a unary operation that may resolve to an overloaded
  11113. /// operator.
  11114. ///
  11115. /// \param OpLoc The location of the operator itself (e.g., '*').
  11116. ///
  11117. /// \param Opc The UnaryOperatorKind that describes this operator.
  11118. ///
  11119. /// \param Fns The set of non-member functions that will be
  11120. /// considered by overload resolution. The caller needs to build this
  11121. /// set based on the context using, e.g.,
  11122. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  11123. /// set should not contain any member functions; those will be added
  11124. /// by CreateOverloadedUnaryOp().
  11125. ///
  11126. /// \param Input The input argument.
  11127. ExprResult
  11128. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
  11129. const UnresolvedSetImpl &Fns,
  11130. Expr *Input, bool PerformADL) {
  11131. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  11132. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  11133. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  11134. // TODO: provide better source location info.
  11135. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  11136. if (checkPlaceholderForOverload(*this, Input))
  11137. return ExprError();
  11138. Expr *Args[2] = { Input, nullptr };
  11139. unsigned NumArgs = 1;
  11140. // For post-increment and post-decrement, add the implicit '0' as
  11141. // the second argument, so that we know this is a post-increment or
  11142. // post-decrement.
  11143. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  11144. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  11145. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  11146. SourceLocation());
  11147. NumArgs = 2;
  11148. }
  11149. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  11150. if (Input->isTypeDependent()) {
  11151. if (Fns.empty())
  11152. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  11153. VK_RValue, OK_Ordinary, OpLoc, false);
  11154. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11155. UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
  11156. Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
  11157. /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
  11158. return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
  11159. Context.DependentTy, VK_RValue, OpLoc,
  11160. FPOptions());
  11161. }
  11162. // Build an empty overload set.
  11163. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  11164. // Add the candidates from the given function set.
  11165. AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
  11166. // Add operator candidates that are member functions.
  11167. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  11168. // Add candidates from ADL.
  11169. if (PerformADL) {
  11170. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  11171. /*ExplicitTemplateArgs*/nullptr,
  11172. CandidateSet);
  11173. }
  11174. // Add builtin operator candidates.
  11175. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  11176. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11177. // Perform overload resolution.
  11178. OverloadCandidateSet::iterator Best;
  11179. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  11180. case OR_Success: {
  11181. // We found a built-in operator or an overloaded operator.
  11182. FunctionDecl *FnDecl = Best->Function;
  11183. if (FnDecl) {
  11184. Expr *Base = nullptr;
  11185. // We matched an overloaded operator. Build a call to that
  11186. // operator.
  11187. // Convert the arguments.
  11188. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11189. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  11190. ExprResult InputRes =
  11191. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  11192. Best->FoundDecl, Method);
  11193. if (InputRes.isInvalid())
  11194. return ExprError();
  11195. Base = Input = InputRes.get();
  11196. } else {
  11197. // Convert the arguments.
  11198. ExprResult InputInit
  11199. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11200. Context,
  11201. FnDecl->getParamDecl(0)),
  11202. SourceLocation(),
  11203. Input);
  11204. if (InputInit.isInvalid())
  11205. return ExprError();
  11206. Input = InputInit.get();
  11207. }
  11208. // Build the actual expression node.
  11209. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  11210. Base, HadMultipleCandidates,
  11211. OpLoc);
  11212. if (FnExpr.isInvalid())
  11213. return ExprError();
  11214. // Determine the result type.
  11215. QualType ResultTy = FnDecl->getReturnType();
  11216. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11217. ResultTy = ResultTy.getNonLValueExprType(Context);
  11218. Args[0] = Input;
  11219. CallExpr *TheCall = CXXOperatorCallExpr::Create(
  11220. Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
  11221. FPOptions(), Best->IsADLCandidate);
  11222. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  11223. return ExprError();
  11224. if (CheckFunctionCall(FnDecl, TheCall,
  11225. FnDecl->getType()->castAs<FunctionProtoType>()))
  11226. return ExprError();
  11227. return MaybeBindToTemporary(TheCall);
  11228. } else {
  11229. // We matched a built-in operator. Convert the arguments, then
  11230. // break out so that we will build the appropriate built-in
  11231. // operator node.
  11232. ExprResult InputRes = PerformImplicitConversion(
  11233. Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
  11234. CCK_ForBuiltinOverloadedOp);
  11235. if (InputRes.isInvalid())
  11236. return ExprError();
  11237. Input = InputRes.get();
  11238. break;
  11239. }
  11240. }
  11241. case OR_No_Viable_Function:
  11242. // This is an erroneous use of an operator which can be overloaded by
  11243. // a non-member function. Check for non-member operators which were
  11244. // defined too late to be candidates.
  11245. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  11246. // FIXME: Recover by calling the found function.
  11247. return ExprError();
  11248. // No viable function; fall through to handling this as a
  11249. // built-in operator, which will produce an error message for us.
  11250. break;
  11251. case OR_Ambiguous:
  11252. CandidateSet.NoteCandidates(
  11253. PartialDiagnosticAt(OpLoc,
  11254. PDiag(diag::err_ovl_ambiguous_oper_unary)
  11255. << UnaryOperator::getOpcodeStr(Opc)
  11256. << Input->getType() << Input->getSourceRange()),
  11257. *this, OCD_ViableCandidates, ArgsArray,
  11258. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  11259. return ExprError();
  11260. case OR_Deleted:
  11261. CandidateSet.NoteCandidates(
  11262. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  11263. << UnaryOperator::getOpcodeStr(Opc)
  11264. << Input->getSourceRange()),
  11265. *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
  11266. OpLoc);
  11267. return ExprError();
  11268. }
  11269. // Either we found no viable overloaded operator or we matched a
  11270. // built-in operator. In either case, fall through to trying to
  11271. // build a built-in operation.
  11272. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11273. }
  11274. /// Create a binary operation that may resolve to an overloaded
  11275. /// operator.
  11276. ///
  11277. /// \param OpLoc The location of the operator itself (e.g., '+').
  11278. ///
  11279. /// \param Opc The BinaryOperatorKind that describes this operator.
  11280. ///
  11281. /// \param Fns The set of non-member functions that will be
  11282. /// considered by overload resolution. The caller needs to build this
  11283. /// set based on the context using, e.g.,
  11284. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  11285. /// set should not contain any member functions; those will be added
  11286. /// by CreateOverloadedBinOp().
  11287. ///
  11288. /// \param LHS Left-hand argument.
  11289. /// \param RHS Right-hand argument.
  11290. ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  11291. BinaryOperatorKind Opc,
  11292. const UnresolvedSetImpl &Fns, Expr *LHS,
  11293. Expr *RHS, bool PerformADL,
  11294. bool AllowRewrittenCandidates) {
  11295. Expr *Args[2] = { LHS, RHS };
  11296. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  11297. if (!getLangOpts().CPlusPlus2a)
  11298. AllowRewrittenCandidates = false;
  11299. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  11300. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  11301. // If either side is type-dependent, create an appropriate dependent
  11302. // expression.
  11303. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  11304. if (Fns.empty()) {
  11305. // If there are no functions to store, just build a dependent
  11306. // BinaryOperator or CompoundAssignment.
  11307. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  11308. return new (Context) BinaryOperator(
  11309. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  11310. OpLoc, FPFeatures);
  11311. return new (Context) CompoundAssignOperator(
  11312. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  11313. Context.DependentTy, Context.DependentTy, OpLoc,
  11314. FPFeatures);
  11315. }
  11316. // FIXME: save results of ADL from here?
  11317. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11318. // TODO: provide better source location info in DNLoc component.
  11319. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  11320. UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
  11321. Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
  11322. /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
  11323. return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
  11324. Context.DependentTy, VK_RValue, OpLoc,
  11325. FPFeatures);
  11326. }
  11327. // Always do placeholder-like conversions on the RHS.
  11328. if (checkPlaceholderForOverload(*this, Args[1]))
  11329. return ExprError();
  11330. // Do placeholder-like conversion on the LHS; note that we should
  11331. // not get here with a PseudoObject LHS.
  11332. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  11333. if (checkPlaceholderForOverload(*this, Args[0]))
  11334. return ExprError();
  11335. // If this is the assignment operator, we only perform overload resolution
  11336. // if the left-hand side is a class or enumeration type. This is actually
  11337. // a hack. The standard requires that we do overload resolution between the
  11338. // various built-in candidates, but as DR507 points out, this can lead to
  11339. // problems. So we do it this way, which pretty much follows what GCC does.
  11340. // Note that we go the traditional code path for compound assignment forms.
  11341. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  11342. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11343. // If this is the .* operator, which is not overloadable, just
  11344. // create a built-in binary operator.
  11345. if (Opc == BO_PtrMemD)
  11346. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11347. // Build an empty overload set.
  11348. OverloadCandidateSet CandidateSet(
  11349. OpLoc, OverloadCandidateSet::CSK_Operator,
  11350. OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
  11351. OverloadedOperatorKind ExtraOp =
  11352. AllowRewrittenCandidates ? getRewrittenOverloadedOperator(Op) : OO_None;
  11353. // Add the candidates from the given function set. This also adds the
  11354. // rewritten candidates using these functions if necessary.
  11355. AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
  11356. // Add operator candidates that are member functions.
  11357. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  11358. if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
  11359. AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
  11360. OverloadCandidateParamOrder::Reversed);
  11361. // In C++20, also add any rewritten member candidates.
  11362. if (ExtraOp) {
  11363. AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
  11364. if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
  11365. AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
  11366. CandidateSet,
  11367. OverloadCandidateParamOrder::Reversed);
  11368. }
  11369. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  11370. // performed for an assignment operator (nor for operator[] nor operator->,
  11371. // which don't get here).
  11372. if (Opc != BO_Assign && PerformADL) {
  11373. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  11374. /*ExplicitTemplateArgs*/ nullptr,
  11375. CandidateSet);
  11376. if (ExtraOp) {
  11377. DeclarationName ExtraOpName =
  11378. Context.DeclarationNames.getCXXOperatorName(ExtraOp);
  11379. AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
  11380. /*ExplicitTemplateArgs*/ nullptr,
  11381. CandidateSet);
  11382. }
  11383. }
  11384. // Add builtin operator candidates.
  11385. //
  11386. // FIXME: We don't add any rewritten candidates here. This is strictly
  11387. // incorrect; a builtin candidate could be hidden by a non-viable candidate,
  11388. // resulting in our selecting a rewritten builtin candidate. For example:
  11389. //
  11390. // enum class E { e };
  11391. // bool operator!=(E, E) requires false;
  11392. // bool k = E::e != E::e;
  11393. //
  11394. // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
  11395. // it seems unreasonable to consider rewritten builtin candidates. A core
  11396. // issue has been filed proposing to removed this requirement.
  11397. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  11398. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11399. // Perform overload resolution.
  11400. OverloadCandidateSet::iterator Best;
  11401. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  11402. case OR_Success: {
  11403. // We found a built-in operator or an overloaded operator.
  11404. FunctionDecl *FnDecl = Best->Function;
  11405. bool IsReversed = (Best->RewriteKind & CRK_Reversed);
  11406. if (IsReversed)
  11407. std::swap(Args[0], Args[1]);
  11408. if (FnDecl) {
  11409. Expr *Base = nullptr;
  11410. // We matched an overloaded operator. Build a call to that
  11411. // operator.
  11412. OverloadedOperatorKind ChosenOp =
  11413. FnDecl->getDeclName().getCXXOverloadedOperator();
  11414. // C++2a [over.match.oper]p9:
  11415. // If a rewritten operator== candidate is selected by overload
  11416. // resolution for an operator@, its return type shall be cv bool
  11417. if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
  11418. !FnDecl->getReturnType()->isBooleanType()) {
  11419. Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
  11420. << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
  11421. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11422. Diag(FnDecl->getLocation(), diag::note_declared_at);
  11423. return ExprError();
  11424. }
  11425. if (AllowRewrittenCandidates && !IsReversed &&
  11426. CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
  11427. // We could have reversed this operator, but didn't. Check if the
  11428. // reversed form was a viable candidate, and if so, if it had a
  11429. // better conversion for either parameter. If so, this call is
  11430. // formally ambiguous, and allowing it is an extension.
  11431. for (OverloadCandidate &Cand : CandidateSet) {
  11432. if (Cand.Viable && Cand.Function == FnDecl &&
  11433. Cand.RewriteKind & CRK_Reversed) {
  11434. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  11435. if (CompareImplicitConversionSequences(
  11436. *this, OpLoc, Cand.Conversions[ArgIdx],
  11437. Best->Conversions[ArgIdx]) ==
  11438. ImplicitConversionSequence::Better) {
  11439. Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
  11440. << BinaryOperator::getOpcodeStr(Opc)
  11441. << Args[0]->getType() << Args[1]->getType()
  11442. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11443. Diag(FnDecl->getLocation(),
  11444. diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
  11445. }
  11446. }
  11447. break;
  11448. }
  11449. }
  11450. }
  11451. // Convert the arguments.
  11452. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11453. // Best->Access is only meaningful for class members.
  11454. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  11455. ExprResult Arg1 =
  11456. PerformCopyInitialization(
  11457. InitializedEntity::InitializeParameter(Context,
  11458. FnDecl->getParamDecl(0)),
  11459. SourceLocation(), Args[1]);
  11460. if (Arg1.isInvalid())
  11461. return ExprError();
  11462. ExprResult Arg0 =
  11463. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  11464. Best->FoundDecl, Method);
  11465. if (Arg0.isInvalid())
  11466. return ExprError();
  11467. Base = Args[0] = Arg0.getAs<Expr>();
  11468. Args[1] = RHS = Arg1.getAs<Expr>();
  11469. } else {
  11470. // Convert the arguments.
  11471. ExprResult Arg0 = PerformCopyInitialization(
  11472. InitializedEntity::InitializeParameter(Context,
  11473. FnDecl->getParamDecl(0)),
  11474. SourceLocation(), Args[0]);
  11475. if (Arg0.isInvalid())
  11476. return ExprError();
  11477. ExprResult Arg1 =
  11478. PerformCopyInitialization(
  11479. InitializedEntity::InitializeParameter(Context,
  11480. FnDecl->getParamDecl(1)),
  11481. SourceLocation(), Args[1]);
  11482. if (Arg1.isInvalid())
  11483. return ExprError();
  11484. Args[0] = LHS = Arg0.getAs<Expr>();
  11485. Args[1] = RHS = Arg1.getAs<Expr>();
  11486. }
  11487. // Build the actual expression node.
  11488. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  11489. Best->FoundDecl, Base,
  11490. HadMultipleCandidates, OpLoc);
  11491. if (FnExpr.isInvalid())
  11492. return ExprError();
  11493. // Determine the result type.
  11494. QualType ResultTy = FnDecl->getReturnType();
  11495. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11496. ResultTy = ResultTy.getNonLValueExprType(Context);
  11497. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  11498. Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
  11499. FPFeatures, Best->IsADLCandidate);
  11500. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  11501. FnDecl))
  11502. return ExprError();
  11503. ArrayRef<const Expr *> ArgsArray(Args, 2);
  11504. const Expr *ImplicitThis = nullptr;
  11505. // Cut off the implicit 'this'.
  11506. if (isa<CXXMethodDecl>(FnDecl)) {
  11507. ImplicitThis = ArgsArray[0];
  11508. ArgsArray = ArgsArray.slice(1);
  11509. }
  11510. // Check for a self move.
  11511. if (Op == OO_Equal)
  11512. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  11513. checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
  11514. isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
  11515. VariadicDoesNotApply);
  11516. ExprResult R = MaybeBindToTemporary(TheCall);
  11517. if (R.isInvalid())
  11518. return ExprError();
  11519. // For a rewritten candidate, we've already reversed the arguments
  11520. // if needed. Perform the rest of the rewrite now.
  11521. if ((Best->RewriteKind & CRK_DifferentOperator) ||
  11522. (Op == OO_Spaceship && IsReversed)) {
  11523. if (Op == OO_ExclaimEqual) {
  11524. assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
  11525. R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
  11526. } else {
  11527. assert(ChosenOp == OO_Spaceship && "unexpected operator name");
  11528. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  11529. Expr *ZeroLiteral =
  11530. IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
  11531. Sema::CodeSynthesisContext Ctx;
  11532. Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
  11533. Ctx.Entity = FnDecl;
  11534. pushCodeSynthesisContext(Ctx);
  11535. R = CreateOverloadedBinOp(
  11536. OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
  11537. IsReversed ? R.get() : ZeroLiteral, PerformADL,
  11538. /*AllowRewrittenCandidates=*/false);
  11539. popCodeSynthesisContext();
  11540. }
  11541. if (R.isInvalid())
  11542. return ExprError();
  11543. } else {
  11544. assert(ChosenOp == Op && "unexpected operator name");
  11545. }
  11546. // Make a note in the AST if we did any rewriting.
  11547. if (Best->RewriteKind != CRK_None)
  11548. R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
  11549. return R;
  11550. } else {
  11551. // We matched a built-in operator. Convert the arguments, then
  11552. // break out so that we will build the appropriate built-in
  11553. // operator node.
  11554. ExprResult ArgsRes0 = PerformImplicitConversion(
  11555. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  11556. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11557. if (ArgsRes0.isInvalid())
  11558. return ExprError();
  11559. Args[0] = ArgsRes0.get();
  11560. ExprResult ArgsRes1 = PerformImplicitConversion(
  11561. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  11562. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11563. if (ArgsRes1.isInvalid())
  11564. return ExprError();
  11565. Args[1] = ArgsRes1.get();
  11566. break;
  11567. }
  11568. }
  11569. case OR_No_Viable_Function: {
  11570. // C++ [over.match.oper]p9:
  11571. // If the operator is the operator , [...] and there are no
  11572. // viable functions, then the operator is assumed to be the
  11573. // built-in operator and interpreted according to clause 5.
  11574. if (Opc == BO_Comma)
  11575. break;
  11576. // For class as left operand for assignment or compound assignment
  11577. // operator do not fall through to handling in built-in, but report that
  11578. // no overloaded assignment operator found
  11579. ExprResult Result = ExprError();
  11580. StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
  11581. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
  11582. Args, OpLoc);
  11583. if (Args[0]->getType()->isRecordType() &&
  11584. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  11585. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  11586. << BinaryOperator::getOpcodeStr(Opc)
  11587. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11588. if (Args[0]->getType()->isIncompleteType()) {
  11589. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  11590. << Args[0]->getType()
  11591. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  11592. }
  11593. } else {
  11594. // This is an erroneous use of an operator which can be overloaded by
  11595. // a non-member function. Check for non-member operators which were
  11596. // defined too late to be candidates.
  11597. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  11598. // FIXME: Recover by calling the found function.
  11599. return ExprError();
  11600. // No viable function; try to create a built-in operation, which will
  11601. // produce an error. Then, show the non-viable candidates.
  11602. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11603. }
  11604. assert(Result.isInvalid() &&
  11605. "C++ binary operator overloading is missing candidates!");
  11606. CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
  11607. return Result;
  11608. }
  11609. case OR_Ambiguous:
  11610. CandidateSet.NoteCandidates(
  11611. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  11612. << BinaryOperator::getOpcodeStr(Opc)
  11613. << Args[0]->getType()
  11614. << Args[1]->getType()
  11615. << Args[0]->getSourceRange()
  11616. << Args[1]->getSourceRange()),
  11617. *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  11618. OpLoc);
  11619. return ExprError();
  11620. case OR_Deleted:
  11621. if (isImplicitlyDeleted(Best->Function)) {
  11622. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  11623. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  11624. << Context.getRecordType(Method->getParent())
  11625. << getSpecialMember(Method);
  11626. // The user probably meant to call this special member. Just
  11627. // explain why it's deleted.
  11628. NoteDeletedFunction(Method);
  11629. return ExprError();
  11630. }
  11631. CandidateSet.NoteCandidates(
  11632. PartialDiagnosticAt(
  11633. OpLoc, PDiag(diag::err_ovl_deleted_oper)
  11634. << getOperatorSpelling(Best->Function->getDeclName()
  11635. .getCXXOverloadedOperator())
  11636. << Args[0]->getSourceRange()
  11637. << Args[1]->getSourceRange()),
  11638. *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
  11639. OpLoc);
  11640. return ExprError();
  11641. }
  11642. // We matched a built-in operator; build it.
  11643. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  11644. }
  11645. ExprResult
  11646. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  11647. SourceLocation RLoc,
  11648. Expr *Base, Expr *Idx) {
  11649. Expr *Args[2] = { Base, Idx };
  11650. DeclarationName OpName =
  11651. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  11652. // If either side is type-dependent, create an appropriate dependent
  11653. // expression.
  11654. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  11655. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  11656. // CHECKME: no 'operator' keyword?
  11657. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  11658. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  11659. UnresolvedLookupExpr *Fn
  11660. = UnresolvedLookupExpr::Create(Context, NamingClass,
  11661. NestedNameSpecifierLoc(), OpNameInfo,
  11662. /*ADL*/ true, /*Overloaded*/ false,
  11663. UnresolvedSetIterator(),
  11664. UnresolvedSetIterator());
  11665. // Can't add any actual overloads yet
  11666. return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
  11667. Context.DependentTy, VK_RValue, RLoc,
  11668. FPOptions());
  11669. }
  11670. // Handle placeholders on both operands.
  11671. if (checkPlaceholderForOverload(*this, Args[0]))
  11672. return ExprError();
  11673. if (checkPlaceholderForOverload(*this, Args[1]))
  11674. return ExprError();
  11675. // Build an empty overload set.
  11676. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  11677. // Subscript can only be overloaded as a member function.
  11678. // Add operator candidates that are member functions.
  11679. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  11680. // Add builtin operator candidates.
  11681. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  11682. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11683. // Perform overload resolution.
  11684. OverloadCandidateSet::iterator Best;
  11685. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  11686. case OR_Success: {
  11687. // We found a built-in operator or an overloaded operator.
  11688. FunctionDecl *FnDecl = Best->Function;
  11689. if (FnDecl) {
  11690. // We matched an overloaded operator. Build a call to that
  11691. // operator.
  11692. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  11693. // Convert the arguments.
  11694. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  11695. ExprResult Arg0 =
  11696. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  11697. Best->FoundDecl, Method);
  11698. if (Arg0.isInvalid())
  11699. return ExprError();
  11700. Args[0] = Arg0.get();
  11701. // Convert the arguments.
  11702. ExprResult InputInit
  11703. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  11704. Context,
  11705. FnDecl->getParamDecl(0)),
  11706. SourceLocation(),
  11707. Args[1]);
  11708. if (InputInit.isInvalid())
  11709. return ExprError();
  11710. Args[1] = InputInit.getAs<Expr>();
  11711. // Build the actual expression node.
  11712. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  11713. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  11714. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  11715. Best->FoundDecl,
  11716. Base,
  11717. HadMultipleCandidates,
  11718. OpLocInfo.getLoc(),
  11719. OpLocInfo.getInfo());
  11720. if (FnExpr.isInvalid())
  11721. return ExprError();
  11722. // Determine the result type
  11723. QualType ResultTy = FnDecl->getReturnType();
  11724. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11725. ResultTy = ResultTy.getNonLValueExprType(Context);
  11726. CXXOperatorCallExpr *TheCall =
  11727. CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
  11728. Args, ResultTy, VK, RLoc, FPOptions());
  11729. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  11730. return ExprError();
  11731. if (CheckFunctionCall(Method, TheCall,
  11732. Method->getType()->castAs<FunctionProtoType>()))
  11733. return ExprError();
  11734. return MaybeBindToTemporary(TheCall);
  11735. } else {
  11736. // We matched a built-in operator. Convert the arguments, then
  11737. // break out so that we will build the appropriate built-in
  11738. // operator node.
  11739. ExprResult ArgsRes0 = PerformImplicitConversion(
  11740. Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
  11741. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11742. if (ArgsRes0.isInvalid())
  11743. return ExprError();
  11744. Args[0] = ArgsRes0.get();
  11745. ExprResult ArgsRes1 = PerformImplicitConversion(
  11746. Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
  11747. AA_Passing, CCK_ForBuiltinOverloadedOp);
  11748. if (ArgsRes1.isInvalid())
  11749. return ExprError();
  11750. Args[1] = ArgsRes1.get();
  11751. break;
  11752. }
  11753. }
  11754. case OR_No_Viable_Function: {
  11755. PartialDiagnostic PD = CandidateSet.empty()
  11756. ? (PDiag(diag::err_ovl_no_oper)
  11757. << Args[0]->getType() << /*subscript*/ 0
  11758. << Args[0]->getSourceRange() << Args[1]->getSourceRange())
  11759. : (PDiag(diag::err_ovl_no_viable_subscript)
  11760. << Args[0]->getType() << Args[0]->getSourceRange()
  11761. << Args[1]->getSourceRange());
  11762. CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
  11763. OCD_AllCandidates, Args, "[]", LLoc);
  11764. return ExprError();
  11765. }
  11766. case OR_Ambiguous:
  11767. CandidateSet.NoteCandidates(
  11768. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
  11769. << "[]" << Args[0]->getType()
  11770. << Args[1]->getType()
  11771. << Args[0]->getSourceRange()
  11772. << Args[1]->getSourceRange()),
  11773. *this, OCD_ViableCandidates, Args, "[]", LLoc);
  11774. return ExprError();
  11775. case OR_Deleted:
  11776. CandidateSet.NoteCandidates(
  11777. PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
  11778. << "[]" << Args[0]->getSourceRange()
  11779. << Args[1]->getSourceRange()),
  11780. *this, OCD_AllCandidates, Args, "[]", LLoc);
  11781. return ExprError();
  11782. }
  11783. // We matched a built-in operator; build it.
  11784. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  11785. }
  11786. /// BuildCallToMemberFunction - Build a call to a member
  11787. /// function. MemExpr is the expression that refers to the member
  11788. /// function (and includes the object parameter), Args/NumArgs are the
  11789. /// arguments to the function call (not including the object
  11790. /// parameter). The caller needs to validate that the member
  11791. /// expression refers to a non-static member function or an overloaded
  11792. /// member function.
  11793. ExprResult
  11794. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  11795. SourceLocation LParenLoc,
  11796. MultiExprArg Args,
  11797. SourceLocation RParenLoc) {
  11798. assert(MemExprE->getType() == Context.BoundMemberTy ||
  11799. MemExprE->getType() == Context.OverloadTy);
  11800. // Dig out the member expression. This holds both the object
  11801. // argument and the member function we're referring to.
  11802. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  11803. // Determine whether this is a call to a pointer-to-member function.
  11804. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  11805. assert(op->getType() == Context.BoundMemberTy);
  11806. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  11807. QualType fnType =
  11808. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  11809. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  11810. QualType resultType = proto->getCallResultType(Context);
  11811. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  11812. // Check that the object type isn't more qualified than the
  11813. // member function we're calling.
  11814. Qualifiers funcQuals = proto->getMethodQuals();
  11815. QualType objectType = op->getLHS()->getType();
  11816. if (op->getOpcode() == BO_PtrMemI)
  11817. objectType = objectType->castAs<PointerType>()->getPointeeType();
  11818. Qualifiers objectQuals = objectType.getQualifiers();
  11819. Qualifiers difference = objectQuals - funcQuals;
  11820. difference.removeObjCGCAttr();
  11821. difference.removeAddressSpace();
  11822. if (difference) {
  11823. std::string qualsString = difference.getAsString();
  11824. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  11825. << fnType.getUnqualifiedType()
  11826. << qualsString
  11827. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  11828. }
  11829. CXXMemberCallExpr *call =
  11830. CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
  11831. valueKind, RParenLoc, proto->getNumParams());
  11832. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
  11833. call, nullptr))
  11834. return ExprError();
  11835. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  11836. return ExprError();
  11837. if (CheckOtherCall(call, proto))
  11838. return ExprError();
  11839. return MaybeBindToTemporary(call);
  11840. }
  11841. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  11842. return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
  11843. RParenLoc);
  11844. UnbridgedCastsSet UnbridgedCasts;
  11845. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  11846. return ExprError();
  11847. MemberExpr *MemExpr;
  11848. CXXMethodDecl *Method = nullptr;
  11849. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  11850. NestedNameSpecifier *Qualifier = nullptr;
  11851. if (isa<MemberExpr>(NakedMemExpr)) {
  11852. MemExpr = cast<MemberExpr>(NakedMemExpr);
  11853. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  11854. FoundDecl = MemExpr->getFoundDecl();
  11855. Qualifier = MemExpr->getQualifier();
  11856. UnbridgedCasts.restore();
  11857. } else {
  11858. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  11859. Qualifier = UnresExpr->getQualifier();
  11860. QualType ObjectType = UnresExpr->getBaseType();
  11861. Expr::Classification ObjectClassification
  11862. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  11863. : UnresExpr->getBase()->Classify(Context);
  11864. // Add overload candidates
  11865. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  11866. OverloadCandidateSet::CSK_Normal);
  11867. // FIXME: avoid copy.
  11868. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11869. if (UnresExpr->hasExplicitTemplateArgs()) {
  11870. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11871. TemplateArgs = &TemplateArgsBuffer;
  11872. }
  11873. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  11874. E = UnresExpr->decls_end(); I != E; ++I) {
  11875. NamedDecl *Func = *I;
  11876. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  11877. if (isa<UsingShadowDecl>(Func))
  11878. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  11879. // Microsoft supports direct constructor calls.
  11880. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  11881. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
  11882. CandidateSet,
  11883. /*SuppressUserConversions*/ false);
  11884. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  11885. // If explicit template arguments were provided, we can't call a
  11886. // non-template member function.
  11887. if (TemplateArgs)
  11888. continue;
  11889. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  11890. ObjectClassification, Args, CandidateSet,
  11891. /*SuppressUserConversions=*/false);
  11892. } else {
  11893. AddMethodTemplateCandidate(
  11894. cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
  11895. TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
  11896. /*SuppressUserConversions=*/false);
  11897. }
  11898. }
  11899. DeclarationName DeclName = UnresExpr->getMemberName();
  11900. UnbridgedCasts.restore();
  11901. OverloadCandidateSet::iterator Best;
  11902. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
  11903. Best)) {
  11904. case OR_Success:
  11905. Method = cast<CXXMethodDecl>(Best->Function);
  11906. FoundDecl = Best->FoundDecl;
  11907. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  11908. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  11909. return ExprError();
  11910. // If FoundDecl is different from Method (such as if one is a template
  11911. // and the other a specialization), make sure DiagnoseUseOfDecl is
  11912. // called on both.
  11913. // FIXME: This would be more comprehensively addressed by modifying
  11914. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  11915. // being used.
  11916. if (Method != FoundDecl.getDecl() &&
  11917. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  11918. return ExprError();
  11919. break;
  11920. case OR_No_Viable_Function:
  11921. CandidateSet.NoteCandidates(
  11922. PartialDiagnosticAt(
  11923. UnresExpr->getMemberLoc(),
  11924. PDiag(diag::err_ovl_no_viable_member_function_in_call)
  11925. << DeclName << MemExprE->getSourceRange()),
  11926. *this, OCD_AllCandidates, Args);
  11927. // FIXME: Leaking incoming expressions!
  11928. return ExprError();
  11929. case OR_Ambiguous:
  11930. CandidateSet.NoteCandidates(
  11931. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  11932. PDiag(diag::err_ovl_ambiguous_member_call)
  11933. << DeclName << MemExprE->getSourceRange()),
  11934. *this, OCD_AllCandidates, Args);
  11935. // FIXME: Leaking incoming expressions!
  11936. return ExprError();
  11937. case OR_Deleted:
  11938. CandidateSet.NoteCandidates(
  11939. PartialDiagnosticAt(UnresExpr->getMemberLoc(),
  11940. PDiag(diag::err_ovl_deleted_member_call)
  11941. << DeclName << MemExprE->getSourceRange()),
  11942. *this, OCD_AllCandidates, Args);
  11943. // FIXME: Leaking incoming expressions!
  11944. return ExprError();
  11945. }
  11946. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  11947. // If overload resolution picked a static member, build a
  11948. // non-member call based on that function.
  11949. if (Method->isStatic()) {
  11950. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  11951. RParenLoc);
  11952. }
  11953. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  11954. }
  11955. QualType ResultType = Method->getReturnType();
  11956. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  11957. ResultType = ResultType.getNonLValueExprType(Context);
  11958. assert(Method && "Member call to something that isn't a method?");
  11959. const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
  11960. CXXMemberCallExpr *TheCall =
  11961. CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
  11962. RParenLoc, Proto->getNumParams());
  11963. // Check for a valid return type.
  11964. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  11965. TheCall, Method))
  11966. return ExprError();
  11967. // Convert the object argument (for a non-static member function call).
  11968. // We only need to do this if there was actually an overload; otherwise
  11969. // it was done at lookup.
  11970. if (!Method->isStatic()) {
  11971. ExprResult ObjectArg =
  11972. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  11973. FoundDecl, Method);
  11974. if (ObjectArg.isInvalid())
  11975. return ExprError();
  11976. MemExpr->setBase(ObjectArg.get());
  11977. }
  11978. // Convert the rest of the arguments
  11979. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  11980. RParenLoc))
  11981. return ExprError();
  11982. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  11983. if (CheckFunctionCall(Method, TheCall, Proto))
  11984. return ExprError();
  11985. // In the case the method to call was not selected by the overloading
  11986. // resolution process, we still need to handle the enable_if attribute. Do
  11987. // that here, so it will not hide previous -- and more relevant -- errors.
  11988. if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
  11989. if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
  11990. Diag(MemE->getMemberLoc(),
  11991. diag::err_ovl_no_viable_member_function_in_call)
  11992. << Method << Method->getSourceRange();
  11993. Diag(Method->getLocation(),
  11994. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  11995. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  11996. return ExprError();
  11997. }
  11998. }
  11999. if ((isa<CXXConstructorDecl>(CurContext) ||
  12000. isa<CXXDestructorDecl>(CurContext)) &&
  12001. TheCall->getMethodDecl()->isPure()) {
  12002. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  12003. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
  12004. MemExpr->performsVirtualDispatch(getLangOpts())) {
  12005. Diag(MemExpr->getBeginLoc(),
  12006. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  12007. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  12008. << MD->getParent()->getDeclName();
  12009. Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
  12010. if (getLangOpts().AppleKext)
  12011. Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
  12012. << MD->getParent()->getDeclName() << MD->getDeclName();
  12013. }
  12014. }
  12015. if (CXXDestructorDecl *DD =
  12016. dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
  12017. // a->A::f() doesn't go through the vtable, except in AppleKext mode.
  12018. bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
  12019. CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
  12020. CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
  12021. MemExpr->getMemberLoc());
  12022. }
  12023. return MaybeBindToTemporary(TheCall);
  12024. }
  12025. /// BuildCallToObjectOfClassType - Build a call to an object of class
  12026. /// type (C++ [over.call.object]), which can end up invoking an
  12027. /// overloaded function call operator (@c operator()) or performing a
  12028. /// user-defined conversion on the object argument.
  12029. ExprResult
  12030. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  12031. SourceLocation LParenLoc,
  12032. MultiExprArg Args,
  12033. SourceLocation RParenLoc) {
  12034. if (checkPlaceholderForOverload(*this, Obj))
  12035. return ExprError();
  12036. ExprResult Object = Obj;
  12037. UnbridgedCastsSet UnbridgedCasts;
  12038. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  12039. return ExprError();
  12040. assert(Object.get()->getType()->isRecordType() &&
  12041. "Requires object type argument");
  12042. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  12043. // C++ [over.call.object]p1:
  12044. // If the primary-expression E in the function call syntax
  12045. // evaluates to a class object of type "cv T", then the set of
  12046. // candidate functions includes at least the function call
  12047. // operators of T. The function call operators of T are obtained by
  12048. // ordinary lookup of the name operator() in the context of
  12049. // (E).operator().
  12050. OverloadCandidateSet CandidateSet(LParenLoc,
  12051. OverloadCandidateSet::CSK_Operator);
  12052. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  12053. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  12054. diag::err_incomplete_object_call, Object.get()))
  12055. return true;
  12056. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  12057. LookupQualifiedName(R, Record->getDecl());
  12058. R.suppressDiagnostics();
  12059. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  12060. Oper != OperEnd; ++Oper) {
  12061. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  12062. Object.get()->Classify(Context), Args, CandidateSet,
  12063. /*SuppressUserConversion=*/false);
  12064. }
  12065. // C++ [over.call.object]p2:
  12066. // In addition, for each (non-explicit in C++0x) conversion function
  12067. // declared in T of the form
  12068. //
  12069. // operator conversion-type-id () cv-qualifier;
  12070. //
  12071. // where cv-qualifier is the same cv-qualification as, or a
  12072. // greater cv-qualification than, cv, and where conversion-type-id
  12073. // denotes the type "pointer to function of (P1,...,Pn) returning
  12074. // R", or the type "reference to pointer to function of
  12075. // (P1,...,Pn) returning R", or the type "reference to function
  12076. // of (P1,...,Pn) returning R", a surrogate call function [...]
  12077. // is also considered as a candidate function. Similarly,
  12078. // surrogate call functions are added to the set of candidate
  12079. // functions for each conversion function declared in an
  12080. // accessible base class provided the function is not hidden
  12081. // within T by another intervening declaration.
  12082. const auto &Conversions =
  12083. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  12084. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  12085. NamedDecl *D = *I;
  12086. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  12087. if (isa<UsingShadowDecl>(D))
  12088. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  12089. // Skip over templated conversion functions; they aren't
  12090. // surrogates.
  12091. if (isa<FunctionTemplateDecl>(D))
  12092. continue;
  12093. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  12094. if (!Conv->isExplicit()) {
  12095. // Strip the reference type (if any) and then the pointer type (if
  12096. // any) to get down to what might be a function type.
  12097. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  12098. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  12099. ConvType = ConvPtrType->getPointeeType();
  12100. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  12101. {
  12102. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  12103. Object.get(), Args, CandidateSet);
  12104. }
  12105. }
  12106. }
  12107. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12108. // Perform overload resolution.
  12109. OverloadCandidateSet::iterator Best;
  12110. switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
  12111. Best)) {
  12112. case OR_Success:
  12113. // Overload resolution succeeded; we'll build the appropriate call
  12114. // below.
  12115. break;
  12116. case OR_No_Viable_Function: {
  12117. PartialDiagnostic PD =
  12118. CandidateSet.empty()
  12119. ? (PDiag(diag::err_ovl_no_oper)
  12120. << Object.get()->getType() << /*call*/ 1
  12121. << Object.get()->getSourceRange())
  12122. : (PDiag(diag::err_ovl_no_viable_object_call)
  12123. << Object.get()->getType() << Object.get()->getSourceRange());
  12124. CandidateSet.NoteCandidates(
  12125. PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
  12126. OCD_AllCandidates, Args);
  12127. break;
  12128. }
  12129. case OR_Ambiguous:
  12130. CandidateSet.NoteCandidates(
  12131. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  12132. PDiag(diag::err_ovl_ambiguous_object_call)
  12133. << Object.get()->getType()
  12134. << Object.get()->getSourceRange()),
  12135. *this, OCD_ViableCandidates, Args);
  12136. break;
  12137. case OR_Deleted:
  12138. CandidateSet.NoteCandidates(
  12139. PartialDiagnosticAt(Object.get()->getBeginLoc(),
  12140. PDiag(diag::err_ovl_deleted_object_call)
  12141. << Object.get()->getType()
  12142. << Object.get()->getSourceRange()),
  12143. *this, OCD_AllCandidates, Args);
  12144. break;
  12145. }
  12146. if (Best == CandidateSet.end())
  12147. return true;
  12148. UnbridgedCasts.restore();
  12149. if (Best->Function == nullptr) {
  12150. // Since there is no function declaration, this is one of the
  12151. // surrogate candidates. Dig out the conversion function.
  12152. CXXConversionDecl *Conv
  12153. = cast<CXXConversionDecl>(
  12154. Best->Conversions[0].UserDefined.ConversionFunction);
  12155. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  12156. Best->FoundDecl);
  12157. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  12158. return ExprError();
  12159. assert(Conv == Best->FoundDecl.getDecl() &&
  12160. "Found Decl & conversion-to-functionptr should be same, right?!");
  12161. // We selected one of the surrogate functions that converts the
  12162. // object parameter to a function pointer. Perform the conversion
  12163. // on the object argument, then let BuildCallExpr finish the job.
  12164. // Create an implicit member expr to refer to the conversion operator.
  12165. // and then call it.
  12166. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  12167. Conv, HadMultipleCandidates);
  12168. if (Call.isInvalid())
  12169. return ExprError();
  12170. // Record usage of conversion in an implicit cast.
  12171. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  12172. CK_UserDefinedConversion, Call.get(),
  12173. nullptr, VK_RValue);
  12174. return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  12175. }
  12176. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  12177. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  12178. // that calls this method, using Object for the implicit object
  12179. // parameter and passing along the remaining arguments.
  12180. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  12181. // An error diagnostic has already been printed when parsing the declaration.
  12182. if (Method->isInvalidDecl())
  12183. return ExprError();
  12184. const FunctionProtoType *Proto =
  12185. Method->getType()->getAs<FunctionProtoType>();
  12186. unsigned NumParams = Proto->getNumParams();
  12187. DeclarationNameInfo OpLocInfo(
  12188. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  12189. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  12190. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  12191. Obj, HadMultipleCandidates,
  12192. OpLocInfo.getLoc(),
  12193. OpLocInfo.getInfo());
  12194. if (NewFn.isInvalid())
  12195. return true;
  12196. // The number of argument slots to allocate in the call. If we have default
  12197. // arguments we need to allocate space for them as well. We additionally
  12198. // need one more slot for the object parameter.
  12199. unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
  12200. // Build the full argument list for the method call (the implicit object
  12201. // parameter is placed at the beginning of the list).
  12202. SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
  12203. bool IsError = false;
  12204. // Initialize the implicit object parameter.
  12205. ExprResult ObjRes =
  12206. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  12207. Best->FoundDecl, Method);
  12208. if (ObjRes.isInvalid())
  12209. IsError = true;
  12210. else
  12211. Object = ObjRes;
  12212. MethodArgs[0] = Object.get();
  12213. // Check the argument types.
  12214. for (unsigned i = 0; i != NumParams; i++) {
  12215. Expr *Arg;
  12216. if (i < Args.size()) {
  12217. Arg = Args[i];
  12218. // Pass the argument.
  12219. ExprResult InputInit
  12220. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  12221. Context,
  12222. Method->getParamDecl(i)),
  12223. SourceLocation(), Arg);
  12224. IsError |= InputInit.isInvalid();
  12225. Arg = InputInit.getAs<Expr>();
  12226. } else {
  12227. ExprResult DefArg
  12228. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  12229. if (DefArg.isInvalid()) {
  12230. IsError = true;
  12231. break;
  12232. }
  12233. Arg = DefArg.getAs<Expr>();
  12234. }
  12235. MethodArgs[i + 1] = Arg;
  12236. }
  12237. // If this is a variadic call, handle args passed through "...".
  12238. if (Proto->isVariadic()) {
  12239. // Promote the arguments (C99 6.5.2.2p7).
  12240. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  12241. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  12242. nullptr);
  12243. IsError |= Arg.isInvalid();
  12244. MethodArgs[i + 1] = Arg.get();
  12245. }
  12246. }
  12247. if (IsError)
  12248. return true;
  12249. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  12250. // Once we've built TheCall, all of the expressions are properly owned.
  12251. QualType ResultTy = Method->getReturnType();
  12252. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12253. ResultTy = ResultTy.getNonLValueExprType(Context);
  12254. CXXOperatorCallExpr *TheCall =
  12255. CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
  12256. ResultTy, VK, RParenLoc, FPOptions());
  12257. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  12258. return true;
  12259. if (CheckFunctionCall(Method, TheCall, Proto))
  12260. return true;
  12261. return MaybeBindToTemporary(TheCall);
  12262. }
  12263. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  12264. /// (if one exists), where @c Base is an expression of class type and
  12265. /// @c Member is the name of the member we're trying to find.
  12266. ExprResult
  12267. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  12268. bool *NoArrowOperatorFound) {
  12269. assert(Base->getType()->isRecordType() &&
  12270. "left-hand side must have class type");
  12271. if (checkPlaceholderForOverload(*this, Base))
  12272. return ExprError();
  12273. SourceLocation Loc = Base->getExprLoc();
  12274. // C++ [over.ref]p1:
  12275. //
  12276. // [...] An expression x->m is interpreted as (x.operator->())->m
  12277. // for a class object x of type T if T::operator->() exists and if
  12278. // the operator is selected as the best match function by the
  12279. // overload resolution mechanism (13.3).
  12280. DeclarationName OpName =
  12281. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  12282. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  12283. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  12284. if (RequireCompleteType(Loc, Base->getType(),
  12285. diag::err_typecheck_incomplete_tag, Base))
  12286. return ExprError();
  12287. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  12288. LookupQualifiedName(R, BaseRecord->getDecl());
  12289. R.suppressDiagnostics();
  12290. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  12291. Oper != OperEnd; ++Oper) {
  12292. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  12293. None, CandidateSet, /*SuppressUserConversion=*/false);
  12294. }
  12295. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12296. // Perform overload resolution.
  12297. OverloadCandidateSet::iterator Best;
  12298. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  12299. case OR_Success:
  12300. // Overload resolution succeeded; we'll build the call below.
  12301. break;
  12302. case OR_No_Viable_Function: {
  12303. auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
  12304. if (CandidateSet.empty()) {
  12305. QualType BaseType = Base->getType();
  12306. if (NoArrowOperatorFound) {
  12307. // Report this specific error to the caller instead of emitting a
  12308. // diagnostic, as requested.
  12309. *NoArrowOperatorFound = true;
  12310. return ExprError();
  12311. }
  12312. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  12313. << BaseType << Base->getSourceRange();
  12314. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  12315. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  12316. << FixItHint::CreateReplacement(OpLoc, ".");
  12317. }
  12318. } else
  12319. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  12320. << "operator->" << Base->getSourceRange();
  12321. CandidateSet.NoteCandidates(*this, Base, Cands);
  12322. return ExprError();
  12323. }
  12324. case OR_Ambiguous:
  12325. CandidateSet.NoteCandidates(
  12326. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
  12327. << "->" << Base->getType()
  12328. << Base->getSourceRange()),
  12329. *this, OCD_ViableCandidates, Base);
  12330. return ExprError();
  12331. case OR_Deleted:
  12332. CandidateSet.NoteCandidates(
  12333. PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
  12334. << "->" << Base->getSourceRange()),
  12335. *this, OCD_AllCandidates, Base);
  12336. return ExprError();
  12337. }
  12338. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  12339. // Convert the object parameter.
  12340. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  12341. ExprResult BaseResult =
  12342. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  12343. Best->FoundDecl, Method);
  12344. if (BaseResult.isInvalid())
  12345. return ExprError();
  12346. Base = BaseResult.get();
  12347. // Build the operator call.
  12348. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  12349. Base, HadMultipleCandidates, OpLoc);
  12350. if (FnExpr.isInvalid())
  12351. return ExprError();
  12352. QualType ResultTy = Method->getReturnType();
  12353. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12354. ResultTy = ResultTy.getNonLValueExprType(Context);
  12355. CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
  12356. Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
  12357. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  12358. return ExprError();
  12359. if (CheckFunctionCall(Method, TheCall,
  12360. Method->getType()->castAs<FunctionProtoType>()))
  12361. return ExprError();
  12362. return MaybeBindToTemporary(TheCall);
  12363. }
  12364. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  12365. /// a literal operator described by the provided lookup results.
  12366. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  12367. DeclarationNameInfo &SuffixInfo,
  12368. ArrayRef<Expr*> Args,
  12369. SourceLocation LitEndLoc,
  12370. TemplateArgumentListInfo *TemplateArgs) {
  12371. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  12372. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  12373. OverloadCandidateSet::CSK_Normal);
  12374. AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
  12375. TemplateArgs);
  12376. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  12377. // Perform overload resolution. This will usually be trivial, but might need
  12378. // to perform substitutions for a literal operator template.
  12379. OverloadCandidateSet::iterator Best;
  12380. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  12381. case OR_Success:
  12382. case OR_Deleted:
  12383. break;
  12384. case OR_No_Viable_Function:
  12385. CandidateSet.NoteCandidates(
  12386. PartialDiagnosticAt(UDSuffixLoc,
  12387. PDiag(diag::err_ovl_no_viable_function_in_call)
  12388. << R.getLookupName()),
  12389. *this, OCD_AllCandidates, Args);
  12390. return ExprError();
  12391. case OR_Ambiguous:
  12392. CandidateSet.NoteCandidates(
  12393. PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
  12394. << R.getLookupName()),
  12395. *this, OCD_ViableCandidates, Args);
  12396. return ExprError();
  12397. }
  12398. FunctionDecl *FD = Best->Function;
  12399. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  12400. nullptr, HadMultipleCandidates,
  12401. SuffixInfo.getLoc(),
  12402. SuffixInfo.getInfo());
  12403. if (Fn.isInvalid())
  12404. return true;
  12405. // Check the argument types. This should almost always be a no-op, except
  12406. // that array-to-pointer decay is applied to string literals.
  12407. Expr *ConvArgs[2];
  12408. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  12409. ExprResult InputInit = PerformCopyInitialization(
  12410. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  12411. SourceLocation(), Args[ArgIdx]);
  12412. if (InputInit.isInvalid())
  12413. return true;
  12414. ConvArgs[ArgIdx] = InputInit.get();
  12415. }
  12416. QualType ResultTy = FD->getReturnType();
  12417. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  12418. ResultTy = ResultTy.getNonLValueExprType(Context);
  12419. UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
  12420. Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
  12421. VK, LitEndLoc, UDSuffixLoc);
  12422. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  12423. return ExprError();
  12424. if (CheckFunctionCall(FD, UDL, nullptr))
  12425. return ExprError();
  12426. return MaybeBindToTemporary(UDL);
  12427. }
  12428. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  12429. /// given LookupResult is non-empty, it is assumed to describe a member which
  12430. /// will be invoked. Otherwise, the function will be found via argument
  12431. /// dependent lookup.
  12432. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  12433. /// otherwise CallExpr is set to ExprError() and some non-success value
  12434. /// is returned.
  12435. Sema::ForRangeStatus
  12436. Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
  12437. SourceLocation RangeLoc,
  12438. const DeclarationNameInfo &NameInfo,
  12439. LookupResult &MemberLookup,
  12440. OverloadCandidateSet *CandidateSet,
  12441. Expr *Range, ExprResult *CallExpr) {
  12442. Scope *S = nullptr;
  12443. CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
  12444. if (!MemberLookup.empty()) {
  12445. ExprResult MemberRef =
  12446. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  12447. /*IsPtr=*/false, CXXScopeSpec(),
  12448. /*TemplateKWLoc=*/SourceLocation(),
  12449. /*FirstQualifierInScope=*/nullptr,
  12450. MemberLookup,
  12451. /*TemplateArgs=*/nullptr, S);
  12452. if (MemberRef.isInvalid()) {
  12453. *CallExpr = ExprError();
  12454. return FRS_DiagnosticIssued;
  12455. }
  12456. *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  12457. if (CallExpr->isInvalid()) {
  12458. *CallExpr = ExprError();
  12459. return FRS_DiagnosticIssued;
  12460. }
  12461. } else {
  12462. UnresolvedSet<0> FoundNames;
  12463. UnresolvedLookupExpr *Fn =
  12464. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  12465. NestedNameSpecifierLoc(), NameInfo,
  12466. /*NeedsADL=*/true, /*Overloaded=*/false,
  12467. FoundNames.begin(), FoundNames.end());
  12468. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  12469. CandidateSet, CallExpr);
  12470. if (CandidateSet->empty() || CandidateSetError) {
  12471. *CallExpr = ExprError();
  12472. return FRS_NoViableFunction;
  12473. }
  12474. OverloadCandidateSet::iterator Best;
  12475. OverloadingResult OverloadResult =
  12476. CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
  12477. if (OverloadResult == OR_No_Viable_Function) {
  12478. *CallExpr = ExprError();
  12479. return FRS_NoViableFunction;
  12480. }
  12481. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  12482. Loc, nullptr, CandidateSet, &Best,
  12483. OverloadResult,
  12484. /*AllowTypoCorrection=*/false);
  12485. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  12486. *CallExpr = ExprError();
  12487. return FRS_DiagnosticIssued;
  12488. }
  12489. }
  12490. return FRS_Success;
  12491. }
  12492. /// FixOverloadedFunctionReference - E is an expression that refers to
  12493. /// a C++ overloaded function (possibly with some parentheses and
  12494. /// perhaps a '&' around it). We have resolved the overloaded function
  12495. /// to the function declaration Fn, so patch up the expression E to
  12496. /// refer (possibly indirectly) to Fn. Returns the new expr.
  12497. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  12498. FunctionDecl *Fn) {
  12499. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  12500. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  12501. Found, Fn);
  12502. if (SubExpr == PE->getSubExpr())
  12503. return PE;
  12504. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  12505. }
  12506. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  12507. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  12508. Found, Fn);
  12509. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  12510. SubExpr->getType()) &&
  12511. "Implicit cast type cannot be determined from overload");
  12512. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  12513. if (SubExpr == ICE->getSubExpr())
  12514. return ICE;
  12515. return ImplicitCastExpr::Create(Context, ICE->getType(),
  12516. ICE->getCastKind(),
  12517. SubExpr, nullptr,
  12518. ICE->getValueKind());
  12519. }
  12520. if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  12521. if (!GSE->isResultDependent()) {
  12522. Expr *SubExpr =
  12523. FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
  12524. if (SubExpr == GSE->getResultExpr())
  12525. return GSE;
  12526. // Replace the resulting type information before rebuilding the generic
  12527. // selection expression.
  12528. ArrayRef<Expr *> A = GSE->getAssocExprs();
  12529. SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
  12530. unsigned ResultIdx = GSE->getResultIndex();
  12531. AssocExprs[ResultIdx] = SubExpr;
  12532. return GenericSelectionExpr::Create(
  12533. Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
  12534. GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
  12535. GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
  12536. ResultIdx);
  12537. }
  12538. // Rather than fall through to the unreachable, return the original generic
  12539. // selection expression.
  12540. return GSE;
  12541. }
  12542. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  12543. assert(UnOp->getOpcode() == UO_AddrOf &&
  12544. "Can only take the address of an overloaded function");
  12545. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  12546. if (Method->isStatic()) {
  12547. // Do nothing: static member functions aren't any different
  12548. // from non-member functions.
  12549. } else {
  12550. // Fix the subexpression, which really has to be an
  12551. // UnresolvedLookupExpr holding an overloaded member function
  12552. // or template.
  12553. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  12554. Found, Fn);
  12555. if (SubExpr == UnOp->getSubExpr())
  12556. return UnOp;
  12557. assert(isa<DeclRefExpr>(SubExpr)
  12558. && "fixed to something other than a decl ref");
  12559. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  12560. && "fixed to a member ref with no nested name qualifier");
  12561. // We have taken the address of a pointer to member
  12562. // function. Perform the computation here so that we get the
  12563. // appropriate pointer to member type.
  12564. QualType ClassType
  12565. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  12566. QualType MemPtrType
  12567. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  12568. // Under the MS ABI, lock down the inheritance model now.
  12569. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  12570. (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
  12571. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  12572. VK_RValue, OK_Ordinary,
  12573. UnOp->getOperatorLoc(), false);
  12574. }
  12575. }
  12576. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  12577. Found, Fn);
  12578. if (SubExpr == UnOp->getSubExpr())
  12579. return UnOp;
  12580. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  12581. Context.getPointerType(SubExpr->getType()),
  12582. VK_RValue, OK_Ordinary,
  12583. UnOp->getOperatorLoc(), false);
  12584. }
  12585. // C++ [except.spec]p17:
  12586. // An exception-specification is considered to be needed when:
  12587. // - in an expression the function is the unique lookup result or the
  12588. // selected member of a set of overloaded functions
  12589. if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
  12590. ResolveExceptionSpec(E->getExprLoc(), FPT);
  12591. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  12592. // FIXME: avoid copy.
  12593. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  12594. if (ULE->hasExplicitTemplateArgs()) {
  12595. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  12596. TemplateArgs = &TemplateArgsBuffer;
  12597. }
  12598. DeclRefExpr *DRE =
  12599. BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
  12600. ULE->getQualifierLoc(), Found.getDecl(),
  12601. ULE->getTemplateKeywordLoc(), TemplateArgs);
  12602. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  12603. return DRE;
  12604. }
  12605. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  12606. // FIXME: avoid copy.
  12607. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  12608. if (MemExpr->hasExplicitTemplateArgs()) {
  12609. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  12610. TemplateArgs = &TemplateArgsBuffer;
  12611. }
  12612. Expr *Base;
  12613. // If we're filling in a static method where we used to have an
  12614. // implicit member access, rewrite to a simple decl ref.
  12615. if (MemExpr->isImplicitAccess()) {
  12616. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  12617. DeclRefExpr *DRE = BuildDeclRefExpr(
  12618. Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
  12619. MemExpr->getQualifierLoc(), Found.getDecl(),
  12620. MemExpr->getTemplateKeywordLoc(), TemplateArgs);
  12621. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  12622. return DRE;
  12623. } else {
  12624. SourceLocation Loc = MemExpr->getMemberLoc();
  12625. if (MemExpr->getQualifier())
  12626. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  12627. Base =
  12628. BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
  12629. }
  12630. } else
  12631. Base = MemExpr->getBase();
  12632. ExprValueKind valueKind;
  12633. QualType type;
  12634. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  12635. valueKind = VK_LValue;
  12636. type = Fn->getType();
  12637. } else {
  12638. valueKind = VK_RValue;
  12639. type = Context.BoundMemberTy;
  12640. }
  12641. return BuildMemberExpr(
  12642. Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  12643. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  12644. /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
  12645. type, valueKind, OK_Ordinary, TemplateArgs);
  12646. }
  12647. llvm_unreachable("Invalid reference to overloaded function");
  12648. }
  12649. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  12650. DeclAccessPair Found,
  12651. FunctionDecl *Fn) {
  12652. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  12653. }