SemaOverload.cpp 507 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703
  1. //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file provides Sema routines for C++ overloading.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/Overload.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/TypeOrdering.h"
  21. #include "clang/Basic/Diagnostic.h"
  22. #include "clang/Basic/DiagnosticOptions.h"
  23. #include "clang/Basic/PartialDiagnostic.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/SemaInternal.h"
  28. #include "clang/Sema/Template.h"
  29. #include "clang/Sema/TemplateDeduction.h"
  30. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  31. #include "llvm/ADT/DenseSet.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include <algorithm>
  36. #include <cstdlib>
  37. using namespace clang;
  38. using namespace sema;
  39. /// A convenience routine for creating a decayed reference to a function.
  40. static ExprResult
  41. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
  42. bool HadMultipleCandidates,
  43. SourceLocation Loc = SourceLocation(),
  44. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  45. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  46. return ExprError();
  47. // If FoundDecl is different from Fn (such as if one is a template
  48. // and the other a specialization), make sure DiagnoseUseOfDecl is
  49. // called on both.
  50. // FIXME: This would be more comprehensively addressed by modifying
  51. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  52. // being used.
  53. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  54. return ExprError();
  55. DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
  56. VK_LValue, Loc, LocInfo);
  57. if (HadMultipleCandidates)
  58. DRE->setHadMultipleCandidates(true);
  59. S.MarkDeclRefReferenced(DRE);
  60. ExprResult E = DRE;
  61. E = S.DefaultFunctionArrayConversion(E.get());
  62. if (E.isInvalid())
  63. return ExprError();
  64. return E;
  65. }
  66. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  67. bool InOverloadResolution,
  68. StandardConversionSequence &SCS,
  69. bool CStyle,
  70. bool AllowObjCWritebackConversion);
  71. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  72. QualType &ToType,
  73. bool InOverloadResolution,
  74. StandardConversionSequence &SCS,
  75. bool CStyle);
  76. static OverloadingResult
  77. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  78. UserDefinedConversionSequence& User,
  79. OverloadCandidateSet& Conversions,
  80. bool AllowExplicit,
  81. bool AllowObjCConversionOnExplicit);
  82. static ImplicitConversionSequence::CompareKind
  83. CompareStandardConversionSequences(Sema &S,
  84. const StandardConversionSequence& SCS1,
  85. const StandardConversionSequence& SCS2);
  86. static ImplicitConversionSequence::CompareKind
  87. CompareQualificationConversions(Sema &S,
  88. const StandardConversionSequence& SCS1,
  89. const StandardConversionSequence& SCS2);
  90. static ImplicitConversionSequence::CompareKind
  91. CompareDerivedToBaseConversions(Sema &S,
  92. const StandardConversionSequence& SCS1,
  93. const StandardConversionSequence& SCS2);
  94. /// GetConversionRank - Retrieve the implicit conversion rank
  95. /// corresponding to the given implicit conversion kind.
  96. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  97. static const ImplicitConversionRank
  98. Rank[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  99. ICR_Exact_Match,
  100. ICR_Exact_Match,
  101. ICR_Exact_Match,
  102. ICR_Exact_Match,
  103. ICR_Exact_Match,
  104. ICR_Exact_Match,
  105. ICR_Promotion,
  106. ICR_Promotion,
  107. ICR_Promotion,
  108. ICR_Conversion,
  109. ICR_Conversion,
  110. ICR_Conversion,
  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_Complex_Real_Conversion,
  120. ICR_Conversion,
  121. ICR_Conversion,
  122. ICR_Writeback_Conversion
  123. // HLSL Change Starts: missing from original
  124. ,ICR_Conversion,
  125. // HLSL Change: new entries
  126. ICR_Conversion,
  127. ICR_Conversion,
  128. ICR_Conversion,
  129. ICR_Conversion,
  130. ICR_Conversion,
  131. ICR_Conversion,
  132. // HLSL Change Ends
  133. };
  134. static_assert(_countof(Rank) == ICK_Num_Conversion_Kinds,
  135. "Otherwise, GetConversionRank is out of sync with ImplicitConversionKind"); // HLSL Change
  136. assert((int)Kind < (int)ICK_Num_Conversion_Kinds); // HLSL Change
  137. return Rank[(int)Kind];
  138. }
  139. /// GetImplicitConversionName - Return the name of this kind of
  140. /// implicit conversion.
  141. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  142. static const char* const Name[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  143. "No conversion",
  144. "Lvalue-to-rvalue",
  145. "Array-to-pointer",
  146. "Function-to-pointer",
  147. "Noreturn adjustment",
  148. "Qualification",
  149. "Integral promotion",
  150. "Floating point promotion",
  151. "Complex promotion",
  152. "Integral conversion",
  153. "Floating conversion",
  154. "Complex conversion",
  155. "Floating-integral conversion",
  156. "Pointer conversion",
  157. "Pointer-to-member conversion",
  158. "Boolean conversion",
  159. "Compatible-types conversion",
  160. "Derived-to-base conversion",
  161. "Vector conversion",
  162. "Vector splat",
  163. "Complex-real conversion",
  164. "Block Pointer conversion",
  165. "Transparent Union Conversion",
  166. "Writeback conversion"
  167. // HLSL Change Starts
  168. ,"Zero constant to event conversion", // HLSL Change: missing value
  169. // HLSL Change: new values
  170. "HLSLVector/Matrix to scalar",
  171. "HLSLVector/Matrix conversion",
  172. "Flat assignment conversion",
  173. "HLSLVector/Matrix splat",
  174. "HLSLVector/Matrix truncation",
  175. "HLSL derived to base",
  176. // HLSL Change Ends
  177. };
  178. static_assert(_countof(Name) == ICK_Num_Conversion_Kinds,
  179. "Otherwise, GetImplicitConversionName is out of sync with ImplicitConversionKind"); // HLSL Change
  180. return Name[Kind];
  181. }
  182. /// StandardConversionSequence - Set the standard conversion
  183. /// sequence to the identity conversion.
  184. void StandardConversionSequence::setAsIdentityConversion() {
  185. First = ICK_Identity;
  186. Second = ICK_Identity;
  187. Third = ICK_Identity;
  188. DeprecatedStringLiteralToCharPtr = false;
  189. QualificationIncludesObjCLifetime = false;
  190. ReferenceBinding = false;
  191. DirectBinding = false;
  192. IsLvalueReference = true;
  193. BindsToFunctionLvalue = false;
  194. BindsToRvalue = false;
  195. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  196. ObjCLifetimeConversionBinding = false;
  197. CopyConstructor = nullptr;
  198. }
  199. /// getRank - Retrieve the rank of this standard conversion sequence
  200. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  201. /// implicit conversions.
  202. ImplicitConversionRank StandardConversionSequence::getRank() const {
  203. ImplicitConversionRank Rank = ICR_Exact_Match;
  204. if (GetConversionRank(First) > Rank)
  205. Rank = GetConversionRank(First);
  206. if (GetConversionRank(Second) > Rank)
  207. Rank = GetConversionRank(Second);
  208. if (GetConversionRank(ComponentConversion) > Rank) // HLSL Change
  209. Rank = GetConversionRank(ComponentConversion);
  210. if (GetConversionRank(Third) > Rank)
  211. Rank = GetConversionRank(Third);
  212. return Rank;
  213. }
  214. /// isPointerConversionToBool - Determines whether this conversion is
  215. /// a conversion of a pointer or pointer-to-member to bool. This is
  216. /// used as part of the ranking of standard conversion sequences
  217. /// (C++ 13.3.3.2p4).
  218. bool StandardConversionSequence::isPointerConversionToBool() const {
  219. // Note that FromType has not necessarily been transformed by the
  220. // array-to-pointer or function-to-pointer implicit conversions, so
  221. // check for their presence as well as checking whether FromType is
  222. // a pointer.
  223. if (getToType(1)->isBooleanType() &&
  224. (getFromType()->isPointerType() ||
  225. getFromType()->isObjCObjectPointerType() ||
  226. getFromType()->isBlockPointerType() ||
  227. getFromType()->isNullPtrType() ||
  228. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  229. return true;
  230. return false;
  231. }
  232. /// isPointerConversionToVoidPointer - Determines whether this
  233. /// conversion is a conversion of a pointer to a void pointer. This is
  234. /// used as part of the ranking of standard conversion sequences (C++
  235. /// 13.3.3.2p4).
  236. bool
  237. StandardConversionSequence::
  238. isPointerConversionToVoidPointer(ASTContext& Context) const {
  239. QualType FromType = getFromType();
  240. QualType ToType = getToType(1);
  241. // Note that FromType has not necessarily been transformed by the
  242. // array-to-pointer implicit conversion, so check for its presence
  243. // and redo the conversion to get a pointer.
  244. if (First == ICK_Array_To_Pointer)
  245. FromType = Context.getArrayDecayedType(FromType);
  246. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  247. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  248. return ToPtrType->getPointeeType()->isVoidType();
  249. return false;
  250. }
  251. /// Skip any implicit casts which could be either part of a narrowing conversion
  252. /// or after one in an implicit conversion.
  253. static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
  254. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  255. switch (ICE->getCastKind()) {
  256. case CK_NoOp:
  257. case CK_IntegralCast:
  258. case CK_IntegralToBoolean:
  259. case CK_IntegralToFloating:
  260. case CK_FloatingToIntegral:
  261. case CK_FloatingToBoolean:
  262. case CK_FloatingCast:
  263. Converted = ICE->getSubExpr();
  264. continue;
  265. default:
  266. return Converted;
  267. }
  268. }
  269. return Converted;
  270. }
  271. /// Check if this standard conversion sequence represents a narrowing
  272. /// conversion, according to C++11 [dcl.init.list]p7.
  273. ///
  274. /// \param Ctx The AST context.
  275. /// \param Converted The result of applying this standard conversion sequence.
  276. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  277. /// value of the expression prior to the narrowing conversion.
  278. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  279. /// type of the expression prior to the narrowing conversion.
  280. NarrowingKind
  281. StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
  282. const Expr *Converted,
  283. APValue &ConstantValue,
  284. QualType &ConstantType) const {
  285. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  286. // C++11 [dcl.init.list]p7:
  287. // A narrowing conversion is an implicit conversion ...
  288. QualType FromType = getToType(0);
  289. QualType ToType = getToType(1);
  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->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
  311. llvm::APSInt IntConstantValue;
  312. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  313. if (Initializer &&
  314. Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  315. // Convert the integer to the floating type.
  316. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  317. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  318. llvm::APFloat::rmNearestTiesToEven);
  319. // And back.
  320. llvm::APSInt ConvertedValue = IntConstantValue;
  321. bool ignored;
  322. Result.convertToInteger(ConvertedValue,
  323. llvm::APFloat::rmTowardZero, &ignored);
  324. // If the resulting value is different, this was a narrowing conversion.
  325. if (IntConstantValue != ConvertedValue) {
  326. ConstantValue = APValue(IntConstantValue);
  327. ConstantType = Initializer->getType();
  328. return NK_Constant_Narrowing;
  329. }
  330. } else {
  331. // Variables are always narrowings.
  332. return NK_Variable_Narrowing;
  333. }
  334. }
  335. return NK_Not_Narrowing;
  336. // -- from long double to double or float, or from double to float, except
  337. // where the source is a constant expression and the actual value after
  338. // conversion is within the range of values that can be represented (even
  339. // if it cannot be represented exactly), or
  340. case ICK_Floating_Conversion:
  341. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  342. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  343. // FromType is larger than ToType.
  344. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  345. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  346. // Constant!
  347. assert(ConstantValue.isFloat());
  348. llvm::APFloat FloatVal = ConstantValue.getFloat();
  349. // Convert the source value into the target type.
  350. bool ignored;
  351. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  352. Ctx.getFloatTypeSemantics(ToType),
  353. llvm::APFloat::rmNearestTiesToEven, &ignored);
  354. // If there was no overflow, the source value is within the range of
  355. // values that can be represented.
  356. if (ConvertStatus & llvm::APFloat::opOverflow) {
  357. ConstantType = Initializer->getType();
  358. return NK_Constant_Narrowing;
  359. }
  360. } else {
  361. return NK_Variable_Narrowing;
  362. }
  363. }
  364. return NK_Not_Narrowing;
  365. // -- from an integer type or unscoped enumeration type to an integer type
  366. // that cannot represent all the values of the original type, except where
  367. // the source is a constant expression and the actual value after
  368. // conversion will fit into the target type and will produce the original
  369. // value when converted back to the original type.
  370. case ICK_Integral_Conversion:
  371. IntegralConversion: {
  372. assert(FromType->isIntegralOrUnscopedEnumerationType());
  373. assert(ToType->isIntegralOrUnscopedEnumerationType());
  374. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  375. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  376. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  377. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  378. if (FromWidth > ToWidth ||
  379. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  380. (FromSigned && !ToSigned)) {
  381. // Not all values of FromType can be represented in ToType.
  382. llvm::APSInt InitializerValue;
  383. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  384. if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  385. // Such conversions on variables are always narrowing.
  386. return NK_Variable_Narrowing;
  387. }
  388. bool Narrowing = false;
  389. if (FromWidth < ToWidth) {
  390. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  391. // narrowing.
  392. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  393. Narrowing = true;
  394. } else {
  395. // Add a bit to the InitializerValue so we don't have to worry about
  396. // signed vs. unsigned comparisons.
  397. InitializerValue = InitializerValue.extend(
  398. InitializerValue.getBitWidth() + 1);
  399. // Convert the initializer to and from the target width and signed-ness.
  400. llvm::APSInt ConvertedValue = InitializerValue;
  401. ConvertedValue = ConvertedValue.trunc(ToWidth);
  402. ConvertedValue.setIsSigned(ToSigned);
  403. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  404. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  405. // If the result is different, this was a narrowing conversion.
  406. if (ConvertedValue != InitializerValue)
  407. Narrowing = true;
  408. }
  409. if (Narrowing) {
  410. ConstantType = Initializer->getType();
  411. ConstantValue = APValue(InitializerValue);
  412. return NK_Constant_Narrowing;
  413. }
  414. }
  415. return NK_Not_Narrowing;
  416. }
  417. default:
  418. // Other kinds of conversions are not narrowings.
  419. return NK_Not_Narrowing;
  420. }
  421. }
  422. /// dump - Print this standard conversion sequence to standard
  423. /// error. Useful for debugging overloading issues.
  424. void StandardConversionSequence::dump() const {
  425. raw_ostream &OS = llvm::errs();
  426. bool PrintedSomething = false;
  427. if (First != ICK_Identity) {
  428. OS << GetImplicitConversionName(First);
  429. PrintedSomething = true;
  430. }
  431. if (Second != ICK_Identity) {
  432. if (PrintedSomething) {
  433. OS << " -> ";
  434. }
  435. OS << GetImplicitConversionName(Second);
  436. if (CopyConstructor) {
  437. OS << " (by copy constructor)";
  438. } else if (DirectBinding) {
  439. OS << " (direct reference binding)";
  440. } else if (ReferenceBinding) {
  441. OS << " (reference binding)";
  442. }
  443. PrintedSomething = true;
  444. }
  445. // HLSL Change Starts
  446. if (ComponentConversion != ICK_Identity) {
  447. if (PrintedSomething) {
  448. OS << " -> ";
  449. }
  450. OS << GetImplicitConversionName(ComponentConversion);
  451. PrintedSomething = true;
  452. }
  453. // HLSL Change Ends
  454. if (Third != ICK_Identity) {
  455. if (PrintedSomething) {
  456. OS << " -> ";
  457. }
  458. OS << GetImplicitConversionName(Third);
  459. PrintedSomething = true;
  460. }
  461. if (!PrintedSomething) {
  462. OS << "No conversions required";
  463. }
  464. }
  465. /// dump - Print this user-defined conversion sequence to standard
  466. /// error. Useful for debugging overloading issues.
  467. void UserDefinedConversionSequence::dump() const {
  468. raw_ostream &OS = llvm::errs();
  469. if (Before.First || Before.Second || Before.Third) {
  470. Before.dump();
  471. OS << " -> ";
  472. }
  473. if (ConversionFunction)
  474. OS << '\'' << *ConversionFunction << '\'';
  475. else
  476. OS << "aggregate initialization";
  477. if (After.First || After.Second || After.Third) {
  478. OS << " -> ";
  479. After.dump();
  480. }
  481. }
  482. /// dump - Print this implicit conversion sequence to standard
  483. /// error. Useful for debugging overloading issues.
  484. void ImplicitConversionSequence::dump() const {
  485. raw_ostream &OS = llvm::errs();
  486. if (isStdInitializerListElement())
  487. OS << "Worst std::initializer_list element conversion: ";
  488. switch (ConversionKind) {
  489. case StandardConversion:
  490. OS << "Standard conversion: ";
  491. Standard.dump();
  492. break;
  493. case UserDefinedConversion:
  494. OS << "User-defined conversion: ";
  495. UserDefined.dump();
  496. break;
  497. case EllipsisConversion:
  498. OS << "Ellipsis conversion";
  499. break;
  500. case AmbiguousConversion:
  501. OS << "Ambiguous conversion";
  502. break;
  503. case BadConversion:
  504. OS << "Bad conversion";
  505. break;
  506. }
  507. OS << "\n";
  508. }
  509. void AmbiguousConversionSequence::construct() {
  510. new (&conversions()) ConversionSet();
  511. }
  512. void AmbiguousConversionSequence::destruct() {
  513. conversions().~ConversionSet();
  514. }
  515. void
  516. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  517. FromTypePtr = O.FromTypePtr;
  518. ToTypePtr = O.ToTypePtr;
  519. new (&conversions()) ConversionSet(O.conversions());
  520. }
  521. namespace {
  522. // Structure used by DeductionFailureInfo to store
  523. // template argument information.
  524. struct DFIArguments {
  525. TemplateArgument FirstArg;
  526. TemplateArgument SecondArg;
  527. };
  528. // Structure used by DeductionFailureInfo to store
  529. // template parameter and template argument information.
  530. struct DFIParamWithArguments : DFIArguments {
  531. TemplateParameter Param;
  532. };
  533. }
  534. /// \brief Convert from Sema's representation of template deduction information
  535. /// to the form used in overload-candidate information.
  536. DeductionFailureInfo
  537. clang::MakeDeductionFailureInfo(ASTContext &Context,
  538. Sema::TemplateDeductionResult TDK,
  539. TemplateDeductionInfo &Info) {
  540. DeductionFailureInfo Result;
  541. Result.Result = static_cast<unsigned>(TDK);
  542. Result.HasDiagnostic = false;
  543. Result.Data = nullptr;
  544. switch (TDK) {
  545. case Sema::TDK_Success:
  546. case Sema::TDK_Invalid:
  547. case Sema::TDK_InstantiationDepth:
  548. case Sema::TDK_TooManyArguments:
  549. case Sema::TDK_TooFewArguments:
  550. break;
  551. case Sema::TDK_Incomplete:
  552. case Sema::TDK_InvalidExplicitArguments:
  553. Result.Data = Info.Param.getOpaqueValue();
  554. break;
  555. case Sema::TDK_NonDeducedMismatch: {
  556. // FIXME: Should allocate from normal heap so that we can free this later.
  557. DFIArguments *Saved = new (Context) DFIArguments;
  558. Saved->FirstArg = Info.FirstArg;
  559. Saved->SecondArg = Info.SecondArg;
  560. Result.Data = Saved;
  561. break;
  562. }
  563. case Sema::TDK_Inconsistent:
  564. case Sema::TDK_Underqualified: {
  565. // FIXME: Should allocate from normal heap so that we can free this later.
  566. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  567. Saved->Param = Info.Param;
  568. Saved->FirstArg = Info.FirstArg;
  569. Saved->SecondArg = Info.SecondArg;
  570. Result.Data = Saved;
  571. break;
  572. }
  573. case Sema::TDK_SubstitutionFailure:
  574. Result.Data = Info.take();
  575. if (Info.hasSFINAEDiagnostic()) {
  576. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  577. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  578. Info.takeSFINAEDiagnostic(*Diag);
  579. Result.HasDiagnostic = true;
  580. }
  581. break;
  582. case Sema::TDK_FailedOverloadResolution:
  583. Result.Data = Info.Expression;
  584. break;
  585. case Sema::TDK_MiscellaneousDeductionFailure:
  586. break;
  587. }
  588. return Result;
  589. }
  590. void DeductionFailureInfo::Destroy() {
  591. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  592. case Sema::TDK_Success:
  593. case Sema::TDK_Invalid:
  594. case Sema::TDK_InstantiationDepth:
  595. case Sema::TDK_Incomplete:
  596. case Sema::TDK_TooManyArguments:
  597. case Sema::TDK_TooFewArguments:
  598. case Sema::TDK_InvalidExplicitArguments:
  599. case Sema::TDK_FailedOverloadResolution:
  600. break;
  601. case Sema::TDK_Inconsistent:
  602. case Sema::TDK_Underqualified:
  603. case Sema::TDK_NonDeducedMismatch:
  604. // FIXME: Destroy the data?
  605. Data = nullptr;
  606. break;
  607. case Sema::TDK_SubstitutionFailure:
  608. // FIXME: Destroy the template argument list?
  609. Data = nullptr;
  610. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  611. Diag->~PartialDiagnosticAt();
  612. HasDiagnostic = false;
  613. }
  614. break;
  615. // Unhandled
  616. case Sema::TDK_MiscellaneousDeductionFailure:
  617. break;
  618. }
  619. }
  620. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  621. if (HasDiagnostic)
  622. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  623. return nullptr;
  624. }
  625. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  626. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  627. case Sema::TDK_Success:
  628. case Sema::TDK_Invalid:
  629. case Sema::TDK_InstantiationDepth:
  630. case Sema::TDK_TooManyArguments:
  631. case Sema::TDK_TooFewArguments:
  632. case Sema::TDK_SubstitutionFailure:
  633. case Sema::TDK_NonDeducedMismatch:
  634. case Sema::TDK_FailedOverloadResolution:
  635. return TemplateParameter();
  636. case Sema::TDK_Incomplete:
  637. case Sema::TDK_InvalidExplicitArguments:
  638. return TemplateParameter::getFromOpaqueValue(Data);
  639. case Sema::TDK_Inconsistent:
  640. case Sema::TDK_Underqualified:
  641. return static_cast<DFIParamWithArguments*>(Data)->Param;
  642. // Unhandled
  643. case Sema::TDK_MiscellaneousDeductionFailure:
  644. break;
  645. }
  646. return TemplateParameter();
  647. }
  648. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  649. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  650. case Sema::TDK_Success:
  651. case Sema::TDK_Invalid:
  652. case Sema::TDK_InstantiationDepth:
  653. case Sema::TDK_TooManyArguments:
  654. case Sema::TDK_TooFewArguments:
  655. case Sema::TDK_Incomplete:
  656. case Sema::TDK_InvalidExplicitArguments:
  657. case Sema::TDK_Inconsistent:
  658. case Sema::TDK_Underqualified:
  659. case Sema::TDK_NonDeducedMismatch:
  660. case Sema::TDK_FailedOverloadResolution:
  661. return nullptr;
  662. case Sema::TDK_SubstitutionFailure:
  663. return static_cast<TemplateArgumentList*>(Data);
  664. // Unhandled
  665. case Sema::TDK_MiscellaneousDeductionFailure:
  666. break;
  667. }
  668. return nullptr;
  669. }
  670. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  671. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  672. case Sema::TDK_Success:
  673. case Sema::TDK_Invalid:
  674. case Sema::TDK_InstantiationDepth:
  675. case Sema::TDK_Incomplete:
  676. case Sema::TDK_TooManyArguments:
  677. case Sema::TDK_TooFewArguments:
  678. case Sema::TDK_InvalidExplicitArguments:
  679. case Sema::TDK_SubstitutionFailure:
  680. case Sema::TDK_FailedOverloadResolution:
  681. return nullptr;
  682. case Sema::TDK_Inconsistent:
  683. case Sema::TDK_Underqualified:
  684. case Sema::TDK_NonDeducedMismatch:
  685. return &static_cast<DFIArguments*>(Data)->FirstArg;
  686. // Unhandled
  687. case Sema::TDK_MiscellaneousDeductionFailure:
  688. break;
  689. }
  690. return nullptr;
  691. }
  692. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  693. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  694. case Sema::TDK_Success:
  695. case Sema::TDK_Invalid:
  696. case Sema::TDK_InstantiationDepth:
  697. case Sema::TDK_Incomplete:
  698. case Sema::TDK_TooManyArguments:
  699. case Sema::TDK_TooFewArguments:
  700. case Sema::TDK_InvalidExplicitArguments:
  701. case Sema::TDK_SubstitutionFailure:
  702. case Sema::TDK_FailedOverloadResolution:
  703. return nullptr;
  704. case Sema::TDK_Inconsistent:
  705. case Sema::TDK_Underqualified:
  706. case Sema::TDK_NonDeducedMismatch:
  707. return &static_cast<DFIArguments*>(Data)->SecondArg;
  708. // Unhandled
  709. case Sema::TDK_MiscellaneousDeductionFailure:
  710. break;
  711. }
  712. return nullptr;
  713. }
  714. Expr *DeductionFailureInfo::getExpr() {
  715. if (static_cast<Sema::TemplateDeductionResult>(Result) ==
  716. Sema::TDK_FailedOverloadResolution)
  717. return static_cast<Expr*>(Data);
  718. return nullptr;
  719. }
  720. void OverloadCandidateSet::destroyCandidates() {
  721. for (iterator i = begin(), e = end(); i != e; ++i) {
  722. for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
  723. i->Conversions[ii].~ImplicitConversionSequence();
  724. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  725. i->DeductionFailure.Destroy();
  726. }
  727. }
  728. void OverloadCandidateSet::clear() {
  729. destroyCandidates();
  730. NumInlineSequences = 0;
  731. Candidates.clear();
  732. Functions.clear();
  733. }
  734. namespace {
  735. class UnbridgedCastsSet {
  736. struct Entry {
  737. Expr **Addr;
  738. Expr *Saved;
  739. };
  740. SmallVector<Entry, 2> Entries;
  741. public:
  742. void save(Sema &S, Expr *&E) {
  743. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  744. Entry entry = { &E, E };
  745. Entries.push_back(entry);
  746. E = S.stripARCUnbridgedCast(E);
  747. }
  748. void restore() {
  749. for (SmallVectorImpl<Entry>::iterator
  750. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  751. *i->Addr = i->Saved;
  752. }
  753. };
  754. }
  755. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  756. /// preprocessing on the given expression.
  757. ///
  758. /// \param unbridgedCasts a collection to which to add unbridged casts;
  759. /// without this, they will be immediately diagnosed as errors
  760. ///
  761. /// Return true on unrecoverable error.
  762. static bool
  763. checkPlaceholderForOverload(Sema &S, Expr *&E,
  764. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  765. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  766. // We can't handle overloaded expressions here because overload
  767. // resolution might reasonably tweak them.
  768. if (placeholder->getKind() == BuiltinType::Overload) return false;
  769. // If the context potentially accepts unbridged ARC casts, strip
  770. // the unbridged cast and add it to the collection for later restoration.
  771. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  772. unbridgedCasts) {
  773. unbridgedCasts->save(S, E);
  774. return false;
  775. }
  776. // Go ahead and check everything else.
  777. ExprResult result = S.CheckPlaceholderExpr(E);
  778. if (result.isInvalid())
  779. return true;
  780. E = result.get();
  781. return false;
  782. }
  783. // Nothing to do.
  784. return false;
  785. }
  786. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  787. /// placeholders.
  788. static bool checkArgPlaceholdersForOverload(Sema &S,
  789. MultiExprArg Args,
  790. UnbridgedCastsSet &unbridged) {
  791. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  792. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  793. return true;
  794. return false;
  795. }
  796. // IsOverload - Determine whether the given New declaration is an
  797. // overload of the declarations in Old. This routine returns false if
  798. // New and Old cannot be overloaded, e.g., if New has the same
  799. // signature as some function in Old (C++ 1.3.10) or if the Old
  800. // declarations aren't functions (or function templates) at all. When
  801. // it does return false, MatchedDecl will point to the decl that New
  802. // cannot be overloaded with. This decl may be a UsingShadowDecl on
  803. // top of the underlying declaration.
  804. //
  805. // Example: Given the following input:
  806. //
  807. // void f(int, float); // #1
  808. // void f(int, int); // #2
  809. // int f(int, int); // #3
  810. //
  811. // When we process #1, there is no previous declaration of "f",
  812. // so IsOverload will not be used.
  813. //
  814. // When we process #2, Old contains only the FunctionDecl for #1. By
  815. // comparing the parameter types, we see that #1 and #2 are overloaded
  816. // (since they have different signatures), so this routine returns
  817. // false; MatchedDecl is unchanged.
  818. //
  819. // When we process #3, Old is an overload set containing #1 and #2. We
  820. // compare the signatures of #3 to #1 (they're overloaded, so we do
  821. // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
  822. // identical (return types of functions are not part of the
  823. // signature), IsOverload returns false and MatchedDecl will be set to
  824. // point to the FunctionDecl for #2.
  825. //
  826. // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
  827. // into a class by a using declaration. The rules for whether to hide
  828. // shadow declarations ignore some properties which otherwise figure
  829. // into a function template's signature.
  830. Sema::OverloadKind
  831. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  832. NamedDecl *&Match, bool NewIsUsingDecl) {
  833. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  834. I != E; ++I) {
  835. NamedDecl *OldD = *I;
  836. bool OldIsUsingDecl = false;
  837. if (isa<UsingShadowDecl>(OldD)) {
  838. OldIsUsingDecl = true;
  839. // We can always introduce two using declarations into the same
  840. // context, even if they have identical signatures.
  841. if (NewIsUsingDecl) continue;
  842. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  843. }
  844. // If either declaration was introduced by a using declaration,
  845. // we'll need to use slightly different rules for matching.
  846. // Essentially, these rules are the normal rules, except that
  847. // function templates hide function templates with different
  848. // return types or template parameter lists.
  849. bool UseMemberUsingDeclRules =
  850. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  851. !New->getFriendObjectKind();
  852. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  853. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  854. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  855. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  856. continue;
  857. }
  858. if (!isa<FunctionTemplateDecl>(OldD) &&
  859. !shouldLinkPossiblyHiddenDecl(*I, New))
  860. continue;
  861. Match = *I;
  862. return Ovl_Match;
  863. }
  864. } else if (isa<UsingDecl>(OldD)) {
  865. // We can overload with these, which can show up when doing
  866. // redeclaration checks for UsingDecls.
  867. assert(Old.getLookupKind() == LookupUsingDeclName);
  868. } else if (isa<TagDecl>(OldD)) {
  869. // We can always overload with tags by hiding them.
  870. } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
  871. // Optimistically assume that an unresolved using decl will
  872. // overload; if it doesn't, we'll have to diagnose during
  873. // template instantiation.
  874. } else {
  875. // (C++ 13p1):
  876. // Only function declarations can be overloaded; object and type
  877. // declarations cannot be overloaded.
  878. Match = *I;
  879. return Ovl_NonFunction;
  880. }
  881. }
  882. return Ovl_Overload;
  883. }
  884. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  885. bool UseUsingDeclRules) {
  886. // C++ [basic.start.main]p2: This function shall not be overloaded.
  887. if (New->isMain())
  888. return false;
  889. // MSVCRT user defined entry points cannot be overloaded.
  890. if (New->isMSVCRTEntryPoint())
  891. return false;
  892. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  893. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  894. // C++ [temp.fct]p2:
  895. // A function template can be overloaded with other function templates
  896. // and with normal (non-template) functions.
  897. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  898. return true;
  899. // Is the function New an overload of the function Old?
  900. QualType OldQType = Context.getCanonicalType(Old->getType());
  901. QualType NewQType = Context.getCanonicalType(New->getType());
  902. // Compare the signatures (C++ 1.3.10) of the two functions to
  903. // determine whether they are overloads. If we find any mismatch
  904. // in the signature, they are overloads.
  905. // If either of these functions is a K&R-style function (no
  906. // prototype), then we consider them to have matching signatures.
  907. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  908. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  909. return false;
  910. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  911. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  912. // The signature of a function includes the types of its
  913. // parameters (C++ 1.3.10), which includes the presence or absence
  914. // of the ellipsis; see C++ DR 357).
  915. if (OldQType != NewQType &&
  916. (OldType->getNumParams() != NewType->getNumParams() ||
  917. OldType->isVariadic() != NewType->isVariadic() ||
  918. !FunctionParamTypesAreEqual(OldType, NewType)))
  919. return true;
  920. // C++ [temp.over.link]p4:
  921. // The signature of a function template consists of its function
  922. // signature, its return type and its template parameter list. The names
  923. // of the template parameters are significant only for establishing the
  924. // relationship between the template parameters and the rest of the
  925. // signature.
  926. //
  927. // We check the return type and template parameter lists for function
  928. // templates first; the remaining checks follow.
  929. //
  930. // However, we don't consider either of these when deciding whether
  931. // a member introduced by a shadow declaration is hidden.
  932. if (!UseUsingDeclRules && NewTemplate &&
  933. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  934. OldTemplate->getTemplateParameters(),
  935. false, TPL_TemplateMatch) ||
  936. OldType->getReturnType() != NewType->getReturnType()))
  937. return true;
  938. // If the function is a class member, its signature includes the
  939. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  940. //
  941. // As part of this, also check whether one of the member functions
  942. // is static, in which case they are not overloads (C++
  943. // 13.1p2). While not part of the definition of the signature,
  944. // this check is important to determine whether these functions
  945. // can be overloaded.
  946. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  947. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  948. if (OldMethod && NewMethod &&
  949. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  950. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  951. if (!UseUsingDeclRules &&
  952. (OldMethod->getRefQualifier() == RQ_None ||
  953. NewMethod->getRefQualifier() == RQ_None)) {
  954. // C++0x [over.load]p2:
  955. // - Member function declarations with the same name and the same
  956. // parameter-type-list as well as member function template
  957. // declarations with the same name, the same parameter-type-list, and
  958. // the same template parameter lists cannot be overloaded if any of
  959. // them, but not all, have a ref-qualifier (8.3.5).
  960. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  961. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  962. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  963. }
  964. return true;
  965. }
  966. // We may not have applied the implicit const for a constexpr member
  967. // function yet (because we haven't yet resolved whether this is a static
  968. // or non-static member function). Add it now, on the assumption that this
  969. // is a redeclaration of OldMethod.
  970. unsigned OldQuals = OldMethod->getTypeQualifiers();
  971. unsigned NewQuals = NewMethod->getTypeQualifiers();
  972. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  973. !isa<CXXConstructorDecl>(NewMethod))
  974. NewQuals |= Qualifiers::Const;
  975. // We do not allow overloading based off of '__restrict'.
  976. OldQuals &= ~Qualifiers::Restrict;
  977. NewQuals &= ~Qualifiers::Restrict;
  978. if (OldQuals != NewQuals)
  979. return true;
  980. }
  981. // enable_if attributes are an order-sensitive part of the signature.
  982. for (specific_attr_iterator<EnableIfAttr>
  983. NewI = New->specific_attr_begin<EnableIfAttr>(),
  984. NewE = New->specific_attr_end<EnableIfAttr>(),
  985. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  986. OldE = Old->specific_attr_end<EnableIfAttr>();
  987. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  988. if (NewI == NewE || OldI == OldE)
  989. return true;
  990. llvm::FoldingSetNodeID NewID, OldID;
  991. NewI->getCond()->Profile(NewID, Context, true);
  992. OldI->getCond()->Profile(OldID, Context, true);
  993. if (NewID != OldID)
  994. return true;
  995. }
  996. // The signatures match; this is not an overload.
  997. return false;
  998. }
  999. /// \brief Checks availability of the function depending on the current
  1000. /// function context. Inside an unavailable function, unavailability is ignored.
  1001. ///
  1002. /// \returns true if \arg FD is unavailable and current context is inside
  1003. /// an available function, false otherwise.
  1004. bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
  1005. return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
  1006. }
  1007. /// \brief Tries a user-defined conversion from From to ToType.
  1008. ///
  1009. /// Produces an implicit conversion sequence for when a standard conversion
  1010. /// is not an option. See TryImplicitConversion for more information.
  1011. static ImplicitConversionSequence
  1012. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1013. bool SuppressUserConversions,
  1014. bool AllowExplicit,
  1015. bool InOverloadResolution,
  1016. bool CStyle,
  1017. bool AllowObjCWritebackConversion,
  1018. bool AllowObjCConversionOnExplicit) {
  1019. ImplicitConversionSequence ICS;
  1020. if (SuppressUserConversions || S.getLangOpts().HLSL) { // HLSL Change - no user conversions
  1021. // We're not in the case above, so there is no conversion that
  1022. // we can perform.
  1023. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1024. return ICS;
  1025. }
  1026. // Attempt user-defined conversion.
  1027. OverloadCandidateSet Conversions(From->getExprLoc(),
  1028. OverloadCandidateSet::CSK_Normal);
  1029. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1030. Conversions, AllowExplicit,
  1031. AllowObjCConversionOnExplicit)) {
  1032. case OR_Success:
  1033. case OR_Deleted:
  1034. ICS.setUserDefined();
  1035. ICS.UserDefined.Before.setAsIdentityConversion();
  1036. // C++ [over.ics.user]p4:
  1037. // A conversion of an expression of class type to the same class
  1038. // type is given Exact Match rank, and a conversion of an
  1039. // expression of class type to a base class of that type is
  1040. // given Conversion rank, in spite of the fact that a copy
  1041. // constructor (i.e., a user-defined conversion function) is
  1042. // called for those cases.
  1043. if (CXXConstructorDecl *Constructor
  1044. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1045. QualType FromCanon
  1046. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1047. QualType ToCanon
  1048. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1049. if (Constructor->isCopyConstructor() &&
  1050. (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
  1051. // Turn this into a "standard" conversion sequence, so that it
  1052. // gets ranked with standard conversion sequences.
  1053. ICS.setStandard();
  1054. ICS.Standard.setAsIdentityConversion();
  1055. ICS.Standard.setFromType(From->getType());
  1056. ICS.Standard.setAllToTypes(ToType);
  1057. ICS.Standard.CopyConstructor = Constructor;
  1058. if (ToCanon != FromCanon)
  1059. ICS.Standard.Second = ICK_Derived_To_Base;
  1060. }
  1061. }
  1062. break;
  1063. case OR_Ambiguous:
  1064. ICS.setAmbiguous();
  1065. ICS.Ambiguous.setFromType(From->getType());
  1066. ICS.Ambiguous.setToType(ToType);
  1067. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1068. Cand != Conversions.end(); ++Cand)
  1069. if (Cand->Viable)
  1070. ICS.Ambiguous.addConversion(Cand->Function);
  1071. break;
  1072. // Fall through.
  1073. case OR_No_Viable_Function:
  1074. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1075. break;
  1076. }
  1077. return ICS;
  1078. }
  1079. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1080. /// from the given expression (Expr) to the given type (ToType). This
  1081. /// function returns an implicit conversion sequence that can be used
  1082. /// to perform the initialization. Given
  1083. ///
  1084. /// void f(float f);
  1085. /// void g(int i) { f(i); }
  1086. ///
  1087. /// this routine would produce an implicit conversion sequence to
  1088. /// describe the initialization of f from i, which will be a standard
  1089. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1090. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1091. //
  1092. /// Note that this routine only determines how the conversion can be
  1093. /// performed; it does not actually perform the conversion. As such,
  1094. /// it will not produce any diagnostics if no conversion is available,
  1095. /// but will instead return an implicit conversion sequence of kind
  1096. /// "BadConversion".
  1097. ///
  1098. /// If @p SuppressUserConversions, then user-defined conversions are
  1099. /// not permitted.
  1100. /// If @p AllowExplicit, then explicit user-defined conversions are
  1101. /// permitted.
  1102. ///
  1103. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1104. /// writeback conversion, which allows __autoreleasing id* parameters to
  1105. /// be initialized with __strong id* or __weak id* arguments.
  1106. static ImplicitConversionSequence
  1107. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1108. bool SuppressUserConversions,
  1109. bool AllowExplicit,
  1110. bool InOverloadResolution,
  1111. bool CStyle,
  1112. bool AllowObjCWritebackConversion,
  1113. bool AllowObjCConversionOnExplicit) {
  1114. ImplicitConversionSequence ICS;
  1115. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1116. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1117. ICS.setStandard();
  1118. return ICS;
  1119. }
  1120. if (!S.getLangOpts().CPlusPlus) {
  1121. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1122. return ICS;
  1123. }
  1124. // C++ [over.ics.user]p4:
  1125. // A conversion of an expression of class type to the same class
  1126. // type is given Exact Match rank, and a conversion of an
  1127. // expression of class type to a base class of that type is
  1128. // given Conversion rank, in spite of the fact that a copy/move
  1129. // constructor (i.e., a user-defined conversion function) is
  1130. // called for those cases.
  1131. QualType FromType = From->getType();
  1132. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1133. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1134. S.IsDerivedFrom(FromType, ToType))) {
  1135. ICS.setStandard();
  1136. ICS.Standard.setAsIdentityConversion();
  1137. ICS.Standard.setFromType(FromType);
  1138. ICS.Standard.setAllToTypes(ToType);
  1139. // We don't actually check at this point whether there is a valid
  1140. // copy/move constructor, since overloading just assumes that it
  1141. // exists. When we actually perform initialization, we'll find the
  1142. // appropriate constructor to copy the returned object, if needed.
  1143. ICS.Standard.CopyConstructor = nullptr;
  1144. // Determine whether this is considered a derived-to-base conversion.
  1145. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1146. ICS.Standard.Second = ICK_Derived_To_Base;
  1147. return ICS;
  1148. }
  1149. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1150. AllowExplicit, InOverloadResolution, CStyle,
  1151. AllowObjCWritebackConversion,
  1152. AllowObjCConversionOnExplicit);
  1153. }
  1154. ImplicitConversionSequence
  1155. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1156. bool SuppressUserConversions,
  1157. bool AllowExplicit,
  1158. bool InOverloadResolution,
  1159. bool CStyle,
  1160. bool AllowObjCWritebackConversion) {
  1161. return ::TryImplicitConversion(*this, From, ToType,
  1162. SuppressUserConversions, AllowExplicit,
  1163. InOverloadResolution, CStyle,
  1164. AllowObjCWritebackConversion,
  1165. /*AllowObjCConversionOnExplicit=*/false);
  1166. }
  1167. /// PerformImplicitConversion - Perform an implicit conversion of the
  1168. /// expression From to the type ToType. Returns the
  1169. /// converted expression. Flavor is the kind of conversion we're
  1170. /// performing, used in the error message. If @p AllowExplicit,
  1171. /// explicit user-defined conversions are permitted.
  1172. ExprResult
  1173. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1174. AssignmentAction Action, bool AllowExplicit) {
  1175. ImplicitConversionSequence ICS;
  1176. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1177. }
  1178. ExprResult
  1179. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1180. AssignmentAction Action, bool AllowExplicit,
  1181. ImplicitConversionSequence& ICS) {
  1182. if (checkPlaceholderForOverload(*this, From))
  1183. return ExprError();
  1184. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1185. bool AllowObjCWritebackConversion
  1186. = getLangOpts().ObjCAutoRefCount &&
  1187. (Action == AA_Passing || Action == AA_Sending);
  1188. if (getLangOpts().ObjC1)
  1189. CheckObjCBridgeRelatedConversions(From->getLocStart(),
  1190. ToType, From->getType(), From);
  1191. ICS = ::TryImplicitConversion(*this, From, ToType,
  1192. /*SuppressUserConversions=*/false,
  1193. AllowExplicit,
  1194. /*InOverloadResolution=*/false,
  1195. /*CStyle=*/false,
  1196. AllowObjCWritebackConversion,
  1197. /*AllowObjCConversionOnExplicit=*/false);
  1198. return PerformImplicitConversion(From, ToType, ICS, Action);
  1199. }
  1200. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1201. /// conversion that strips "noreturn" off the nested function type.
  1202. bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
  1203. QualType &ResultTy) {
  1204. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1205. return false;
  1206. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1207. // where F adds one of the following at most once:
  1208. // - a pointer
  1209. // - a member pointer
  1210. // - a block pointer
  1211. CanQualType CanTo = Context.getCanonicalType(ToType);
  1212. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1213. Type::TypeClass TyClass = CanTo->getTypeClass();
  1214. if (TyClass != CanFrom->getTypeClass()) return false;
  1215. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1216. if (TyClass == Type::Pointer) {
  1217. CanTo = CanTo.getAs<PointerType>()->getPointeeType();
  1218. CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
  1219. } else if (TyClass == Type::BlockPointer) {
  1220. CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
  1221. CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
  1222. } else if (TyClass == Type::MemberPointer) {
  1223. CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
  1224. CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
  1225. } else {
  1226. return false;
  1227. }
  1228. TyClass = CanTo->getTypeClass();
  1229. if (TyClass != CanFrom->getTypeClass()) return false;
  1230. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1231. return false;
  1232. }
  1233. const FunctionType *FromFn = cast<FunctionType>(CanFrom);
  1234. FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
  1235. if (!EInfo.getNoReturn()) return false;
  1236. FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
  1237. assert(QualType(FromFn, 0).isCanonical());
  1238. if (QualType(FromFn, 0) != CanTo) return false;
  1239. ResultTy = ToType;
  1240. return true;
  1241. }
  1242. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1243. /// vector conversion.
  1244. ///
  1245. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1246. /// conversion.
  1247. static bool IsVectorConversion(Sema &S, QualType FromType,
  1248. QualType ToType, ImplicitConversionKind &ICK) {
  1249. // We need at least one of these types to be a vector type to have a vector
  1250. // conversion.
  1251. if (!ToType->isVectorType() && !FromType->isVectorType())
  1252. return false;
  1253. // Identical types require no conversions.
  1254. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1255. return false;
  1256. // There are no conversions between extended vector types, only identity.
  1257. if (ToType->isExtVectorType()) {
  1258. // There are no conversions between extended vector types other than the
  1259. // identity conversion.
  1260. if (FromType->isExtVectorType())
  1261. return false;
  1262. // Vector splat from any arithmetic type to a vector.
  1263. if (FromType->isArithmeticType()) {
  1264. ICK = ICK_Vector_Splat;
  1265. return true;
  1266. }
  1267. }
  1268. // We can perform the conversion between vector types in the following cases:
  1269. // 1)vector types are equivalent AltiVec and GCC vector types
  1270. // 2)lax vector conversions are permitted and the vector types are of the
  1271. // same size
  1272. if (ToType->isVectorType() && FromType->isVectorType()) {
  1273. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1274. S.isLaxVectorConversion(FromType, ToType)) {
  1275. ICK = ICK_Vector_Conversion;
  1276. return true;
  1277. }
  1278. }
  1279. return false;
  1280. }
  1281. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1282. bool InOverloadResolution,
  1283. StandardConversionSequence &SCS,
  1284. bool CStyle);
  1285. /// IsStandardConversion - Determines whether there is a standard
  1286. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1287. /// expression From to the type ToType. Standard conversion sequences
  1288. /// only consider non-class types; for conversions that involve class
  1289. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1290. /// contain the standard conversion sequence required to perform this
  1291. /// conversion and this routine will return true. Otherwise, this
  1292. /// routine will return false and the value of SCS is unspecified.
  1293. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1294. bool InOverloadResolution,
  1295. StandardConversionSequence &SCS,
  1296. bool CStyle,
  1297. bool AllowObjCWritebackConversion) {
  1298. QualType FromType = From->getType();
  1299. // Standard conversions (C++ [conv])
  1300. SCS.setAsIdentityConversion();
  1301. SCS.IncompatibleObjC = false;
  1302. SCS.setFromType(FromType);
  1303. SCS.CopyConstructor = nullptr;
  1304. // HLSL Change Begins
  1305. if (S.getLangOpts().HLSL) {
  1306. return hlsl::CanConvert(&S, SourceLocation(), From, ToType, /*explicitConversion=*/false, &SCS);
  1307. }
  1308. // HLSL Change Ends
  1309. // There are no standard conversions for class types in C++, so
  1310. // abort early. When overloading in C, however, we do permit
  1311. if (FromType->isRecordType() || ToType->isRecordType()) {
  1312. if (S.getLangOpts().CPlusPlus)
  1313. return false;
  1314. // When we're overloading in C, we allow, as standard conversions,
  1315. }
  1316. // The first conversion can be an lvalue-to-rvalue conversion,
  1317. // array-to-pointer conversion, or function-to-pointer conversion
  1318. // (C++ 4p1).
  1319. if (FromType == S.Context.OverloadTy) {
  1320. DeclAccessPair AccessPair;
  1321. if (FunctionDecl *Fn
  1322. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1323. AccessPair)) {
  1324. // We were able to resolve the address of the overloaded function,
  1325. // so we can convert to the type of that function.
  1326. FromType = Fn->getType();
  1327. SCS.setFromType(FromType);
  1328. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1329. // if the type matches (identity) or we are converting to bool
  1330. if (!S.Context.hasSameUnqualifiedType(
  1331. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1332. QualType resultTy;
  1333. // if the function type matches except for [[noreturn]], it's ok
  1334. if (!S.IsNoReturnConversion(FromType,
  1335. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1336. // otherwise, only a boolean conversion is standard
  1337. if (!ToType->isBooleanType())
  1338. return false;
  1339. }
  1340. // Check if the "from" expression is taking the address of an overloaded
  1341. // function and recompute the FromType accordingly. Take advantage of the
  1342. // fact that non-static member functions *must* have such an address-of
  1343. // expression.
  1344. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1345. if (Method && !Method->isStatic()) {
  1346. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1347. "Non-unary operator on non-static member address");
  1348. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1349. == UO_AddrOf &&
  1350. "Non-address-of operator on non-static member address");
  1351. const Type *ClassType
  1352. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1353. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1354. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1355. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1356. UO_AddrOf &&
  1357. "Non-address-of operator for overloaded function expression");
  1358. FromType = S.Context.getPointerType(FromType);
  1359. }
  1360. // Check that we've computed the proper type after overload resolution.
  1361. assert(S.Context.hasSameType(
  1362. FromType,
  1363. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1364. } else {
  1365. return false;
  1366. }
  1367. }
  1368. // Lvalue-to-rvalue conversion (C++11 4.1):
  1369. // A glvalue (3.10) of a non-function, non-array type T can
  1370. // be converted to a prvalue.
  1371. bool argIsLValue = From->isGLValue();
  1372. if (argIsLValue &&
  1373. !FromType->isFunctionType() && (!FromType->isArrayType() || S.getLangOpts().HLSL) && // HLSL Change - HLSL allows arrays
  1374. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1375. SCS.First = ICK_Lvalue_To_Rvalue;
  1376. // C11 6.3.2.1p2:
  1377. // ... if the lvalue has atomic type, the value has the non-atomic version
  1378. // of the type of the lvalue ...
  1379. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1380. FromType = Atomic->getValueType();
  1381. // If T is a non-class type, the type of the rvalue is the
  1382. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1383. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1384. // just strip the qualifiers because they don't matter.
  1385. FromType = FromType.getUnqualifiedType();
  1386. } else if (FromType->isArrayType()) {
  1387. // Array-to-pointer conversion (C++ 4.2)
  1388. SCS.First = ICK_Array_To_Pointer;
  1389. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1390. // bound of T" can be converted to an rvalue of type "pointer to
  1391. // T" (C++ 4.2p1).
  1392. FromType = S.Context.getArrayDecayedType(FromType);
  1393. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1394. // This conversion is deprecated in C++03 (D.4)
  1395. SCS.DeprecatedStringLiteralToCharPtr = true;
  1396. // For the purpose of ranking in overload resolution
  1397. // (13.3.3.1.1), this conversion is considered an
  1398. // array-to-pointer conversion followed by a qualification
  1399. // conversion (4.4). (C++ 4.2p2)
  1400. SCS.Second = ICK_Identity;
  1401. SCS.Third = ICK_Qualification;
  1402. SCS.QualificationIncludesObjCLifetime = false;
  1403. SCS.setAllToTypes(FromType);
  1404. return true;
  1405. }
  1406. } else if (FromType->isFunctionType() && argIsLValue) {
  1407. // Function-to-pointer conversion (C++ 4.3).
  1408. SCS.First = ICK_Function_To_Pointer;
  1409. // An lvalue of function type T can be converted to an rvalue of
  1410. // type "pointer to T." The result is a pointer to the
  1411. // function. (C++ 4.3p1).
  1412. FromType = S.Context.getPointerType(FromType);
  1413. } else {
  1414. // We don't require any conversions for the first step.
  1415. SCS.First = ICK_Identity;
  1416. }
  1417. SCS.setToType(0, FromType);
  1418. // The second conversion can be an integral promotion, floating
  1419. // point promotion, integral conversion, floating point conversion,
  1420. // floating-integral conversion, pointer conversion,
  1421. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1422. // For overloading in C, this can also be a "compatible-type"
  1423. // conversion.
  1424. bool IncompatibleObjC = false;
  1425. ImplicitConversionKind SecondICK = ICK_Identity;
  1426. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1427. // The unqualified versions of the types are the same: there's no
  1428. // conversion to do.
  1429. SCS.Second = ICK_Identity;
  1430. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1431. // Integral promotion (C++ 4.5).
  1432. SCS.Second = ICK_Integral_Promotion;
  1433. FromType = ToType.getUnqualifiedType();
  1434. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1435. // Floating point promotion (C++ 4.6).
  1436. SCS.Second = ICK_Floating_Promotion;
  1437. FromType = ToType.getUnqualifiedType();
  1438. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1439. // Complex promotion (Clang extension)
  1440. SCS.Second = ICK_Complex_Promotion;
  1441. FromType = ToType.getUnqualifiedType();
  1442. } else if (ToType->isBooleanType() &&
  1443. (FromType->isArithmeticType() ||
  1444. FromType->isAnyPointerType() ||
  1445. FromType->isBlockPointerType() ||
  1446. FromType->isMemberPointerType() ||
  1447. FromType->isNullPtrType())) {
  1448. // Boolean conversions (C++ 4.12).
  1449. SCS.Second = ICK_Boolean_Conversion;
  1450. FromType = S.Context.BoolTy;
  1451. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1452. ToType->isIntegralType(S.Context)) {
  1453. // Integral conversions (C++ 4.7).
  1454. SCS.Second = ICK_Integral_Conversion;
  1455. FromType = ToType.getUnqualifiedType();
  1456. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1457. // Complex conversions (C99 6.3.1.6)
  1458. SCS.Second = ICK_Complex_Conversion;
  1459. FromType = ToType.getUnqualifiedType();
  1460. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1461. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1462. // Complex-real conversions (C99 6.3.1.7)
  1463. SCS.Second = ICK_Complex_Real;
  1464. FromType = ToType.getUnqualifiedType();
  1465. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1466. // Floating point conversions (C++ 4.8).
  1467. SCS.Second = ICK_Floating_Conversion;
  1468. FromType = ToType.getUnqualifiedType();
  1469. } else if ((FromType->isRealFloatingType() &&
  1470. ToType->isIntegralType(S.Context)) ||
  1471. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1472. ToType->isRealFloatingType())) {
  1473. // Floating-integral conversions (C++ 4.9).
  1474. SCS.Second = ICK_Floating_Integral;
  1475. FromType = ToType.getUnqualifiedType();
  1476. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1477. SCS.Second = ICK_Block_Pointer_Conversion;
  1478. } else if (AllowObjCWritebackConversion &&
  1479. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1480. SCS.Second = ICK_Writeback_Conversion;
  1481. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1482. FromType, IncompatibleObjC)) {
  1483. // Pointer conversions (C++ 4.10).
  1484. SCS.Second = ICK_Pointer_Conversion;
  1485. SCS.IncompatibleObjC = IncompatibleObjC;
  1486. FromType = FromType.getUnqualifiedType();
  1487. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1488. InOverloadResolution, FromType)) {
  1489. // Pointer to member conversions (4.11).
  1490. SCS.Second = ICK_Pointer_Member;
  1491. } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
  1492. SCS.Second = SecondICK;
  1493. FromType = ToType.getUnqualifiedType();
  1494. } else if (!S.getLangOpts().CPlusPlus &&
  1495. S.Context.typesAreCompatible(ToType, FromType)) {
  1496. // Compatible conversions (Clang extension for C function overloading)
  1497. SCS.Second = ICK_Compatible_Conversion;
  1498. FromType = ToType.getUnqualifiedType();
  1499. } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
  1500. // Treat a conversion that strips "noreturn" as an identity conversion.
  1501. SCS.Second = ICK_NoReturn_Adjustment;
  1502. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1503. InOverloadResolution,
  1504. SCS, CStyle)) {
  1505. SCS.Second = ICK_TransparentUnionConversion;
  1506. FromType = ToType;
  1507. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1508. CStyle)) {
  1509. // tryAtomicConversion has updated the standard conversion sequence
  1510. // appropriately.
  1511. return true;
  1512. } else if (ToType->isEventT() &&
  1513. From->isIntegerConstantExpr(S.getASTContext()) &&
  1514. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1515. SCS.Second = ICK_Zero_Event_Conversion;
  1516. FromType = ToType;
  1517. } else {
  1518. // No second conversion required.
  1519. SCS.Second = ICK_Identity;
  1520. }
  1521. SCS.setToType(1, FromType);
  1522. QualType CanonFrom;
  1523. QualType CanonTo;
  1524. // The third conversion can be a qualification conversion (C++ 4p1).
  1525. bool ObjCLifetimeConversion;
  1526. if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1527. ObjCLifetimeConversion)) {
  1528. SCS.Third = ICK_Qualification;
  1529. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1530. FromType = ToType;
  1531. CanonFrom = S.Context.getCanonicalType(FromType);
  1532. CanonTo = S.Context.getCanonicalType(ToType);
  1533. } else {
  1534. // No conversion required
  1535. SCS.Third = ICK_Identity;
  1536. // C++ [over.best.ics]p6:
  1537. // [...] Any difference in top-level cv-qualification is
  1538. // subsumed by the initialization itself and does not constitute
  1539. // a conversion. [...]
  1540. CanonFrom = S.Context.getCanonicalType(FromType);
  1541. CanonTo = S.Context.getCanonicalType(ToType);
  1542. if (CanonFrom.getLocalUnqualifiedType()
  1543. == CanonTo.getLocalUnqualifiedType() &&
  1544. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1545. FromType = ToType;
  1546. CanonFrom = CanonTo;
  1547. }
  1548. }
  1549. SCS.setToType(2, FromType);
  1550. // If we have not converted the argument type to the parameter type,
  1551. // this is a bad conversion sequence.
  1552. if (CanonFrom != CanonTo)
  1553. return false;
  1554. return true;
  1555. }
  1556. static bool
  1557. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1558. QualType &ToType,
  1559. bool InOverloadResolution,
  1560. StandardConversionSequence &SCS,
  1561. bool CStyle) {
  1562. const RecordType *UT = ToType->getAsUnionType();
  1563. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1564. return false;
  1565. // The field to initialize within the transparent union.
  1566. RecordDecl *UD = UT->getDecl();
  1567. // It's compatible if the expression matches any of the fields.
  1568. for (const auto *it : UD->fields()) {
  1569. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1570. CStyle, /*ObjCWritebackConversion=*/false)) {
  1571. ToType = it->getType();
  1572. return true;
  1573. }
  1574. }
  1575. return false;
  1576. }
  1577. /// IsIntegralPromotion - Determines whether the conversion from the
  1578. /// expression From (whose potentially-adjusted type is FromType) to
  1579. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1580. /// sets PromotedType to the promoted type.
  1581. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1582. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1583. // All integers are built-in.
  1584. if (!To) {
  1585. return false;
  1586. }
  1587. // An rvalue of type char, signed char, unsigned char, short int, or
  1588. // unsigned short int can be converted to an rvalue of type int if
  1589. // int can represent all the values of the source type; otherwise,
  1590. // the source rvalue can be converted to an rvalue of type unsigned
  1591. // int (C++ 4.5p1).
  1592. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1593. !FromType->isEnumeralType()) {
  1594. if (// We can promote any signed, promotable integer type to an int
  1595. (FromType->isSignedIntegerType() ||
  1596. // We can promote any unsigned integer type whose size is
  1597. // less than int to an int.
  1598. (!FromType->isSignedIntegerType() &&
  1599. Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
  1600. return To->getKind() == BuiltinType::Int;
  1601. }
  1602. return To->getKind() == BuiltinType::UInt;
  1603. }
  1604. // C++11 [conv.prom]p3:
  1605. // A prvalue of an unscoped enumeration type whose underlying type is not
  1606. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1607. // following types that can represent all the values of the enumeration
  1608. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1609. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1610. // long long int. If none of the types in that list can represent all the
  1611. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1612. // type can be converted to an rvalue a prvalue of the extended integer type
  1613. // with lowest integer conversion rank (4.13) greater than the rank of long
  1614. // long in which all the values of the enumeration can be represented. If
  1615. // there are two such extended types, the signed one is chosen.
  1616. // C++11 [conv.prom]p4:
  1617. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  1618. // can be converted to a prvalue of its underlying type. Moreover, if
  1619. // integral promotion can be applied to its underlying type, a prvalue of an
  1620. // unscoped enumeration type whose underlying type is fixed can also be
  1621. // converted to a prvalue of the promoted underlying type.
  1622. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1623. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1624. // provided for a scoped enumeration.
  1625. if (FromEnumType->getDecl()->isScoped())
  1626. return false;
  1627. // We can perform an integral promotion to the underlying type of the enum,
  1628. // even if that's not the promoted type. Note that the check for promoting
  1629. // the underlying type is based on the type alone, and does not consider
  1630. // the bitfield-ness of the actual source expression.
  1631. if (FromEnumType->getDecl()->isFixed()) {
  1632. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  1633. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  1634. IsIntegralPromotion(nullptr, Underlying, ToType);
  1635. }
  1636. // We have already pre-calculated the promotion type, so this is trivial.
  1637. if (ToType->isIntegerType() &&
  1638. !RequireCompleteType(From->getLocStart(), FromType, 0))
  1639. return Context.hasSameUnqualifiedType(
  1640. ToType, FromEnumType->getDecl()->getPromotionType());
  1641. }
  1642. // C++0x [conv.prom]p2:
  1643. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1644. // to an rvalue a prvalue of the first of the following types that can
  1645. // represent all the values of its underlying type: int, unsigned int,
  1646. // long int, unsigned long int, long long int, or unsigned long long int.
  1647. // If none of the types in that list can represent all the values of its
  1648. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1649. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1650. // type.
  1651. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1652. ToType->isIntegerType()) {
  1653. // Determine whether the type we're converting from is signed or
  1654. // unsigned.
  1655. bool FromIsSigned = FromType->isSignedIntegerType();
  1656. uint64_t FromSize = Context.getTypeSize(FromType);
  1657. // The types we'll try to promote to, in the appropriate
  1658. // order. Try each of these types.
  1659. QualType PromoteTypes[6] = {
  1660. Context.IntTy, Context.UnsignedIntTy,
  1661. Context.LongTy, Context.UnsignedLongTy ,
  1662. Context.LongLongTy, Context.UnsignedLongLongTy
  1663. };
  1664. for (int Idx = 0; Idx < 6; ++Idx) {
  1665. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1666. if (FromSize < ToSize ||
  1667. (FromSize == ToSize &&
  1668. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1669. // We found the type that we can promote to. If this is the
  1670. // type we wanted, we have a promotion. Otherwise, no
  1671. // promotion.
  1672. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1673. }
  1674. }
  1675. }
  1676. // An rvalue for an integral bit-field (9.6) can be converted to an
  1677. // rvalue of type int if int can represent all the values of the
  1678. // bit-field; otherwise, it can be converted to unsigned int if
  1679. // unsigned int can represent all the values of the bit-field. If
  1680. // the bit-field is larger yet, no integral promotion applies to
  1681. // it. If the bit-field has an enumerated type, it is treated as any
  1682. // other value of that type for promotion purposes (C++ 4.5p3).
  1683. // FIXME: We should delay checking of bit-fields until we actually perform the
  1684. // conversion.
  1685. if (From) {
  1686. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  1687. llvm::APSInt BitWidth;
  1688. if (FromType->isIntegralType(Context) &&
  1689. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1690. llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1691. ToSize = Context.getTypeSize(ToType);
  1692. // Are we promoting to an int from a bitfield that fits in an int?
  1693. if (BitWidth < ToSize ||
  1694. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1695. return To->getKind() == BuiltinType::Int;
  1696. }
  1697. // Are we promoting to an unsigned int from an unsigned bitfield
  1698. // that fits into an unsigned int?
  1699. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1700. return To->getKind() == BuiltinType::UInt;
  1701. }
  1702. return false;
  1703. }
  1704. }
  1705. }
  1706. // An rvalue of type bool can be converted to an rvalue of type int,
  1707. // with false becoming zero and true becoming one (C++ 4.5p4).
  1708. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1709. return true;
  1710. }
  1711. return false;
  1712. }
  1713. /// IsFloatingPointPromotion - Determines whether the conversion from
  1714. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1715. /// returns true and sets PromotedType to the promoted type.
  1716. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1717. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1718. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1719. /// An rvalue of type float can be converted to an rvalue of type
  1720. /// double. (C++ 4.6p1).
  1721. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1722. ToBuiltin->getKind() == BuiltinType::Double)
  1723. return true;
  1724. // C99 6.3.1.5p1:
  1725. // When a float is promoted to double or long double, or a
  1726. // double is promoted to long double [...].
  1727. if (!getLangOpts().CPlusPlus &&
  1728. (FromBuiltin->getKind() == BuiltinType::Float ||
  1729. FromBuiltin->getKind() == BuiltinType::Double) &&
  1730. (ToBuiltin->getKind() == BuiltinType::LongDouble))
  1731. return true;
  1732. // Half can be promoted to float.
  1733. if (!getLangOpts().NativeHalfType &&
  1734. FromBuiltin->getKind() == BuiltinType::Half &&
  1735. ToBuiltin->getKind() == BuiltinType::Float)
  1736. return true;
  1737. // HLSL Change Starts
  1738. if (getLangOpts().HLSL) {
  1739. if (FromBuiltin->getKind() == BuiltinType::LitFloat &&
  1740. (ToBuiltin->getKind() == BuiltinType::Min10Float ||
  1741. ToBuiltin->getKind() == BuiltinType::Float ||
  1742. ToBuiltin->getKind() == BuiltinType::Half ||
  1743. ToBuiltin->getKind() == BuiltinType::Double))
  1744. return true;
  1745. if (FromBuiltin->getKind() == BuiltinType::Min10Float &&
  1746. (ToBuiltin->getKind() == BuiltinType::Float ||
  1747. ToBuiltin->getKind() == BuiltinType::Half ||
  1748. ToBuiltin->getKind() == BuiltinType::Double))
  1749. return true;
  1750. }
  1751. // HLSL Change Ends
  1752. }
  1753. return false;
  1754. }
  1755. /// \brief Determine if a conversion is a complex promotion.
  1756. ///
  1757. /// A complex promotion is defined as a complex -> complex conversion
  1758. /// where the conversion between the underlying real types is a
  1759. /// floating-point or integral promotion.
  1760. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1761. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1762. if (!FromComplex)
  1763. return false;
  1764. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1765. if (!ToComplex)
  1766. return false;
  1767. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1768. ToComplex->getElementType()) ||
  1769. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  1770. ToComplex->getElementType());
  1771. }
  1772. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1773. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1774. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1775. /// if non-empty, will be a pointer to ToType that may or may not have
  1776. /// the right set of qualifiers on its pointee.
  1777. ///
  1778. static QualType
  1779. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  1780. QualType ToPointee, QualType ToType,
  1781. ASTContext &Context,
  1782. bool StripObjCLifetime = false) {
  1783. assert((FromPtr->getTypeClass() == Type::Pointer ||
  1784. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  1785. "Invalid similarly-qualified pointer type");
  1786. /// Conversions to 'id' subsume cv-qualifier conversions.
  1787. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  1788. return ToType.getUnqualifiedType();
  1789. QualType CanonFromPointee
  1790. = Context.getCanonicalType(FromPtr->getPointeeType());
  1791. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  1792. Qualifiers Quals = CanonFromPointee.getQualifiers();
  1793. if (StripObjCLifetime)
  1794. Quals.removeObjCLifetime();
  1795. // Exact qualifier match -> return the pointer type we're converting to.
  1796. if (CanonToPointee.getLocalQualifiers() == Quals) {
  1797. // ToType is exactly what we need. Return it.
  1798. if (!ToType.isNull())
  1799. return ToType.getUnqualifiedType();
  1800. // Build a pointer to ToPointee. It has the right qualifiers
  1801. // already.
  1802. if (isa<ObjCObjectPointerType>(ToType))
  1803. return Context.getObjCObjectPointerType(ToPointee);
  1804. return Context.getPointerType(ToPointee);
  1805. }
  1806. // Just build a canonical type that has the right qualifiers.
  1807. QualType QualifiedCanonToPointee
  1808. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  1809. if (isa<ObjCObjectPointerType>(ToType))
  1810. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  1811. return Context.getPointerType(QualifiedCanonToPointee);
  1812. }
  1813. static bool isNullPointerConstantForConversion(Expr *Expr,
  1814. bool InOverloadResolution,
  1815. ASTContext &Context) {
  1816. // Handle value-dependent integral null pointer constants correctly.
  1817. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  1818. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  1819. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  1820. return !InOverloadResolution;
  1821. return Expr->isNullPointerConstant(Context,
  1822. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  1823. : Expr::NPC_ValueDependentIsNull);
  1824. }
  1825. /// IsPointerConversion - Determines whether the conversion of the
  1826. /// expression From, which has the (possibly adjusted) type FromType,
  1827. /// can be converted to the type ToType via a pointer conversion (C++
  1828. /// 4.10). If so, returns true and places the converted type (that
  1829. /// might differ from ToType in its cv-qualifiers at some level) into
  1830. /// ConvertedType.
  1831. ///
  1832. /// This routine also supports conversions to and from block pointers
  1833. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  1834. /// pointers to interfaces. FIXME: Once we've determined the
  1835. /// appropriate overloading rules for Objective-C, we may want to
  1836. /// split the Objective-C checks into a different routine; however,
  1837. /// GCC seems to consider all of these conversions to be pointer
  1838. /// conversions, so for now they live here. IncompatibleObjC will be
  1839. /// set if the conversion is an allowed Objective-C conversion that
  1840. /// should result in a warning.
  1841. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  1842. bool InOverloadResolution,
  1843. QualType& ConvertedType,
  1844. bool &IncompatibleObjC) {
  1845. IncompatibleObjC = false;
  1846. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  1847. IncompatibleObjC))
  1848. return true;
  1849. // Conversion from a null pointer constant to any Objective-C pointer type.
  1850. if (ToType->isObjCObjectPointerType() &&
  1851. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1852. ConvertedType = ToType;
  1853. return true;
  1854. }
  1855. // Blocks: Block pointers can be converted to void*.
  1856. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  1857. ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
  1858. ConvertedType = ToType;
  1859. return true;
  1860. }
  1861. // Blocks: A null pointer constant can be converted to a block
  1862. // pointer type.
  1863. if (ToType->isBlockPointerType() &&
  1864. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1865. ConvertedType = ToType;
  1866. return true;
  1867. }
  1868. // If the left-hand-side is nullptr_t, the right side can be a null
  1869. // pointer constant.
  1870. if (ToType->isNullPtrType() &&
  1871. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1872. ConvertedType = ToType;
  1873. return true;
  1874. }
  1875. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  1876. if (!ToTypePtr)
  1877. return false;
  1878. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  1879. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1880. ConvertedType = ToType;
  1881. return true;
  1882. }
  1883. // Beyond this point, both types need to be pointers
  1884. // , including objective-c pointers.
  1885. QualType ToPointeeType = ToTypePtr->getPointeeType();
  1886. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  1887. !getLangOpts().ObjCAutoRefCount) {
  1888. ConvertedType = BuildSimilarlyQualifiedPointerType(
  1889. FromType->getAs<ObjCObjectPointerType>(),
  1890. ToPointeeType,
  1891. ToType, Context);
  1892. return true;
  1893. }
  1894. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  1895. if (!FromTypePtr)
  1896. return false;
  1897. QualType FromPointeeType = FromTypePtr->getPointeeType();
  1898. // If the unqualified pointee types are the same, this can't be a
  1899. // pointer conversion, so don't do all of the work below.
  1900. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  1901. return false;
  1902. // An rvalue of type "pointer to cv T," where T is an object type,
  1903. // can be converted to an rvalue of type "pointer to cv void" (C++
  1904. // 4.10p2).
  1905. if (FromPointeeType->isIncompleteOrObjectType() &&
  1906. ToPointeeType->isVoidType()) {
  1907. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1908. ToPointeeType,
  1909. ToType, Context,
  1910. /*StripObjCLifetime=*/true);
  1911. return true;
  1912. }
  1913. // MSVC allows implicit function to void* type conversion.
  1914. if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
  1915. ToPointeeType->isVoidType()) {
  1916. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1917. ToPointeeType,
  1918. ToType, Context);
  1919. return true;
  1920. }
  1921. // When we're overloading in C, we allow a special kind of pointer
  1922. // conversion for compatible-but-not-identical pointee types.
  1923. if (!getLangOpts().CPlusPlus &&
  1924. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  1925. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1926. ToPointeeType,
  1927. ToType, Context);
  1928. return true;
  1929. }
  1930. // C++ [conv.ptr]p3:
  1931. //
  1932. // An rvalue of type "pointer to cv D," where D is a class type,
  1933. // can be converted to an rvalue of type "pointer to cv B," where
  1934. // B is a base class (clause 10) of D. If B is an inaccessible
  1935. // (clause 11) or ambiguous (10.2) base class of D, a program that
  1936. // necessitates this conversion is ill-formed. The result of the
  1937. // conversion is a pointer to the base class sub-object of the
  1938. // derived class object. The null pointer value is converted to
  1939. // the null pointer value of the destination type.
  1940. //
  1941. // Note that we do not check for ambiguity or inaccessibility
  1942. // here. That is handled by CheckPointerConversion.
  1943. if (getLangOpts().CPlusPlus &&
  1944. FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  1945. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  1946. !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
  1947. IsDerivedFrom(FromPointeeType, ToPointeeType)) {
  1948. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1949. ToPointeeType,
  1950. ToType, Context);
  1951. return true;
  1952. }
  1953. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  1954. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  1955. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1956. ToPointeeType,
  1957. ToType, Context);
  1958. return true;
  1959. }
  1960. return false;
  1961. }
  1962. /// \brief Adopt the given qualifiers for the given type.
  1963. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  1964. Qualifiers TQs = T.getQualifiers();
  1965. // Check whether qualifiers already match.
  1966. if (TQs == Qs)
  1967. return T;
  1968. if (Qs.compatiblyIncludes(TQs))
  1969. return Context.getQualifiedType(T, Qs);
  1970. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  1971. }
  1972. /// isObjCPointerConversion - Determines whether this is an
  1973. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  1974. /// with the same arguments and return values.
  1975. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  1976. QualType& ConvertedType,
  1977. bool &IncompatibleObjC) {
  1978. if (!getLangOpts().ObjC1)
  1979. return false;
  1980. // The set of qualifiers on the type we're converting from.
  1981. Qualifiers FromQualifiers = FromType.getQualifiers();
  1982. // First, we handle all conversions on ObjC object pointer types.
  1983. const ObjCObjectPointerType* ToObjCPtr =
  1984. ToType->getAs<ObjCObjectPointerType>();
  1985. const ObjCObjectPointerType *FromObjCPtr =
  1986. FromType->getAs<ObjCObjectPointerType>();
  1987. if (ToObjCPtr && FromObjCPtr) {
  1988. // If the pointee types are the same (ignoring qualifications),
  1989. // then this is not a pointer conversion.
  1990. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  1991. FromObjCPtr->getPointeeType()))
  1992. return false;
  1993. // Conversion between Objective-C pointers.
  1994. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  1995. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  1996. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  1997. if (getLangOpts().CPlusPlus && LHS && RHS &&
  1998. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  1999. FromObjCPtr->getPointeeType()))
  2000. return false;
  2001. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2002. ToObjCPtr->getPointeeType(),
  2003. ToType, Context);
  2004. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2005. return true;
  2006. }
  2007. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2008. // Okay: this is some kind of implicit downcast of Objective-C
  2009. // interfaces, which is permitted. However, we're going to
  2010. // complain about it.
  2011. IncompatibleObjC = true;
  2012. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2013. ToObjCPtr->getPointeeType(),
  2014. ToType, Context);
  2015. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2016. return true;
  2017. }
  2018. }
  2019. // Beyond this point, both types need to be C pointers or block pointers.
  2020. QualType ToPointeeType;
  2021. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2022. ToPointeeType = ToCPtr->getPointeeType();
  2023. else if (const BlockPointerType *ToBlockPtr =
  2024. ToType->getAs<BlockPointerType>()) {
  2025. // Objective C++: We're able to convert from a pointer to any object
  2026. // to a block pointer type.
  2027. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2028. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2029. return true;
  2030. }
  2031. ToPointeeType = ToBlockPtr->getPointeeType();
  2032. }
  2033. else if (FromType->getAs<BlockPointerType>() &&
  2034. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2035. // Objective C++: We're able to convert from a block pointer type to a
  2036. // pointer to any object.
  2037. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2038. return true;
  2039. }
  2040. else
  2041. return false;
  2042. QualType FromPointeeType;
  2043. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2044. FromPointeeType = FromCPtr->getPointeeType();
  2045. else if (const BlockPointerType *FromBlockPtr =
  2046. FromType->getAs<BlockPointerType>())
  2047. FromPointeeType = FromBlockPtr->getPointeeType();
  2048. else
  2049. return false;
  2050. // If we have pointers to pointers, recursively check whether this
  2051. // is an Objective-C conversion.
  2052. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2053. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2054. IncompatibleObjC)) {
  2055. // We always complain about this conversion.
  2056. IncompatibleObjC = true;
  2057. ConvertedType = Context.getPointerType(ConvertedType);
  2058. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2059. return true;
  2060. }
  2061. // Allow conversion of pointee being objective-c pointer to another one;
  2062. // as in I* to id.
  2063. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2064. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2065. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2066. IncompatibleObjC)) {
  2067. ConvertedType = Context.getPointerType(ConvertedType);
  2068. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2069. return true;
  2070. }
  2071. // If we have pointers to functions or blocks, check whether the only
  2072. // differences in the argument and result types are in Objective-C
  2073. // pointer conversions. If so, we permit the conversion (but
  2074. // complain about it).
  2075. const FunctionProtoType *FromFunctionType
  2076. = FromPointeeType->getAs<FunctionProtoType>();
  2077. const FunctionProtoType *ToFunctionType
  2078. = ToPointeeType->getAs<FunctionProtoType>();
  2079. if (FromFunctionType && ToFunctionType) {
  2080. // If the function types are exactly the same, this isn't an
  2081. // Objective-C pointer conversion.
  2082. if (Context.getCanonicalType(FromPointeeType)
  2083. == Context.getCanonicalType(ToPointeeType))
  2084. return false;
  2085. // Perform the quick checks that will tell us whether these
  2086. // function types are obviously different.
  2087. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2088. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2089. FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
  2090. return false;
  2091. bool HasObjCConversion = false;
  2092. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2093. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2094. // Okay, the types match exactly. Nothing to do.
  2095. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2096. ToFunctionType->getReturnType(),
  2097. ConvertedType, IncompatibleObjC)) {
  2098. // Okay, we have an Objective-C pointer conversion.
  2099. HasObjCConversion = true;
  2100. } else {
  2101. // Function types are too different. Abort.
  2102. return false;
  2103. }
  2104. // Check argument types.
  2105. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2106. ArgIdx != NumArgs; ++ArgIdx) {
  2107. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2108. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2109. if (Context.getCanonicalType(FromArgType)
  2110. == Context.getCanonicalType(ToArgType)) {
  2111. // Okay, the types match exactly. Nothing to do.
  2112. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2113. ConvertedType, IncompatibleObjC)) {
  2114. // Okay, we have an Objective-C pointer conversion.
  2115. HasObjCConversion = true;
  2116. } else {
  2117. // Argument types are too different. Abort.
  2118. return false;
  2119. }
  2120. }
  2121. if (HasObjCConversion) {
  2122. // We had an Objective-C conversion. Allow this pointer
  2123. // conversion, but complain about it.
  2124. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2125. IncompatibleObjC = true;
  2126. return true;
  2127. }
  2128. }
  2129. return false;
  2130. }
  2131. /// \brief Determine whether this is an Objective-C writeback conversion,
  2132. /// used for parameter passing when performing automatic reference counting.
  2133. ///
  2134. /// \param FromType The type we're converting form.
  2135. ///
  2136. /// \param ToType The type we're converting to.
  2137. ///
  2138. /// \param ConvertedType The type that will be produced after applying
  2139. /// this conversion.
  2140. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2141. QualType &ConvertedType) {
  2142. if (!getLangOpts().ObjCAutoRefCount ||
  2143. Context.hasSameUnqualifiedType(FromType, ToType))
  2144. return false;
  2145. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2146. QualType ToPointee;
  2147. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2148. ToPointee = ToPointer->getPointeeType();
  2149. else
  2150. return false;
  2151. Qualifiers ToQuals = ToPointee.getQualifiers();
  2152. if (!ToPointee->isObjCLifetimeType() ||
  2153. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2154. !ToQuals.withoutObjCLifetime().empty())
  2155. return false;
  2156. // Argument must be a pointer to __strong to __weak.
  2157. QualType FromPointee;
  2158. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2159. FromPointee = FromPointer->getPointeeType();
  2160. else
  2161. return false;
  2162. Qualifiers FromQuals = FromPointee.getQualifiers();
  2163. if (!FromPointee->isObjCLifetimeType() ||
  2164. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2165. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2166. return false;
  2167. // Make sure that we have compatible qualifiers.
  2168. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2169. if (!ToQuals.compatiblyIncludes(FromQuals))
  2170. return false;
  2171. // Remove qualifiers from the pointee type we're converting from; they
  2172. // aren't used in the compatibility check belong, and we'll be adding back
  2173. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2174. FromPointee = FromPointee.getUnqualifiedType();
  2175. // The unqualified form of the pointee types must be compatible.
  2176. ToPointee = ToPointee.getUnqualifiedType();
  2177. bool IncompatibleObjC;
  2178. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2179. FromPointee = ToPointee;
  2180. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2181. IncompatibleObjC))
  2182. return false;
  2183. /// \brief Construct the type we're converting to, which is a pointer to
  2184. /// __autoreleasing pointee.
  2185. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2186. ConvertedType = Context.getPointerType(FromPointee);
  2187. return true;
  2188. }
  2189. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2190. QualType& ConvertedType) {
  2191. QualType ToPointeeType;
  2192. if (const BlockPointerType *ToBlockPtr =
  2193. ToType->getAs<BlockPointerType>())
  2194. ToPointeeType = ToBlockPtr->getPointeeType();
  2195. else
  2196. return false;
  2197. QualType FromPointeeType;
  2198. if (const BlockPointerType *FromBlockPtr =
  2199. FromType->getAs<BlockPointerType>())
  2200. FromPointeeType = FromBlockPtr->getPointeeType();
  2201. else
  2202. return false;
  2203. // We have pointer to blocks, check whether the only
  2204. // differences in the argument and result types are in Objective-C
  2205. // pointer conversions. If so, we permit the conversion.
  2206. const FunctionProtoType *FromFunctionType
  2207. = FromPointeeType->getAs<FunctionProtoType>();
  2208. const FunctionProtoType *ToFunctionType
  2209. = ToPointeeType->getAs<FunctionProtoType>();
  2210. if (!FromFunctionType || !ToFunctionType)
  2211. return false;
  2212. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2213. return true;
  2214. // Perform the quick checks that will tell us whether these
  2215. // function types are obviously different.
  2216. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2217. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2218. return false;
  2219. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2220. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2221. if (FromEInfo != ToEInfo)
  2222. return false;
  2223. bool IncompatibleObjC = false;
  2224. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2225. ToFunctionType->getReturnType())) {
  2226. // Okay, the types match exactly. Nothing to do.
  2227. } else {
  2228. QualType RHS = FromFunctionType->getReturnType();
  2229. QualType LHS = ToFunctionType->getReturnType();
  2230. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2231. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2232. LHS = LHS.getUnqualifiedType();
  2233. if (Context.hasSameType(RHS,LHS)) {
  2234. // OK exact match.
  2235. } else if (isObjCPointerConversion(RHS, LHS,
  2236. ConvertedType, IncompatibleObjC)) {
  2237. if (IncompatibleObjC)
  2238. return false;
  2239. // Okay, we have an Objective-C pointer conversion.
  2240. }
  2241. else
  2242. return false;
  2243. }
  2244. // Check argument types.
  2245. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2246. ArgIdx != NumArgs; ++ArgIdx) {
  2247. IncompatibleObjC = false;
  2248. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2249. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2250. if (Context.hasSameType(FromArgType, ToArgType)) {
  2251. // Okay, the types match exactly. Nothing to do.
  2252. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2253. ConvertedType, IncompatibleObjC)) {
  2254. if (IncompatibleObjC)
  2255. return false;
  2256. // Okay, we have an Objective-C pointer conversion.
  2257. } else
  2258. // Argument types are too different. Abort.
  2259. return false;
  2260. }
  2261. if (LangOpts.ObjCAutoRefCount &&
  2262. !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
  2263. ToFunctionType))
  2264. return false;
  2265. ConvertedType = ToType;
  2266. return true;
  2267. }
  2268. enum {
  2269. ft_default,
  2270. ft_different_class,
  2271. ft_parameter_arity,
  2272. ft_parameter_mismatch,
  2273. ft_return_type,
  2274. ft_qualifer_mismatch
  2275. };
  2276. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2277. /// function types. Catches different number of parameter, mismatch in
  2278. /// parameter types, and different return types.
  2279. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2280. QualType FromType, QualType ToType) {
  2281. // If either type is not valid, include no extra info.
  2282. if (FromType.isNull() || ToType.isNull()) {
  2283. PDiag << ft_default;
  2284. return;
  2285. }
  2286. // Get the function type from the pointers.
  2287. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2288. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2289. *ToMember = ToType->getAs<MemberPointerType>();
  2290. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2291. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2292. << QualType(FromMember->getClass(), 0);
  2293. return;
  2294. }
  2295. FromType = FromMember->getPointeeType();
  2296. ToType = ToMember->getPointeeType();
  2297. }
  2298. if (FromType->isPointerType())
  2299. FromType = FromType->getPointeeType();
  2300. if (ToType->isPointerType())
  2301. ToType = ToType->getPointeeType();
  2302. // Remove references.
  2303. FromType = FromType.getNonReferenceType();
  2304. ToType = ToType.getNonReferenceType();
  2305. // Don't print extra info for non-specialized template functions.
  2306. if (FromType->isInstantiationDependentType() &&
  2307. !FromType->getAs<TemplateSpecializationType>()) {
  2308. PDiag << ft_default;
  2309. return;
  2310. }
  2311. // No extra info for same types.
  2312. if (Context.hasSameType(FromType, ToType)) {
  2313. PDiag << ft_default;
  2314. return;
  2315. }
  2316. const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
  2317. *ToFunction = ToType->getAs<FunctionProtoType>();
  2318. // Both types need to be function types.
  2319. if (!FromFunction || !ToFunction) {
  2320. PDiag << ft_default;
  2321. return;
  2322. }
  2323. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2324. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2325. << FromFunction->getNumParams();
  2326. return;
  2327. }
  2328. // Handle different parameter types.
  2329. unsigned ArgPos;
  2330. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2331. PDiag << ft_parameter_mismatch << ArgPos + 1
  2332. << ToFunction->getParamType(ArgPos)
  2333. << FromFunction->getParamType(ArgPos);
  2334. return;
  2335. }
  2336. // Handle different return type.
  2337. if (!Context.hasSameType(FromFunction->getReturnType(),
  2338. ToFunction->getReturnType())) {
  2339. PDiag << ft_return_type << ToFunction->getReturnType()
  2340. << FromFunction->getReturnType();
  2341. return;
  2342. }
  2343. unsigned FromQuals = FromFunction->getTypeQuals(),
  2344. ToQuals = ToFunction->getTypeQuals();
  2345. if (FromQuals != ToQuals) {
  2346. PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
  2347. return;
  2348. }
  2349. // Unable to find a difference, so add no extra info.
  2350. PDiag << ft_default;
  2351. }
  2352. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2353. /// for equality of their argument types. Caller has already checked that
  2354. /// they have same number of arguments. If the parameters are different,
  2355. /// ArgPos will have the parameter index of the first different parameter.
  2356. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2357. const FunctionProtoType *NewType,
  2358. unsigned *ArgPos) {
  2359. int index = 0;
  2360. for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
  2361. N = NewType->param_type_begin(),
  2362. E = OldType->param_type_end();
  2363. O && (O != E); ++O, ++N) {
  2364. if (!Context.hasSameType(O->getUnqualifiedType(),
  2365. N->getUnqualifiedType())
  2366. || OldType->getParamMods()[index] != NewType->getParamMods()[index]) { // HLSL Change - check param mods
  2367. index++;
  2368. if (ArgPos)
  2369. *ArgPos = O - OldType->param_type_begin();
  2370. return false;
  2371. }
  2372. }
  2373. return true;
  2374. }
  2375. /// CheckPointerConversion - Check the pointer conversion from the
  2376. /// expression From to the type ToType. This routine checks for
  2377. /// ambiguous or inaccessible derived-to-base pointer
  2378. /// conversions for which IsPointerConversion has already returned
  2379. /// true. It returns true and produces a diagnostic if there was an
  2380. /// error, or returns false otherwise.
  2381. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2382. CastKind &Kind,
  2383. CXXCastPath& BasePath,
  2384. bool IgnoreBaseAccess) {
  2385. QualType FromType = From->getType();
  2386. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2387. Kind = CK_BitCast;
  2388. if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2389. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2390. Expr::NPCK_ZeroExpression) {
  2391. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2392. DiagRuntimeBehavior(From->getExprLoc(), From,
  2393. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2394. << ToType << From->getSourceRange());
  2395. else if (!isUnevaluatedContext())
  2396. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2397. << ToType << From->getSourceRange();
  2398. }
  2399. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2400. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2401. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2402. ToPointeeType = ToPtrType->getPointeeType();
  2403. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2404. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2405. // We must have a derived-to-base conversion. Check an
  2406. // ambiguous or inaccessible conversion.
  2407. if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
  2408. From->getExprLoc(),
  2409. From->getSourceRange(), &BasePath,
  2410. IgnoreBaseAccess))
  2411. return true;
  2412. // The conversion was successful.
  2413. Kind = CK_DerivedToBase;
  2414. }
  2415. }
  2416. } else if (const ObjCObjectPointerType *ToPtrType =
  2417. ToType->getAs<ObjCObjectPointerType>()) {
  2418. if (const ObjCObjectPointerType *FromPtrType =
  2419. FromType->getAs<ObjCObjectPointerType>()) {
  2420. // Objective-C++ conversions are always okay.
  2421. // FIXME: We should have a different class of conversions for the
  2422. // Objective-C++ implicit conversions.
  2423. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2424. return false;
  2425. } else if (FromType->isBlockPointerType()) {
  2426. Kind = CK_BlockPointerToObjCPointerCast;
  2427. } else {
  2428. Kind = CK_CPointerToObjCPointerCast;
  2429. }
  2430. } else if (ToType->isBlockPointerType()) {
  2431. if (!FromType->isBlockPointerType())
  2432. Kind = CK_AnyPointerToBlockPointerCast;
  2433. }
  2434. // We shouldn't fall into this case unless it's valid for other
  2435. // reasons.
  2436. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2437. Kind = CK_NullToPointer;
  2438. return false;
  2439. }
  2440. /// IsMemberPointerConversion - Determines whether the conversion of the
  2441. /// expression From, which has the (possibly adjusted) type FromType, can be
  2442. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2443. /// If so, returns true and places the converted type (that might differ from
  2444. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2445. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2446. QualType ToType,
  2447. bool InOverloadResolution,
  2448. QualType &ConvertedType) {
  2449. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2450. if (!ToTypePtr)
  2451. return false;
  2452. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2453. if (From->isNullPointerConstant(Context,
  2454. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2455. : Expr::NPC_ValueDependentIsNull)) {
  2456. ConvertedType = ToType;
  2457. return true;
  2458. }
  2459. // Otherwise, both types have to be member pointers.
  2460. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2461. if (!FromTypePtr)
  2462. return false;
  2463. // A pointer to member of B can be converted to a pointer to member of D,
  2464. // where D is derived from B (C++ 4.11p2).
  2465. QualType FromClass(FromTypePtr->getClass(), 0);
  2466. QualType ToClass(ToTypePtr->getClass(), 0);
  2467. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2468. !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
  2469. IsDerivedFrom(ToClass, FromClass)) {
  2470. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2471. ToClass.getTypePtr());
  2472. return true;
  2473. }
  2474. return false;
  2475. }
  2476. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2477. /// expression From to the type ToType. This routine checks for ambiguous or
  2478. /// virtual or inaccessible base-to-derived member pointer conversions
  2479. /// for which IsMemberPointerConversion has already returned true. It returns
  2480. /// true and produces a diagnostic if there was an error, or returns false
  2481. /// otherwise.
  2482. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2483. CastKind &Kind,
  2484. CXXCastPath &BasePath,
  2485. bool IgnoreBaseAccess) {
  2486. QualType FromType = From->getType();
  2487. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2488. if (!FromPtrType) {
  2489. // This must be a null pointer to member pointer conversion
  2490. assert(From->isNullPointerConstant(Context,
  2491. Expr::NPC_ValueDependentIsNull) &&
  2492. "Expr must be null pointer constant!");
  2493. Kind = CK_NullToMemberPointer;
  2494. return false;
  2495. }
  2496. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2497. assert(ToPtrType && "No member pointer cast has a target type "
  2498. "that is not a member pointer.");
  2499. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2500. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2501. // FIXME: What about dependent types?
  2502. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2503. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2504. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2505. /*DetectVirtual=*/true);
  2506. bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
  2507. assert(DerivationOkay &&
  2508. "Should not have been called if derivation isn't OK.");
  2509. (void)DerivationOkay;
  2510. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2511. getUnqualifiedType())) {
  2512. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2513. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2514. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2515. return true;
  2516. }
  2517. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2518. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2519. << FromClass << ToClass << QualType(VBase, 0)
  2520. << From->getSourceRange();
  2521. return true;
  2522. }
  2523. if (!IgnoreBaseAccess)
  2524. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2525. Paths.front(),
  2526. diag::err_downcast_from_inaccessible_base);
  2527. // Must be a base to derived member conversion.
  2528. BuildBasePathArray(Paths, BasePath);
  2529. Kind = CK_BaseToDerivedMemberPointer;
  2530. return false;
  2531. }
  2532. /// Determine whether the lifetime conversion between the two given
  2533. /// qualifiers sets is nontrivial.
  2534. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2535. Qualifiers ToQuals) {
  2536. // Converting anything to const __unsafe_unretained is trivial.
  2537. if (ToQuals.hasConst() &&
  2538. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2539. return false;
  2540. return true;
  2541. }
  2542. /// IsQualificationConversion - Determines whether the conversion from
  2543. /// an rvalue of type FromType to ToType is a qualification conversion
  2544. /// (C++ 4.4).
  2545. ///
  2546. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2547. /// when the qualification conversion involves a change in the Objective-C
  2548. /// object lifetime.
  2549. bool
  2550. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2551. bool CStyle, bool &ObjCLifetimeConversion) {
  2552. FromType = Context.getCanonicalType(FromType);
  2553. ToType = Context.getCanonicalType(ToType);
  2554. ObjCLifetimeConversion = false;
  2555. // If FromType and ToType are the same type, this is not a
  2556. // qualification conversion.
  2557. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2558. return false;
  2559. // (C++ 4.4p4):
  2560. // A conversion can add cv-qualifiers at levels other than the first
  2561. // in multi-level pointers, subject to the following rules: [...]
  2562. bool PreviousToQualsIncludeConst = true;
  2563. bool UnwrappedAnyPointer = false;
  2564. while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
  2565. // Within each iteration of the loop, we check the qualifiers to
  2566. // determine if this still looks like a qualification
  2567. // conversion. Then, if all is well, we unwrap one more level of
  2568. // pointers or pointers-to-members and do it all again
  2569. // until there are no more pointers or pointers-to-members left to
  2570. // unwrap.
  2571. UnwrappedAnyPointer = true;
  2572. Qualifiers FromQuals = FromType.getQualifiers();
  2573. Qualifiers ToQuals = ToType.getQualifiers();
  2574. // Objective-C ARC:
  2575. // Check Objective-C lifetime conversions.
  2576. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2577. UnwrappedAnyPointer) {
  2578. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2579. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2580. ObjCLifetimeConversion = true;
  2581. FromQuals.removeObjCLifetime();
  2582. ToQuals.removeObjCLifetime();
  2583. } else {
  2584. // Qualification conversions cannot cast between different
  2585. // Objective-C lifetime qualifiers.
  2586. return false;
  2587. }
  2588. }
  2589. // Allow addition/removal of GC attributes but not changing GC attributes.
  2590. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2591. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2592. FromQuals.removeObjCGCAttr();
  2593. ToQuals.removeObjCGCAttr();
  2594. }
  2595. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2596. // 2,j, and similarly for volatile.
  2597. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2598. return false;
  2599. // -- if the cv 1,j and cv 2,j are different, then const is in
  2600. // every cv for 0 < k < j.
  2601. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2602. && !PreviousToQualsIncludeConst)
  2603. return false;
  2604. // Keep track of whether all prior cv-qualifiers in the "to" type
  2605. // include const.
  2606. PreviousToQualsIncludeConst
  2607. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2608. }
  2609. // We are left with FromType and ToType being the pointee types
  2610. // after unwrapping the original FromType and ToType the same number
  2611. // of types. If we unwrapped any pointers, and if FromType and
  2612. // ToType have the same unqualified type (since we checked
  2613. // qualifiers above), then this is a qualification conversion.
  2614. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2615. }
  2616. /// \brief - Determine whether this is a conversion from a scalar type to an
  2617. /// atomic type.
  2618. ///
  2619. /// If successful, updates \c SCS's second and third steps in the conversion
  2620. /// sequence to finish the conversion.
  2621. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2622. bool InOverloadResolution,
  2623. StandardConversionSequence &SCS,
  2624. bool CStyle) {
  2625. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2626. if (!ToAtomic)
  2627. return false;
  2628. StandardConversionSequence InnerSCS;
  2629. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2630. InOverloadResolution, InnerSCS,
  2631. CStyle, /*AllowObjCWritebackConversion=*/false))
  2632. return false;
  2633. SCS.Second = InnerSCS.Second;
  2634. SCS.setToType(1, InnerSCS.getToType(1));
  2635. SCS.Third = InnerSCS.Third;
  2636. SCS.QualificationIncludesObjCLifetime
  2637. = InnerSCS.QualificationIncludesObjCLifetime;
  2638. SCS.setToType(2, InnerSCS.getToType(2));
  2639. return true;
  2640. }
  2641. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2642. CXXConstructorDecl *Constructor,
  2643. QualType Type) {
  2644. const FunctionProtoType *CtorType =
  2645. Constructor->getType()->getAs<FunctionProtoType>();
  2646. if (CtorType->getNumParams() > 0) {
  2647. QualType FirstArg = CtorType->getParamType(0);
  2648. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2649. return true;
  2650. }
  2651. return false;
  2652. }
  2653. static OverloadingResult
  2654. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2655. CXXRecordDecl *To,
  2656. UserDefinedConversionSequence &User,
  2657. OverloadCandidateSet &CandidateSet,
  2658. bool AllowExplicit) {
  2659. DeclContext::lookup_result R = S.LookupConstructors(To);
  2660. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2661. Con != ConEnd; ++Con) {
  2662. NamedDecl *D = *Con;
  2663. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2664. // Find the constructor (which may be a template).
  2665. CXXConstructorDecl *Constructor = nullptr;
  2666. FunctionTemplateDecl *ConstructorTmpl
  2667. = dyn_cast<FunctionTemplateDecl>(D);
  2668. if (ConstructorTmpl)
  2669. Constructor
  2670. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2671. else
  2672. Constructor = cast<CXXConstructorDecl>(D);
  2673. bool Usable = !Constructor->isInvalidDecl() &&
  2674. S.isInitListConstructor(Constructor) &&
  2675. (AllowExplicit || !Constructor->isExplicit());
  2676. if (Usable) {
  2677. // If the first argument is (a reference to) the target type,
  2678. // suppress conversions.
  2679. bool SuppressUserConversions =
  2680. isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
  2681. if (ConstructorTmpl)
  2682. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2683. /*ExplicitArgs*/ nullptr,
  2684. From, CandidateSet,
  2685. SuppressUserConversions);
  2686. else
  2687. S.AddOverloadCandidate(Constructor, FoundDecl,
  2688. From, CandidateSet,
  2689. SuppressUserConversions);
  2690. }
  2691. }
  2692. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2693. OverloadCandidateSet::iterator Best;
  2694. switch (auto Result =
  2695. CandidateSet.BestViableFunction(S, From->getLocStart(),
  2696. Best, true)) {
  2697. case OR_Deleted:
  2698. case OR_Success: {
  2699. // Record the standard conversion we used and the conversion function.
  2700. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2701. QualType ThisType = Constructor->getThisType(S.Context);
  2702. // Initializer lists don't have conversions as such.
  2703. User.Before.setAsIdentityConversion();
  2704. User.HadMultipleCandidates = HadMultipleCandidates;
  2705. User.ConversionFunction = Constructor;
  2706. User.FoundConversionFunction = Best->FoundDecl;
  2707. User.After.setAsIdentityConversion();
  2708. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2709. User.After.setAllToTypes(ToType);
  2710. return Result;
  2711. }
  2712. case OR_No_Viable_Function:
  2713. return OR_No_Viable_Function;
  2714. case OR_Ambiguous:
  2715. return OR_Ambiguous;
  2716. }
  2717. llvm_unreachable("Invalid OverloadResult!");
  2718. }
  2719. /// Determines whether there is a user-defined conversion sequence
  2720. /// (C++ [over.ics.user]) that converts expression From to the type
  2721. /// ToType. If such a conversion exists, User will contain the
  2722. /// user-defined conversion sequence that performs such a conversion
  2723. /// and this routine will return true. Otherwise, this routine returns
  2724. /// false and User is unspecified.
  2725. ///
  2726. /// \param AllowExplicit true if the conversion should consider C++0x
  2727. /// "explicit" conversion functions as well as non-explicit conversion
  2728. /// functions (C++0x [class.conv.fct]p2).
  2729. ///
  2730. /// \param AllowObjCConversionOnExplicit true if the conversion should
  2731. /// allow an extra Objective-C pointer conversion on uses of explicit
  2732. /// constructors. Requires \c AllowExplicit to also be set.
  2733. static OverloadingResult
  2734. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2735. UserDefinedConversionSequence &User,
  2736. OverloadCandidateSet &CandidateSet,
  2737. bool AllowExplicit,
  2738. bool AllowObjCConversionOnExplicit) {
  2739. assert(AllowExplicit || !AllowObjCConversionOnExplicit);
  2740. // Whether we will only visit constructors.
  2741. bool ConstructorsOnly = false;
  2742. // If the type we are conversion to is a class type, enumerate its
  2743. // constructors.
  2744. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2745. // C++ [over.match.ctor]p1:
  2746. // When objects of class type are direct-initialized (8.5), or
  2747. // copy-initialized from an expression of the same or a
  2748. // derived class type (8.5), overload resolution selects the
  2749. // constructor. [...] For copy-initialization, the candidate
  2750. // functions are all the converting constructors (12.3.1) of
  2751. // that class. The argument list is the expression-list within
  2752. // the parentheses of the initializer.
  2753. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  2754. (From->getType()->getAs<RecordType>() &&
  2755. S.IsDerivedFrom(From->getType(), ToType)))
  2756. ConstructorsOnly = true;
  2757. S.RequireCompleteType(From->getExprLoc(), ToType, 0);
  2758. // RequireCompleteType may have returned true due to some invalid decl
  2759. // during template instantiation, but ToType may be complete enough now
  2760. // to try to recover.
  2761. if (ToType->isIncompleteType()) {
  2762. // We're not going to find any constructors.
  2763. } else if (CXXRecordDecl *ToRecordDecl
  2764. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  2765. Expr **Args = &From;
  2766. unsigned NumArgs = 1;
  2767. bool ListInitializing = false;
  2768. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  2769. // But first, see if there is an init-list-constructor that will work.
  2770. OverloadingResult Result = IsInitializerListConstructorConversion(
  2771. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  2772. if (Result != OR_No_Viable_Function)
  2773. return Result;
  2774. // Never mind.
  2775. CandidateSet.clear();
  2776. // If we're list-initializing, we pass the individual elements as
  2777. // arguments, not the entire list.
  2778. Args = InitList->getInits();
  2779. NumArgs = InitList->getNumInits();
  2780. ListInitializing = true;
  2781. }
  2782. DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
  2783. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2784. Con != ConEnd; ++Con) {
  2785. NamedDecl *D = *Con;
  2786. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2787. // Find the constructor (which may be a template).
  2788. CXXConstructorDecl *Constructor = nullptr;
  2789. FunctionTemplateDecl *ConstructorTmpl
  2790. = dyn_cast<FunctionTemplateDecl>(D);
  2791. if (ConstructorTmpl)
  2792. Constructor
  2793. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2794. else
  2795. Constructor = cast<CXXConstructorDecl>(D);
  2796. bool Usable = !Constructor->isInvalidDecl();
  2797. if (ListInitializing)
  2798. Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
  2799. else
  2800. Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
  2801. if (Usable) {
  2802. bool SuppressUserConversions = !ConstructorsOnly;
  2803. if (SuppressUserConversions && ListInitializing) {
  2804. SuppressUserConversions = false;
  2805. if (NumArgs == 1) {
  2806. // If the first argument is (a reference to) the target type,
  2807. // suppress conversions.
  2808. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2809. S.Context, Constructor, ToType);
  2810. }
  2811. }
  2812. if (ConstructorTmpl)
  2813. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2814. /*ExplicitArgs*/ nullptr,
  2815. llvm::makeArrayRef(Args, NumArgs),
  2816. CandidateSet, SuppressUserConversions);
  2817. else
  2818. // Allow one user-defined conversion when user specifies a
  2819. // From->ToType conversion via an static cast (c-style, etc).
  2820. S.AddOverloadCandidate(Constructor, FoundDecl,
  2821. llvm::makeArrayRef(Args, NumArgs),
  2822. CandidateSet, SuppressUserConversions);
  2823. }
  2824. }
  2825. }
  2826. }
  2827. // Enumerate conversion functions, if we're allowed to.
  2828. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  2829. } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
  2830. // No conversion functions from incomplete types.
  2831. } else if (const RecordType *FromRecordType
  2832. = From->getType()->getAs<RecordType>()) {
  2833. if (CXXRecordDecl *FromRecordDecl
  2834. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  2835. // Add all of the conversion functions as candidates.
  2836. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  2837. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  2838. DeclAccessPair FoundDecl = I.getPair();
  2839. NamedDecl *D = FoundDecl.getDecl();
  2840. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  2841. if (isa<UsingShadowDecl>(D))
  2842. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2843. CXXConversionDecl *Conv;
  2844. FunctionTemplateDecl *ConvTemplate;
  2845. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  2846. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  2847. else
  2848. Conv = cast<CXXConversionDecl>(D);
  2849. if (AllowExplicit || !Conv->isExplicit()) {
  2850. if (ConvTemplate)
  2851. S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
  2852. ActingContext, From, ToType,
  2853. CandidateSet,
  2854. AllowObjCConversionOnExplicit);
  2855. else
  2856. S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
  2857. From, ToType, CandidateSet,
  2858. AllowObjCConversionOnExplicit);
  2859. }
  2860. }
  2861. }
  2862. }
  2863. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2864. OverloadCandidateSet::iterator Best;
  2865. switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
  2866. Best, true)) {
  2867. case OR_Success:
  2868. case OR_Deleted:
  2869. // Record the standard conversion we used and the conversion function.
  2870. if (CXXConstructorDecl *Constructor
  2871. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  2872. // C++ [over.ics.user]p1:
  2873. // If the user-defined conversion is specified by a
  2874. // constructor (12.3.1), the initial standard conversion
  2875. // sequence converts the source type to the type required by
  2876. // the argument of the constructor.
  2877. //
  2878. QualType ThisType = Constructor->getThisType(S.Context);
  2879. if (isa<InitListExpr>(From)) {
  2880. // Initializer lists don't have conversions as such.
  2881. User.Before.setAsIdentityConversion();
  2882. } else {
  2883. if (Best->Conversions[0].isEllipsis())
  2884. User.EllipsisConversion = true;
  2885. else {
  2886. User.Before = Best->Conversions[0].Standard;
  2887. User.EllipsisConversion = false;
  2888. }
  2889. }
  2890. User.HadMultipleCandidates = HadMultipleCandidates;
  2891. User.ConversionFunction = Constructor;
  2892. User.FoundConversionFunction = Best->FoundDecl;
  2893. User.After.setAsIdentityConversion();
  2894. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2895. User.After.setAllToTypes(ToType);
  2896. return Result;
  2897. }
  2898. if (CXXConversionDecl *Conversion
  2899. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  2900. // C++ [over.ics.user]p1:
  2901. //
  2902. // [...] If the user-defined conversion is specified by a
  2903. // conversion function (12.3.2), the initial standard
  2904. // conversion sequence converts the source type to the
  2905. // implicit object parameter of the conversion function.
  2906. User.Before = Best->Conversions[0].Standard;
  2907. User.HadMultipleCandidates = HadMultipleCandidates;
  2908. User.ConversionFunction = Conversion;
  2909. User.FoundConversionFunction = Best->FoundDecl;
  2910. User.EllipsisConversion = false;
  2911. // C++ [over.ics.user]p2:
  2912. // The second standard conversion sequence converts the
  2913. // result of the user-defined conversion to the target type
  2914. // for the sequence. Since an implicit conversion sequence
  2915. // is an initialization, the special rules for
  2916. // initialization by user-defined conversion apply when
  2917. // selecting the best user-defined conversion for a
  2918. // user-defined conversion sequence (see 13.3.3 and
  2919. // 13.3.3.1).
  2920. User.After = Best->FinalConversion;
  2921. return Result;
  2922. }
  2923. llvm_unreachable("Not a constructor or conversion function?");
  2924. case OR_No_Viable_Function:
  2925. return OR_No_Viable_Function;
  2926. case OR_Ambiguous:
  2927. return OR_Ambiguous;
  2928. }
  2929. llvm_unreachable("Invalid OverloadResult!");
  2930. }
  2931. bool
  2932. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  2933. ImplicitConversionSequence ICS;
  2934. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  2935. OverloadCandidateSet::CSK_Normal);
  2936. OverloadingResult OvResult =
  2937. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  2938. CandidateSet, false, false);
  2939. if (OvResult == OR_Ambiguous)
  2940. Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
  2941. << From->getType() << ToType << From->getSourceRange();
  2942. else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
  2943. if (!RequireCompleteType(From->getLocStart(), ToType,
  2944. diag::err_typecheck_nonviable_condition_incomplete,
  2945. From->getType(), From->getSourceRange()))
  2946. Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
  2947. << From->getType() << From->getSourceRange() << ToType;
  2948. } else
  2949. return false;
  2950. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
  2951. return true;
  2952. }
  2953. /// \brief Compare the user-defined conversion functions or constructors
  2954. /// of two user-defined conversion sequences to determine whether any ordering
  2955. /// is possible.
  2956. static ImplicitConversionSequence::CompareKind
  2957. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  2958. FunctionDecl *Function2) {
  2959. if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
  2960. return ImplicitConversionSequence::Indistinguishable;
  2961. // Objective-C++:
  2962. // If both conversion functions are implicitly-declared conversions from
  2963. // a lambda closure type to a function pointer and a block pointer,
  2964. // respectively, always prefer the conversion to a function pointer,
  2965. // because the function pointer is more lightweight and is more likely
  2966. // to keep code working.
  2967. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  2968. if (!Conv1)
  2969. return ImplicitConversionSequence::Indistinguishable;
  2970. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  2971. if (!Conv2)
  2972. return ImplicitConversionSequence::Indistinguishable;
  2973. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  2974. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  2975. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  2976. if (Block1 != Block2)
  2977. return Block1 ? ImplicitConversionSequence::Worse
  2978. : ImplicitConversionSequence::Better;
  2979. }
  2980. return ImplicitConversionSequence::Indistinguishable;
  2981. }
  2982. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  2983. const ImplicitConversionSequence &ICS) {
  2984. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  2985. (ICS.isUserDefined() &&
  2986. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  2987. }
  2988. /// CompareImplicitConversionSequences - Compare two implicit
  2989. /// conversion sequences to determine whether one is better than the
  2990. /// other or if they are indistinguishable (C++ 13.3.3.2).
  2991. static ImplicitConversionSequence::CompareKind
  2992. CompareImplicitConversionSequences(Sema &S,
  2993. const ImplicitConversionSequence& ICS1,
  2994. const ImplicitConversionSequence& ICS2)
  2995. {
  2996. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  2997. // conversion sequences (as defined in 13.3.3.1)
  2998. // -- a standard conversion sequence (13.3.3.1.1) is a better
  2999. // conversion sequence than a user-defined conversion sequence or
  3000. // an ellipsis conversion sequence, and
  3001. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3002. // conversion sequence than an ellipsis conversion sequence
  3003. // (13.3.3.1.3).
  3004. //
  3005. // C++0x [over.best.ics]p10:
  3006. // For the purpose of ranking implicit conversion sequences as
  3007. // described in 13.3.3.2, the ambiguous conversion sequence is
  3008. // treated as a user-defined sequence that is indistinguishable
  3009. // from any other user-defined conversion sequence.
  3010. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3011. // been removed from C++11. We still accept this conversion, if it happens at
  3012. // the best viable function. Otherwise, this conversion is considered worse
  3013. // than ellipsis conversion. Consider this as an extension; this is not in the
  3014. // standard. For example:
  3015. //
  3016. // int &f(...); // #1
  3017. // void f(char*); // #2
  3018. // void g() { int &r = f("foo"); }
  3019. //
  3020. // In C++03, we pick #2 as the best viable function.
  3021. // In C++11, we pick #1 as the best viable function, because ellipsis
  3022. // conversion is better than string-literal to char* conversion (since there
  3023. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3024. // convert arguments, #2 would be the best viable function in C++11.
  3025. // If the best viable function has this conversion, a warning will be issued
  3026. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3027. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3028. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3029. hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
  3030. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3031. ? ImplicitConversionSequence::Worse
  3032. : ImplicitConversionSequence::Better;
  3033. // HLSL Change Starts
  3034. // This ranking happens in HLSL as part of diagnostics; otherwise the specific ranking is used.
  3035. if (S.getLangOpts().HLSL) {
  3036. if (!ICS1.isInitialized() || !ICS2.isInitialized())
  3037. return ImplicitConversionSequence::Indistinguishable;
  3038. }
  3039. // HLSL Change Ends
  3040. if (ICS1.getKindRank() < ICS2.getKindRank())
  3041. return ImplicitConversionSequence::Better;
  3042. if (ICS2.getKindRank() < ICS1.getKindRank())
  3043. return ImplicitConversionSequence::Worse;
  3044. // The following checks require both conversion sequences to be of
  3045. // the same kind.
  3046. if (ICS1.getKind() != ICS2.getKind())
  3047. return ImplicitConversionSequence::Indistinguishable;
  3048. ImplicitConversionSequence::CompareKind Result =
  3049. ImplicitConversionSequence::Indistinguishable;
  3050. // Two implicit conversion sequences of the same form are
  3051. // indistinguishable conversion sequences unless one of the
  3052. // following rules apply: (C++ 13.3.3.2p3):
  3053. // List-initialization sequence L1 is a better conversion sequence than
  3054. // list-initialization sequence L2 if:
  3055. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3056. // if not that,
  3057. // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
  3058. // and N1 is smaller than N2.,
  3059. // even if one of the other rules in this paragraph would otherwise apply.
  3060. if (!ICS1.isBad()) {
  3061. if (ICS1.isStdInitializerListElement() &&
  3062. !ICS2.isStdInitializerListElement())
  3063. return ImplicitConversionSequence::Better;
  3064. if (!ICS1.isStdInitializerListElement() &&
  3065. ICS2.isStdInitializerListElement())
  3066. return ImplicitConversionSequence::Worse;
  3067. }
  3068. if (ICS1.isStandard())
  3069. // Standard conversion sequence S1 is a better conversion sequence than
  3070. // standard conversion sequence S2 if [...]
  3071. Result = CompareStandardConversionSequences(S,
  3072. ICS1.Standard, ICS2.Standard);
  3073. else if (ICS1.isUserDefined()) {
  3074. // User-defined conversion sequence U1 is a better conversion
  3075. // sequence than another user-defined conversion sequence U2 if
  3076. // they contain the same user-defined conversion function or
  3077. // constructor and if the second standard conversion sequence of
  3078. // U1 is better than the second standard conversion sequence of
  3079. // U2 (C++ 13.3.3.2p3).
  3080. if (ICS1.UserDefined.ConversionFunction ==
  3081. ICS2.UserDefined.ConversionFunction)
  3082. Result = CompareStandardConversionSequences(S,
  3083. ICS1.UserDefined.After,
  3084. ICS2.UserDefined.After);
  3085. else
  3086. Result = compareConversionFunctions(S,
  3087. ICS1.UserDefined.ConversionFunction,
  3088. ICS2.UserDefined.ConversionFunction);
  3089. }
  3090. return Result;
  3091. }
  3092. static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
  3093. while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3094. Qualifiers Quals;
  3095. T1 = Context.getUnqualifiedArrayType(T1, Quals);
  3096. T2 = Context.getUnqualifiedArrayType(T2, Quals);
  3097. }
  3098. return Context.hasSameUnqualifiedType(T1, T2);
  3099. }
  3100. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3101. // determine if one is a proper subset of the other.
  3102. static ImplicitConversionSequence::CompareKind
  3103. compareStandardConversionSubsets(ASTContext &Context,
  3104. const StandardConversionSequence& SCS1,
  3105. const StandardConversionSequence& SCS2) {
  3106. ImplicitConversionSequence::CompareKind Result
  3107. = ImplicitConversionSequence::Indistinguishable;
  3108. // the identity conversion sequence is considered to be a subsequence of
  3109. // any non-identity conversion sequence
  3110. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3111. return ImplicitConversionSequence::Better;
  3112. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3113. return ImplicitConversionSequence::Worse;
  3114. if (SCS1.Second != SCS2.Second) {
  3115. if (SCS1.Second == ICK_Identity)
  3116. Result = ImplicitConversionSequence::Better;
  3117. else if (SCS2.Second == ICK_Identity)
  3118. Result = ImplicitConversionSequence::Worse;
  3119. else
  3120. return ImplicitConversionSequence::Indistinguishable;
  3121. } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
  3122. return ImplicitConversionSequence::Indistinguishable;
  3123. if (SCS1.Third == SCS2.Third) {
  3124. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3125. : ImplicitConversionSequence::Indistinguishable;
  3126. }
  3127. if (SCS1.Third == ICK_Identity)
  3128. return Result == ImplicitConversionSequence::Worse
  3129. ? ImplicitConversionSequence::Indistinguishable
  3130. : ImplicitConversionSequence::Better;
  3131. if (SCS2.Third == ICK_Identity)
  3132. return Result == ImplicitConversionSequence::Better
  3133. ? ImplicitConversionSequence::Indistinguishable
  3134. : ImplicitConversionSequence::Worse;
  3135. return ImplicitConversionSequence::Indistinguishable;
  3136. }
  3137. /// \brief Determine whether one of the given reference bindings is better
  3138. /// than the other based on what kind of bindings they are.
  3139. static bool
  3140. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3141. const StandardConversionSequence &SCS2) {
  3142. // C++0x [over.ics.rank]p3b4:
  3143. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3144. // implicit object parameter of a non-static member function declared
  3145. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3146. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3147. // lvalue reference to a function lvalue and S2 binds an rvalue
  3148. // reference*.
  3149. //
  3150. // FIXME: Rvalue references. We're going rogue with the above edits,
  3151. // because the semantics in the current C++0x working paper (N3225 at the
  3152. // time of this writing) break the standard definition of std::forward
  3153. // and std::reference_wrapper when dealing with references to functions.
  3154. // Proposed wording changes submitted to CWG for consideration.
  3155. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3156. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3157. return false;
  3158. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3159. SCS2.IsLvalueReference) ||
  3160. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3161. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3162. }
  3163. /// CompareStandardConversionSequences - Compare two standard
  3164. /// conversion sequences to determine whether one is better than the
  3165. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3166. static ImplicitConversionSequence::CompareKind
  3167. CompareStandardConversionSequences(Sema &S,
  3168. const StandardConversionSequence& SCS1,
  3169. const StandardConversionSequence& SCS2)
  3170. {
  3171. // Standard conversion sequence S1 is a better conversion sequence
  3172. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3173. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3174. // sequences in the canonical form defined by 13.3.3.1.1,
  3175. // excluding any Lvalue Transformation; the identity conversion
  3176. // sequence is considered to be a subsequence of any
  3177. // non-identity conversion sequence) or, if not that,
  3178. if (ImplicitConversionSequence::CompareKind CK
  3179. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3180. return CK;
  3181. // -- the rank of S1 is better than the rank of S2 (by the rules
  3182. // defined below), or, if not that,
  3183. ImplicitConversionRank Rank1 = SCS1.getRank();
  3184. ImplicitConversionRank Rank2 = SCS2.getRank();
  3185. if (Rank1 < Rank2)
  3186. return ImplicitConversionSequence::Better;
  3187. else if (Rank2 < Rank1)
  3188. return ImplicitConversionSequence::Worse;
  3189. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3190. // are indistinguishable unless one of the following rules
  3191. // applies:
  3192. // A conversion that is not a conversion of a pointer, or
  3193. // pointer to member, to bool is better than another conversion
  3194. // that is such a conversion.
  3195. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3196. return SCS2.isPointerConversionToBool()
  3197. ? ImplicitConversionSequence::Better
  3198. : ImplicitConversionSequence::Worse;
  3199. // C++ [over.ics.rank]p4b2:
  3200. //
  3201. // If class B is derived directly or indirectly from class A,
  3202. // conversion of B* to A* is better than conversion of B* to
  3203. // void*, and conversion of A* to void* is better than conversion
  3204. // of B* to void*.
  3205. bool SCS1ConvertsToVoid
  3206. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3207. bool SCS2ConvertsToVoid
  3208. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3209. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3210. // Exactly one of the conversion sequences is a conversion to
  3211. // a void pointer; it's the worse conversion.
  3212. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3213. : ImplicitConversionSequence::Worse;
  3214. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3215. // Neither conversion sequence converts to a void pointer; compare
  3216. // their derived-to-base conversions.
  3217. if (ImplicitConversionSequence::CompareKind DerivedCK
  3218. = CompareDerivedToBaseConversions(S, SCS1, SCS2))
  3219. return DerivedCK;
  3220. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3221. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3222. // Both conversion sequences are conversions to void
  3223. // pointers. Compare the source types to determine if there's an
  3224. // inheritance relationship in their sources.
  3225. QualType FromType1 = SCS1.getFromType();
  3226. QualType FromType2 = SCS2.getFromType();
  3227. // Adjust the types we're converting from via the array-to-pointer
  3228. // conversion, if we need to.
  3229. if (SCS1.First == ICK_Array_To_Pointer)
  3230. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3231. if (SCS2.First == ICK_Array_To_Pointer)
  3232. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3233. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3234. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3235. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3236. return ImplicitConversionSequence::Better;
  3237. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3238. return ImplicitConversionSequence::Worse;
  3239. // Objective-C++: If one interface is more specific than the
  3240. // other, it is the better one.
  3241. const ObjCObjectPointerType* FromObjCPtr1
  3242. = FromType1->getAs<ObjCObjectPointerType>();
  3243. const ObjCObjectPointerType* FromObjCPtr2
  3244. = FromType2->getAs<ObjCObjectPointerType>();
  3245. if (FromObjCPtr1 && FromObjCPtr2) {
  3246. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3247. FromObjCPtr2);
  3248. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3249. FromObjCPtr1);
  3250. if (AssignLeft != AssignRight) {
  3251. return AssignLeft? ImplicitConversionSequence::Better
  3252. : ImplicitConversionSequence::Worse;
  3253. }
  3254. }
  3255. }
  3256. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3257. // bullet 3).
  3258. if (ImplicitConversionSequence::CompareKind QualCK
  3259. = CompareQualificationConversions(S, SCS1, SCS2))
  3260. return QualCK;
  3261. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3262. // Check for a better reference binding based on the kind of bindings.
  3263. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3264. return ImplicitConversionSequence::Better;
  3265. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3266. return ImplicitConversionSequence::Worse;
  3267. // C++ [over.ics.rank]p3b4:
  3268. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3269. // which the references refer are the same type except for
  3270. // top-level cv-qualifiers, and the type to which the reference
  3271. // initialized by S2 refers is more cv-qualified than the type
  3272. // to which the reference initialized by S1 refers.
  3273. QualType T1 = SCS1.getToType(2);
  3274. QualType T2 = SCS2.getToType(2);
  3275. T1 = S.Context.getCanonicalType(T1);
  3276. T2 = S.Context.getCanonicalType(T2);
  3277. Qualifiers T1Quals, T2Quals;
  3278. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3279. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3280. if (UnqualT1 == UnqualT2) {
  3281. // Objective-C++ ARC: If the references refer to objects with different
  3282. // lifetimes, prefer bindings that don't change lifetime.
  3283. if (SCS1.ObjCLifetimeConversionBinding !=
  3284. SCS2.ObjCLifetimeConversionBinding) {
  3285. return SCS1.ObjCLifetimeConversionBinding
  3286. ? ImplicitConversionSequence::Worse
  3287. : ImplicitConversionSequence::Better;
  3288. }
  3289. // If the type is an array type, promote the element qualifiers to the
  3290. // type for comparison.
  3291. if (isa<ArrayType>(T1) && T1Quals)
  3292. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3293. if (isa<ArrayType>(T2) && T2Quals)
  3294. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3295. if (T2.isMoreQualifiedThan(T1))
  3296. return ImplicitConversionSequence::Better;
  3297. else if (T1.isMoreQualifiedThan(T2))
  3298. return ImplicitConversionSequence::Worse;
  3299. }
  3300. }
  3301. // In Microsoft mode, prefer an integral conversion to a
  3302. // floating-to-integral conversion if the integral conversion
  3303. // is between types of the same size.
  3304. // For example:
  3305. // void f(float);
  3306. // void f(int);
  3307. // int main {
  3308. // long a;
  3309. // f(a);
  3310. // }
  3311. // Here, MSVC will call f(int) instead of generating a compile error
  3312. // as clang will do in standard mode.
  3313. if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
  3314. SCS2.Second == ICK_Floating_Integral &&
  3315. S.Context.getTypeSize(SCS1.getFromType()) ==
  3316. S.Context.getTypeSize(SCS1.getToType(2)))
  3317. return ImplicitConversionSequence::Better;
  3318. return ImplicitConversionSequence::Indistinguishable;
  3319. }
  3320. /// CompareQualificationConversions - Compares two standard conversion
  3321. /// sequences to determine whether they can be ranked based on their
  3322. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3323. static ImplicitConversionSequence::CompareKind
  3324. CompareQualificationConversions(Sema &S,
  3325. const StandardConversionSequence& SCS1,
  3326. const StandardConversionSequence& SCS2) {
  3327. // C++ 13.3.3.2p3:
  3328. // -- S1 and S2 differ only in their qualification conversion and
  3329. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3330. // cv-qualification signature of type T1 is a proper subset of
  3331. // the cv-qualification signature of type T2, and S1 is not the
  3332. // deprecated string literal array-to-pointer conversion (4.2).
  3333. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3334. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3335. return ImplicitConversionSequence::Indistinguishable;
  3336. // FIXME: the example in the standard doesn't use a qualification
  3337. // conversion (!)
  3338. QualType T1 = SCS1.getToType(2);
  3339. QualType T2 = SCS2.getToType(2);
  3340. T1 = S.Context.getCanonicalType(T1);
  3341. T2 = S.Context.getCanonicalType(T2);
  3342. Qualifiers T1Quals, T2Quals;
  3343. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3344. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3345. // If the types are the same, we won't learn anything by unwrapped
  3346. // them.
  3347. if (UnqualT1 == UnqualT2)
  3348. return ImplicitConversionSequence::Indistinguishable;
  3349. // If the type is an array type, promote the element qualifiers to the type
  3350. // for comparison.
  3351. if (isa<ArrayType>(T1) && T1Quals)
  3352. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3353. if (isa<ArrayType>(T2) && T2Quals)
  3354. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3355. ImplicitConversionSequence::CompareKind Result
  3356. = ImplicitConversionSequence::Indistinguishable;
  3357. // Objective-C++ ARC:
  3358. // Prefer qualification conversions not involving a change in lifetime
  3359. // to qualification conversions that do not change lifetime.
  3360. if (SCS1.QualificationIncludesObjCLifetime !=
  3361. SCS2.QualificationIncludesObjCLifetime) {
  3362. Result = SCS1.QualificationIncludesObjCLifetime
  3363. ? ImplicitConversionSequence::Worse
  3364. : ImplicitConversionSequence::Better;
  3365. }
  3366. while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3367. // Within each iteration of the loop, we check the qualifiers to
  3368. // determine if this still looks like a qualification
  3369. // conversion. Then, if all is well, we unwrap one more level of
  3370. // pointers or pointers-to-members and do it all again
  3371. // until there are no more pointers or pointers-to-members left
  3372. // to unwrap. This essentially mimics what
  3373. // IsQualificationConversion does, but here we're checking for a
  3374. // strict subset of qualifiers.
  3375. if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
  3376. // The qualifiers are the same, so this doesn't tell us anything
  3377. // about how the sequences rank.
  3378. ;
  3379. else if (T2.isMoreQualifiedThan(T1)) {
  3380. // T1 has fewer qualifiers, so it could be the better sequence.
  3381. if (Result == ImplicitConversionSequence::Worse)
  3382. // Neither has qualifiers that are a subset of the other's
  3383. // qualifiers.
  3384. return ImplicitConversionSequence::Indistinguishable;
  3385. Result = ImplicitConversionSequence::Better;
  3386. } else if (T1.isMoreQualifiedThan(T2)) {
  3387. // T2 has fewer qualifiers, so it could be the better sequence.
  3388. if (Result == ImplicitConversionSequence::Better)
  3389. // Neither has qualifiers that are a subset of the other's
  3390. // qualifiers.
  3391. return ImplicitConversionSequence::Indistinguishable;
  3392. Result = ImplicitConversionSequence::Worse;
  3393. } else {
  3394. // Qualifiers are disjoint.
  3395. return ImplicitConversionSequence::Indistinguishable;
  3396. }
  3397. // If the types after this point are equivalent, we're done.
  3398. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3399. break;
  3400. }
  3401. // Check that the winning standard conversion sequence isn't using
  3402. // the deprecated string literal array to pointer conversion.
  3403. switch (Result) {
  3404. case ImplicitConversionSequence::Better:
  3405. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3406. Result = ImplicitConversionSequence::Indistinguishable;
  3407. break;
  3408. case ImplicitConversionSequence::Indistinguishable:
  3409. break;
  3410. case ImplicitConversionSequence::Worse:
  3411. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3412. Result = ImplicitConversionSequence::Indistinguishable;
  3413. break;
  3414. }
  3415. return Result;
  3416. }
  3417. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3418. /// sequences to determine whether they can be ranked based on their
  3419. /// various kinds of derived-to-base conversions (C++
  3420. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3421. /// conversions between Objective-C interface types.
  3422. static ImplicitConversionSequence::CompareKind
  3423. CompareDerivedToBaseConversions(Sema &S,
  3424. const StandardConversionSequence& SCS1,
  3425. const StandardConversionSequence& SCS2) {
  3426. QualType FromType1 = SCS1.getFromType();
  3427. QualType ToType1 = SCS1.getToType(1);
  3428. QualType FromType2 = SCS2.getFromType();
  3429. QualType ToType2 = SCS2.getToType(1);
  3430. // Adjust the types we're converting from via the array-to-pointer
  3431. // conversion, if we need to.
  3432. if (SCS1.First == ICK_Array_To_Pointer)
  3433. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3434. if (SCS2.First == ICK_Array_To_Pointer)
  3435. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3436. // Canonicalize all of the types.
  3437. FromType1 = S.Context.getCanonicalType(FromType1);
  3438. ToType1 = S.Context.getCanonicalType(ToType1);
  3439. FromType2 = S.Context.getCanonicalType(FromType2);
  3440. ToType2 = S.Context.getCanonicalType(ToType2);
  3441. // C++ [over.ics.rank]p4b3:
  3442. //
  3443. // If class B is derived directly or indirectly from class A and
  3444. // class C is derived directly or indirectly from B,
  3445. //
  3446. // Compare based on pointer conversions.
  3447. if (SCS1.Second == ICK_Pointer_Conversion &&
  3448. SCS2.Second == ICK_Pointer_Conversion &&
  3449. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3450. FromType1->isPointerType() && FromType2->isPointerType() &&
  3451. ToType1->isPointerType() && ToType2->isPointerType()) {
  3452. QualType FromPointee1
  3453. = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3454. QualType ToPointee1
  3455. = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3456. QualType FromPointee2
  3457. = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3458. QualType ToPointee2
  3459. = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3460. // -- conversion of C* to B* is better than conversion of C* to A*,
  3461. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3462. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3463. return ImplicitConversionSequence::Better;
  3464. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3465. return ImplicitConversionSequence::Worse;
  3466. }
  3467. // -- conversion of B* to A* is better than conversion of C* to A*,
  3468. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3469. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3470. return ImplicitConversionSequence::Better;
  3471. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3472. return ImplicitConversionSequence::Worse;
  3473. }
  3474. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3475. SCS2.Second == ICK_Pointer_Conversion) {
  3476. const ObjCObjectPointerType *FromPtr1
  3477. = FromType1->getAs<ObjCObjectPointerType>();
  3478. const ObjCObjectPointerType *FromPtr2
  3479. = FromType2->getAs<ObjCObjectPointerType>();
  3480. const ObjCObjectPointerType *ToPtr1
  3481. = ToType1->getAs<ObjCObjectPointerType>();
  3482. const ObjCObjectPointerType *ToPtr2
  3483. = ToType2->getAs<ObjCObjectPointerType>();
  3484. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3485. // Apply the same conversion ranking rules for Objective-C pointer types
  3486. // that we do for C++ pointers to class types. However, we employ the
  3487. // Objective-C pseudo-subtyping relationship used for assignment of
  3488. // Objective-C pointer types.
  3489. bool FromAssignLeft
  3490. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3491. bool FromAssignRight
  3492. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3493. bool ToAssignLeft
  3494. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3495. bool ToAssignRight
  3496. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3497. // A conversion to an a non-id object pointer type or qualified 'id'
  3498. // type is better than a conversion to 'id'.
  3499. if (ToPtr1->isObjCIdType() &&
  3500. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3501. return ImplicitConversionSequence::Worse;
  3502. if (ToPtr2->isObjCIdType() &&
  3503. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3504. return ImplicitConversionSequence::Better;
  3505. // A conversion to a non-id object pointer type is better than a
  3506. // conversion to a qualified 'id' type
  3507. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3508. return ImplicitConversionSequence::Worse;
  3509. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3510. return ImplicitConversionSequence::Better;
  3511. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3512. // type is better than a conversion to 'Class'.
  3513. if (ToPtr1->isObjCClassType() &&
  3514. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3515. return ImplicitConversionSequence::Worse;
  3516. if (ToPtr2->isObjCClassType() &&
  3517. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3518. return ImplicitConversionSequence::Better;
  3519. // A conversion to a non-Class object pointer type is better than a
  3520. // conversion to a qualified 'Class' type.
  3521. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3522. return ImplicitConversionSequence::Worse;
  3523. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3524. return ImplicitConversionSequence::Better;
  3525. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3526. if (S.Context.hasSameType(FromType1, FromType2) &&
  3527. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3528. (ToAssignLeft != ToAssignRight))
  3529. return ToAssignLeft? ImplicitConversionSequence::Worse
  3530. : ImplicitConversionSequence::Better;
  3531. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3532. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3533. (FromAssignLeft != FromAssignRight))
  3534. return FromAssignLeft? ImplicitConversionSequence::Better
  3535. : ImplicitConversionSequence::Worse;
  3536. }
  3537. }
  3538. // Ranking of member-pointer types.
  3539. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3540. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3541. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3542. const MemberPointerType * FromMemPointer1 =
  3543. FromType1->getAs<MemberPointerType>();
  3544. const MemberPointerType * ToMemPointer1 =
  3545. ToType1->getAs<MemberPointerType>();
  3546. const MemberPointerType * FromMemPointer2 =
  3547. FromType2->getAs<MemberPointerType>();
  3548. const MemberPointerType * ToMemPointer2 =
  3549. ToType2->getAs<MemberPointerType>();
  3550. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3551. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3552. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3553. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3554. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3555. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3556. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3557. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3558. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3559. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3560. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3561. return ImplicitConversionSequence::Worse;
  3562. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3563. return ImplicitConversionSequence::Better;
  3564. }
  3565. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3566. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3567. if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3568. return ImplicitConversionSequence::Better;
  3569. else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3570. return ImplicitConversionSequence::Worse;
  3571. }
  3572. }
  3573. if (SCS1.Second == ICK_Derived_To_Base) {
  3574. // -- conversion of C to B is better than conversion of C to A,
  3575. // -- binding of an expression of type C to a reference of type
  3576. // B& is better than binding an expression of type C to a
  3577. // reference of type A&,
  3578. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3579. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3580. if (S.IsDerivedFrom(ToType1, ToType2))
  3581. return ImplicitConversionSequence::Better;
  3582. else if (S.IsDerivedFrom(ToType2, ToType1))
  3583. return ImplicitConversionSequence::Worse;
  3584. }
  3585. // -- conversion of B to A is better than conversion of C to A.
  3586. // -- binding of an expression of type B to a reference of type
  3587. // A& is better than binding an expression of type C to a
  3588. // reference of type A&,
  3589. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3590. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3591. if (S.IsDerivedFrom(FromType2, FromType1))
  3592. return ImplicitConversionSequence::Better;
  3593. else if (S.IsDerivedFrom(FromType1, FromType2))
  3594. return ImplicitConversionSequence::Worse;
  3595. }
  3596. }
  3597. return ImplicitConversionSequence::Indistinguishable;
  3598. }
  3599. /// \brief Determine whether the given type is valid, e.g., it is not an invalid
  3600. /// C++ class.
  3601. static bool isTypeValid(QualType T) {
  3602. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3603. return !Record->isInvalidDecl();
  3604. return true;
  3605. }
  3606. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3607. /// determine whether they are reference-related,
  3608. /// reference-compatible, reference-compatible with added
  3609. /// qualification, or incompatible, for use in C++ initialization by
  3610. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3611. /// type, and the first type (T1) is the pointee type of the reference
  3612. /// type being initialized.
  3613. Sema::ReferenceCompareResult
  3614. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3615. QualType OrigT1, QualType OrigT2,
  3616. bool &DerivedToBase,
  3617. bool &ObjCConversion,
  3618. bool &ObjCLifetimeConversion) {
  3619. assert(!OrigT1->isReferenceType() &&
  3620. "T1 must be the pointee type of the reference type");
  3621. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3622. QualType T1 = Context.getCanonicalType(OrigT1);
  3623. QualType T2 = Context.getCanonicalType(OrigT2);
  3624. Qualifiers T1Quals, T2Quals;
  3625. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3626. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3627. // C++ [dcl.init.ref]p4:
  3628. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3629. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3630. // T1 is a base class of T2.
  3631. DerivedToBase = false;
  3632. ObjCConversion = false;
  3633. ObjCLifetimeConversion = false;
  3634. if (UnqualT1 == UnqualT2) {
  3635. // Nothing to do.
  3636. } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
  3637. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3638. IsDerivedFrom(UnqualT2, UnqualT1))
  3639. DerivedToBase = true;
  3640. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3641. UnqualT2->isObjCObjectOrInterfaceType() &&
  3642. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3643. ObjCConversion = true;
  3644. else
  3645. return Ref_Incompatible;
  3646. // At this point, we know that T1 and T2 are reference-related (at
  3647. // least).
  3648. // If the type is an array type, promote the element qualifiers to the type
  3649. // for comparison.
  3650. if (isa<ArrayType>(T1) && T1Quals)
  3651. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3652. if (isa<ArrayType>(T2) && T2Quals)
  3653. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3654. // C++ [dcl.init.ref]p4:
  3655. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3656. // reference-related to T2 and cv1 is the same cv-qualification
  3657. // as, or greater cv-qualification than, cv2. For purposes of
  3658. // overload resolution, cases for which cv1 is greater
  3659. // cv-qualification than cv2 are identified as
  3660. // reference-compatible with added qualification (see 13.3.3.2).
  3661. //
  3662. // Note that we also require equivalence of Objective-C GC and address-space
  3663. // qualifiers when performing these computations, so that e.g., an int in
  3664. // address space 1 is not reference-compatible with an int in address
  3665. // space 2.
  3666. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3667. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3668. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3669. ObjCLifetimeConversion = true;
  3670. T1Quals.removeObjCLifetime();
  3671. T2Quals.removeObjCLifetime();
  3672. }
  3673. if (T1Quals == T2Quals)
  3674. return Ref_Compatible;
  3675. else if (T1Quals.compatiblyIncludes(T2Quals))
  3676. return Ref_Compatible_With_Added_Qualification;
  3677. else
  3678. return Ref_Related;
  3679. }
  3680. /// \brief Look for a user-defined conversion to an value reference-compatible
  3681. /// with DeclType. Return true if something definite is found.
  3682. static bool
  3683. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  3684. QualType DeclType, SourceLocation DeclLoc,
  3685. Expr *Init, QualType T2, bool AllowRvalues,
  3686. bool AllowExplicit) {
  3687. assert(T2->isRecordType() && "Can only find conversions of record types.");
  3688. CXXRecordDecl *T2RecordDecl
  3689. = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
  3690. OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
  3691. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3692. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3693. NamedDecl *D = *I;
  3694. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3695. if (isa<UsingShadowDecl>(D))
  3696. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3697. FunctionTemplateDecl *ConvTemplate
  3698. = dyn_cast<FunctionTemplateDecl>(D);
  3699. CXXConversionDecl *Conv;
  3700. if (ConvTemplate)
  3701. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3702. else
  3703. Conv = cast<CXXConversionDecl>(D);
  3704. // If this is an explicit conversion, and we're not allowed to consider
  3705. // explicit conversions, skip it.
  3706. if (!AllowExplicit && Conv->isExplicit())
  3707. continue;
  3708. if (AllowRvalues) {
  3709. bool DerivedToBase = false;
  3710. bool ObjCConversion = false;
  3711. bool ObjCLifetimeConversion = false;
  3712. // If we are initializing an rvalue reference, don't permit conversion
  3713. // functions that return lvalues.
  3714. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  3715. const ReferenceType *RefType
  3716. = Conv->getConversionType()->getAs<LValueReferenceType>();
  3717. if (RefType && !RefType->getPointeeType()->isFunctionType())
  3718. continue;
  3719. }
  3720. if (!ConvTemplate &&
  3721. S.CompareReferenceRelationship(
  3722. DeclLoc,
  3723. Conv->getConversionType().getNonReferenceType()
  3724. .getUnqualifiedType(),
  3725. DeclType.getNonReferenceType().getUnqualifiedType(),
  3726. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  3727. Sema::Ref_Incompatible)
  3728. continue;
  3729. } else {
  3730. // If the conversion function doesn't return a reference type,
  3731. // it can't be considered for this conversion. An rvalue reference
  3732. // is only acceptable if its referencee is a function type.
  3733. const ReferenceType *RefType =
  3734. Conv->getConversionType()->getAs<ReferenceType>();
  3735. if (!RefType ||
  3736. (!RefType->isLValueReferenceType() &&
  3737. !RefType->getPointeeType()->isFunctionType()))
  3738. continue;
  3739. }
  3740. if (ConvTemplate)
  3741. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
  3742. Init, DeclType, CandidateSet,
  3743. /*AllowObjCConversionOnExplicit=*/false);
  3744. else
  3745. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
  3746. DeclType, CandidateSet,
  3747. /*AllowObjCConversionOnExplicit=*/false);
  3748. }
  3749. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3750. OverloadCandidateSet::iterator Best;
  3751. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  3752. case OR_Success:
  3753. // C++ [over.ics.ref]p1:
  3754. //
  3755. // [...] If the parameter binds directly to the result of
  3756. // applying a conversion function to the argument
  3757. // expression, the implicit conversion sequence is a
  3758. // user-defined conversion sequence (13.3.3.1.2), with the
  3759. // second standard conversion sequence either an identity
  3760. // conversion or, if the conversion function returns an
  3761. // entity of a type that is a derived class of the parameter
  3762. // type, a derived-to-base Conversion.
  3763. if (!Best->FinalConversion.DirectBinding)
  3764. return false;
  3765. ICS.setUserDefined();
  3766. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  3767. ICS.UserDefined.After = Best->FinalConversion;
  3768. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  3769. ICS.UserDefined.ConversionFunction = Best->Function;
  3770. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  3771. ICS.UserDefined.EllipsisConversion = false;
  3772. assert(ICS.UserDefined.After.ReferenceBinding &&
  3773. ICS.UserDefined.After.DirectBinding &&
  3774. "Expected a direct reference binding!");
  3775. return true;
  3776. case OR_Ambiguous:
  3777. ICS.setAmbiguous();
  3778. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  3779. Cand != CandidateSet.end(); ++Cand)
  3780. if (Cand->Viable)
  3781. ICS.Ambiguous.addConversion(Cand->Function);
  3782. return true;
  3783. case OR_No_Viable_Function:
  3784. case OR_Deleted:
  3785. // There was no suitable conversion, or we found a deleted
  3786. // conversion; continue with other checks.
  3787. return false;
  3788. }
  3789. llvm_unreachable("Invalid OverloadResult!");
  3790. }
  3791. /// \brief Compute an implicit conversion sequence for reference
  3792. /// initialization.
  3793. static ImplicitConversionSequence
  3794. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  3795. SourceLocation DeclLoc,
  3796. bool SuppressUserConversions,
  3797. bool AllowExplicit) {
  3798. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  3799. // Most paths end in a failed conversion.
  3800. ImplicitConversionSequence ICS;
  3801. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3802. QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
  3803. QualType T2 = Init->getType();
  3804. // If the initializer is the address of an overloaded function, try
  3805. // to resolve the overloaded function. If all goes well, T2 is the
  3806. // type of the resulting function.
  3807. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  3808. DeclAccessPair Found;
  3809. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  3810. false, Found))
  3811. T2 = Fn->getType();
  3812. }
  3813. // Compute some basic properties of the types and the initializer.
  3814. bool isRValRef = DeclType->isRValueReferenceType();
  3815. bool DerivedToBase = false;
  3816. bool ObjCConversion = false;
  3817. bool ObjCLifetimeConversion = false;
  3818. Expr::Classification InitCategory = Init->Classify(S.Context);
  3819. Sema::ReferenceCompareResult RefRelationship
  3820. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  3821. ObjCConversion, ObjCLifetimeConversion);
  3822. // C++0x [dcl.init.ref]p5:
  3823. // A reference to type "cv1 T1" is initialized by an expression
  3824. // of type "cv2 T2" as follows:
  3825. // -- If reference is an lvalue reference and the initializer expression
  3826. if (!isRValRef) {
  3827. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  3828. // reference-compatible with "cv2 T2," or
  3829. //
  3830. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  3831. if (InitCategory.isLValue() &&
  3832. RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
  3833. // C++ [over.ics.ref]p1:
  3834. // When a parameter of reference type binds directly (8.5.3)
  3835. // to an argument expression, the implicit conversion sequence
  3836. // is the identity conversion, unless the argument expression
  3837. // has a type that is a derived class of the parameter type,
  3838. // in which case the implicit conversion sequence is a
  3839. // derived-to-base Conversion (13.3.3.1).
  3840. ICS.setStandard();
  3841. ICS.Standard.First = ICK_Identity;
  3842. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3843. : ObjCConversion? ICK_Compatible_Conversion
  3844. : ICK_Identity;
  3845. ICS.Standard.Third = ICK_Identity;
  3846. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3847. ICS.Standard.setToType(0, T2);
  3848. ICS.Standard.setToType(1, T1);
  3849. ICS.Standard.setToType(2, T1);
  3850. ICS.Standard.ReferenceBinding = true;
  3851. ICS.Standard.DirectBinding = true;
  3852. ICS.Standard.IsLvalueReference = !isRValRef;
  3853. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3854. ICS.Standard.BindsToRvalue = false;
  3855. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3856. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3857. ICS.Standard.CopyConstructor = nullptr;
  3858. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3859. // Nothing more to do: the inaccessibility/ambiguity check for
  3860. // derived-to-base conversions is suppressed when we're
  3861. // computing the implicit conversion sequence (C++
  3862. // [over.best.ics]p2).
  3863. return ICS;
  3864. }
  3865. // -- has a class type (i.e., T2 is a class type), where T1 is
  3866. // not reference-related to T2, and can be implicitly
  3867. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  3868. // is reference-compatible with "cv3 T3" 92) (this
  3869. // conversion is selected by enumerating the applicable
  3870. // conversion functions (13.3.1.6) and choosing the best
  3871. // one through overload resolution (13.3)),
  3872. if (!SuppressUserConversions && T2->isRecordType() &&
  3873. !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3874. RefRelationship == Sema::Ref_Incompatible) {
  3875. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3876. Init, T2, /*AllowRvalues=*/false,
  3877. AllowExplicit))
  3878. return ICS;
  3879. }
  3880. }
  3881. // -- Otherwise, the reference shall be an lvalue reference to a
  3882. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3883. // shall be an rvalue reference.
  3884. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  3885. return ICS;
  3886. // -- If the initializer expression
  3887. //
  3888. // -- is an xvalue, class prvalue, array prvalue or function
  3889. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  3890. if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
  3891. (InitCategory.isXValue() ||
  3892. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  3893. (InitCategory.isLValue() && T2->isFunctionType()))) {
  3894. ICS.setStandard();
  3895. ICS.Standard.First = ICK_Identity;
  3896. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3897. : ObjCConversion? ICK_Compatible_Conversion
  3898. : ICK_Identity;
  3899. ICS.Standard.Third = ICK_Identity;
  3900. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3901. ICS.Standard.setToType(0, T2);
  3902. ICS.Standard.setToType(1, T1);
  3903. ICS.Standard.setToType(2, T1);
  3904. ICS.Standard.ReferenceBinding = true;
  3905. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  3906. // binding unless we're binding to a class prvalue.
  3907. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  3908. // allow the use of rvalue references in C++98/03 for the benefit of
  3909. // standard library implementors; therefore, we need the xvalue check here.
  3910. ICS.Standard.DirectBinding =
  3911. S.getLangOpts().CPlusPlus11 ||
  3912. !(InitCategory.isPRValue() || T2->isRecordType());
  3913. ICS.Standard.IsLvalueReference = !isRValRef;
  3914. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3915. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  3916. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3917. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3918. ICS.Standard.CopyConstructor = nullptr;
  3919. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3920. return ICS;
  3921. }
  3922. // -- has a class type (i.e., T2 is a class type), where T1 is not
  3923. // reference-related to T2, and can be implicitly converted to
  3924. // an xvalue, class prvalue, or function lvalue of type
  3925. // "cv3 T3", where "cv1 T1" is reference-compatible with
  3926. // "cv3 T3",
  3927. //
  3928. // then the reference is bound to the value of the initializer
  3929. // expression in the first case and to the result of the conversion
  3930. // in the second case (or, in either case, to an appropriate base
  3931. // class subobject).
  3932. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3933. T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3934. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3935. Init, T2, /*AllowRvalues=*/true,
  3936. AllowExplicit)) {
  3937. // In the second case, if the reference is an rvalue reference
  3938. // and the second standard conversion sequence of the
  3939. // user-defined conversion sequence includes an lvalue-to-rvalue
  3940. // conversion, the program is ill-formed.
  3941. if (ICS.isUserDefined() && isRValRef &&
  3942. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  3943. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3944. return ICS;
  3945. }
  3946. // A temporary of function type cannot be created; don't even try.
  3947. if (T1->isFunctionType())
  3948. return ICS;
  3949. // -- Otherwise, a temporary of type "cv1 T1" is created and
  3950. // initialized from the initializer expression using the
  3951. // rules for a non-reference copy initialization (8.5). The
  3952. // reference is then bound to the temporary. If T1 is
  3953. // reference-related to T2, cv1 must be the same
  3954. // cv-qualification as, or greater cv-qualification than,
  3955. // cv2; otherwise, the program is ill-formed.
  3956. if (RefRelationship == Sema::Ref_Related) {
  3957. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  3958. // we would be reference-compatible or reference-compatible with
  3959. // added qualification. But that wasn't the case, so the reference
  3960. // initialization fails.
  3961. //
  3962. // Note that we only want to check address spaces and cvr-qualifiers here.
  3963. // ObjC GC and lifetime qualifiers aren't important.
  3964. Qualifiers T1Quals = T1.getQualifiers();
  3965. Qualifiers T2Quals = T2.getQualifiers();
  3966. T1Quals.removeObjCGCAttr();
  3967. T1Quals.removeObjCLifetime();
  3968. T2Quals.removeObjCGCAttr();
  3969. T2Quals.removeObjCLifetime();
  3970. if (!T1Quals.compatiblyIncludes(T2Quals))
  3971. return ICS;
  3972. }
  3973. // If at least one of the types is a class type, the types are not
  3974. // related, and we aren't allowed any user conversions, the
  3975. // reference binding fails. This case is important for breaking
  3976. // recursion, since TryImplicitConversion below will attempt to
  3977. // create a temporary through the use of a copy constructor.
  3978. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3979. (T1->isRecordType() || T2->isRecordType()))
  3980. return ICS;
  3981. // If T1 is reference-related to T2 and the reference is an rvalue
  3982. // reference, the initializer expression shall not be an lvalue.
  3983. if (RefRelationship >= Sema::Ref_Related &&
  3984. isRValRef && Init->Classify(S.Context).isLValue())
  3985. return ICS;
  3986. // C++ [over.ics.ref]p2:
  3987. // When a parameter of reference type is not bound directly to
  3988. // an argument expression, the conversion sequence is the one
  3989. // required to convert the argument expression to the
  3990. // underlying type of the reference according to
  3991. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  3992. // to copy-initializing a temporary of the underlying type with
  3993. // the argument expression. Any difference in top-level
  3994. // cv-qualification is subsumed by the initialization itself
  3995. // and does not constitute a conversion.
  3996. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  3997. /*AllowExplicit=*/false,
  3998. /*InOverloadResolution=*/false,
  3999. /*CStyle=*/false,
  4000. /*AllowObjCWritebackConversion=*/false,
  4001. /*AllowObjCConversionOnExplicit=*/false);
  4002. // Of course, that's still a reference binding.
  4003. if (ICS.isStandard()) {
  4004. ICS.Standard.ReferenceBinding = true;
  4005. ICS.Standard.IsLvalueReference = !isRValRef;
  4006. ICS.Standard.BindsToFunctionLvalue = false;
  4007. ICS.Standard.BindsToRvalue = true;
  4008. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4009. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4010. } else if (ICS.isUserDefined()) {
  4011. const ReferenceType *LValRefType =
  4012. ICS.UserDefined.ConversionFunction->getReturnType()
  4013. ->getAs<LValueReferenceType>();
  4014. // C++ [over.ics.ref]p3:
  4015. // Except for an implicit object parameter, for which see 13.3.1, a
  4016. // standard conversion sequence cannot be formed if it requires [...]
  4017. // binding an rvalue reference to an lvalue other than a function
  4018. // lvalue.
  4019. // Note that the function case is not possible here.
  4020. if (DeclType->isRValueReferenceType() && LValRefType) {
  4021. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4022. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4023. // reference to an rvalue!
  4024. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4025. return ICS;
  4026. }
  4027. ICS.UserDefined.Before.setAsIdentityConversion();
  4028. ICS.UserDefined.After.ReferenceBinding = true;
  4029. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4030. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4031. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4032. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4033. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4034. }
  4035. return ICS;
  4036. }
  4037. static ImplicitConversionSequence
  4038. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4039. bool SuppressUserConversions,
  4040. bool InOverloadResolution,
  4041. bool AllowObjCWritebackConversion,
  4042. bool AllowExplicit = false);
  4043. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4044. /// initializer list From.
  4045. static ImplicitConversionSequence
  4046. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4047. bool SuppressUserConversions,
  4048. bool InOverloadResolution,
  4049. bool AllowObjCWritebackConversion) {
  4050. // C++11 [over.ics.list]p1:
  4051. // When an argument is an initializer list, it is not an expression and
  4052. // special rules apply for converting it to a parameter type.
  4053. ImplicitConversionSequence Result;
  4054. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4055. // We need a complete type for what follows. Incomplete types can never be
  4056. // initialized from init lists.
  4057. if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
  4058. return Result;
  4059. // Per DR1467:
  4060. // If the parameter type is a class X and the initializer list has a single
  4061. // element of type cv U, where U is X or a class derived from X, the
  4062. // implicit conversion sequence is the one required to convert the element
  4063. // to the parameter type.
  4064. //
  4065. // Otherwise, if the parameter type is a character array [... ]
  4066. // and the initializer list has a single element that is an
  4067. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4068. // implicit conversion sequence is the identity conversion.
  4069. if (From->getNumInits() == 1) {
  4070. if (ToType->isRecordType()) {
  4071. QualType InitType = From->getInit(0)->getType();
  4072. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4073. S.IsDerivedFrom(InitType, ToType))
  4074. return TryCopyInitialization(S, From->getInit(0), ToType,
  4075. SuppressUserConversions,
  4076. InOverloadResolution,
  4077. AllowObjCWritebackConversion);
  4078. }
  4079. // FIXME: Check the other conditions here: array of character type,
  4080. // initializer is a string literal.
  4081. if (ToType->isArrayType()) {
  4082. InitializedEntity Entity =
  4083. InitializedEntity::InitializeParameter(S.Context, ToType,
  4084. /*Consumed=*/false);
  4085. if (S.CanPerformCopyInitialization(Entity, From)) {
  4086. Result.setStandard();
  4087. Result.Standard.setAsIdentityConversion();
  4088. Result.Standard.setFromType(ToType);
  4089. Result.Standard.setAllToTypes(ToType);
  4090. return Result;
  4091. }
  4092. }
  4093. }
  4094. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4095. // C++11 [over.ics.list]p2:
  4096. // If the parameter type is std::initializer_list<X> or "array of X" and
  4097. // all the elements can be implicitly converted to X, the implicit
  4098. // conversion sequence is the worst conversion necessary to convert an
  4099. // element of the list to X.
  4100. //
  4101. // C++14 [over.ics.list]p3:
  4102. // Otherwise, if the parameter type is "array of N X", if the initializer
  4103. // list has exactly N elements or if it has fewer than N elements and X is
  4104. // default-constructible, and if all the elements of the initializer list
  4105. // can be implicitly converted to X, the implicit conversion sequence is
  4106. // the worst conversion necessary to convert an element of the list to X.
  4107. //
  4108. // FIXME: We're missing a lot of these checks.
  4109. bool toStdInitializerList = false;
  4110. QualType X;
  4111. if (ToType->isArrayType())
  4112. X = S.Context.getAsArrayType(ToType)->getElementType();
  4113. else
  4114. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4115. if (!X.isNull()) {
  4116. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4117. Expr *Init = From->getInit(i);
  4118. ImplicitConversionSequence ICS =
  4119. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4120. InOverloadResolution,
  4121. AllowObjCWritebackConversion);
  4122. // If a single element isn't convertible, fail.
  4123. if (ICS.isBad()) {
  4124. Result = ICS;
  4125. break;
  4126. }
  4127. // Otherwise, look for the worst conversion.
  4128. if (Result.isBad() ||
  4129. CompareImplicitConversionSequences(S, ICS, Result) ==
  4130. ImplicitConversionSequence::Worse)
  4131. Result = ICS;
  4132. }
  4133. // For an empty list, we won't have computed any conversion sequence.
  4134. // Introduce the identity conversion sequence.
  4135. if (From->getNumInits() == 0) {
  4136. Result.setStandard();
  4137. Result.Standard.setAsIdentityConversion();
  4138. Result.Standard.setFromType(ToType);
  4139. Result.Standard.setAllToTypes(ToType);
  4140. }
  4141. Result.setStdInitializerListElement(toStdInitializerList);
  4142. return Result;
  4143. }
  4144. // C++14 [over.ics.list]p4:
  4145. // C++11 [over.ics.list]p3:
  4146. // Otherwise, if the parameter is a non-aggregate class X and overload
  4147. // resolution chooses a single best constructor [...] the implicit
  4148. // conversion sequence is a user-defined conversion sequence. If multiple
  4149. // constructors are viable but none is better than the others, the
  4150. // implicit conversion sequence is a user-defined conversion sequence.
  4151. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4152. // This function can deal with initializer lists.
  4153. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4154. /*AllowExplicit=*/false,
  4155. InOverloadResolution, /*CStyle=*/false,
  4156. AllowObjCWritebackConversion,
  4157. /*AllowObjCConversionOnExplicit=*/false);
  4158. }
  4159. // C++14 [over.ics.list]p5:
  4160. // C++11 [over.ics.list]p4:
  4161. // Otherwise, if the parameter has an aggregate type which can be
  4162. // initialized from the initializer list [...] the implicit conversion
  4163. // sequence is a user-defined conversion sequence.
  4164. if (ToType->isAggregateType()) {
  4165. // Type is an aggregate, argument is an init list. At this point it comes
  4166. // down to checking whether the initialization works.
  4167. // FIXME: Find out whether this parameter is consumed or not.
  4168. InitializedEntity Entity =
  4169. InitializedEntity::InitializeParameter(S.Context, ToType,
  4170. /*Consumed=*/false);
  4171. if (S.CanPerformCopyInitialization(Entity, From)) {
  4172. Result.setUserDefined();
  4173. Result.UserDefined.Before.setAsIdentityConversion();
  4174. // Initializer lists don't have a type.
  4175. Result.UserDefined.Before.setFromType(QualType());
  4176. Result.UserDefined.Before.setAllToTypes(QualType());
  4177. Result.UserDefined.After.setAsIdentityConversion();
  4178. Result.UserDefined.After.setFromType(ToType);
  4179. Result.UserDefined.After.setAllToTypes(ToType);
  4180. Result.UserDefined.ConversionFunction = nullptr;
  4181. }
  4182. return Result;
  4183. }
  4184. // C++14 [over.ics.list]p6:
  4185. // C++11 [over.ics.list]p5:
  4186. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4187. if (ToType->isReferenceType()) {
  4188. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4189. // mention initializer lists in any way. So we go by what list-
  4190. // initialization would do and try to extrapolate from that.
  4191. QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
  4192. // If the initializer list has a single element that is reference-related
  4193. // to the parameter type, we initialize the reference from that.
  4194. if (From->getNumInits() == 1) {
  4195. Expr *Init = From->getInit(0);
  4196. QualType T2 = Init->getType();
  4197. // If the initializer is the address of an overloaded function, try
  4198. // to resolve the overloaded function. If all goes well, T2 is the
  4199. // type of the resulting function.
  4200. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4201. DeclAccessPair Found;
  4202. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4203. Init, ToType, false, Found))
  4204. T2 = Fn->getType();
  4205. }
  4206. // Compute some basic properties of the types and the initializer.
  4207. bool dummy1 = false;
  4208. bool dummy2 = false;
  4209. bool dummy3 = false;
  4210. Sema::ReferenceCompareResult RefRelationship
  4211. = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
  4212. dummy2, dummy3);
  4213. if (RefRelationship >= Sema::Ref_Related) {
  4214. return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
  4215. SuppressUserConversions,
  4216. /*AllowExplicit=*/false);
  4217. }
  4218. }
  4219. // Otherwise, we bind the reference to a temporary created from the
  4220. // initializer list.
  4221. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4222. InOverloadResolution,
  4223. AllowObjCWritebackConversion);
  4224. if (Result.isFailure())
  4225. return Result;
  4226. assert(!Result.isEllipsis() &&
  4227. "Sub-initialization cannot result in ellipsis conversion.");
  4228. // Can we even bind to a temporary?
  4229. if (ToType->isRValueReferenceType() ||
  4230. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4231. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4232. Result.UserDefined.After;
  4233. SCS.ReferenceBinding = true;
  4234. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4235. SCS.BindsToRvalue = true;
  4236. SCS.BindsToFunctionLvalue = false;
  4237. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4238. SCS.ObjCLifetimeConversionBinding = false;
  4239. } else
  4240. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4241. From, ToType);
  4242. return Result;
  4243. }
  4244. // C++14 [over.ics.list]p7:
  4245. // C++11 [over.ics.list]p6:
  4246. // Otherwise, if the parameter type is not a class:
  4247. if (!ToType->isRecordType()) {
  4248. // - if the initializer list has one element that is not itself an
  4249. // initializer list, the implicit conversion sequence is the one
  4250. // required to convert the element to the parameter type.
  4251. unsigned NumInits = From->getNumInits();
  4252. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4253. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4254. SuppressUserConversions,
  4255. InOverloadResolution,
  4256. AllowObjCWritebackConversion);
  4257. // - if the initializer list has no elements, the implicit conversion
  4258. // sequence is the identity conversion.
  4259. else if (NumInits == 0) {
  4260. Result.setStandard();
  4261. Result.Standard.setAsIdentityConversion();
  4262. Result.Standard.setFromType(ToType);
  4263. Result.Standard.setAllToTypes(ToType);
  4264. }
  4265. return Result;
  4266. }
  4267. // C++14 [over.ics.list]p8:
  4268. // C++11 [over.ics.list]p7:
  4269. // In all cases other than those enumerated above, no conversion is possible
  4270. return Result;
  4271. }
  4272. /// TryCopyInitialization - Try to copy-initialize a value of type
  4273. /// ToType from the expression From. Return the implicit conversion
  4274. /// sequence required to pass this argument, which may be a bad
  4275. /// conversion sequence (meaning that the argument cannot be passed to
  4276. /// a parameter of this type). If @p SuppressUserConversions, then we
  4277. /// do not permit any user-defined conversion sequences.
  4278. static ImplicitConversionSequence
  4279. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4280. bool SuppressUserConversions,
  4281. bool InOverloadResolution,
  4282. bool AllowObjCWritebackConversion,
  4283. bool AllowExplicit) {
  4284. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4285. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4286. InOverloadResolution,AllowObjCWritebackConversion);
  4287. // HLSL Change Starts
  4288. if (S.getLangOpts().HLSL) {
  4289. // Note that this is incorrect. Copy initialization isn't syntactically
  4290. // allowed in HLSL, but C++ uses it to perform matching for argments to
  4291. // parameters.
  4292. //
  4293. // The correct fix should go to implicit conversions, but because the type
  4294. // system isn't currently up to spec, it's easier to isolate the behavior by
  4295. // putting this only on this path.
  4296. const bool ListInitFalse = false;
  4297. const bool SuppressDiagTrue = true;
  4298. const Sema::CheckedConversionKind kind = Sema::CCK_ImplicitConversion;
  4299. ImplicitConversionSequence ICS;
  4300. ICS.setStandard();
  4301. unsigned msg;
  4302. CastKind castKind;
  4303. CXXCastPath castPath;
  4304. ExprResult E(From);
  4305. if (::hlsl::TryStaticCastForHLSL(
  4306. &S, E, ToType, kind, From->getSourceRange(), msg, castKind,
  4307. castPath, ListInitFalse, SuppressDiagTrue, &ICS.Standard)) {
  4308. return ICS;
  4309. }
  4310. }
  4311. // HLSL Change Ends
  4312. if (ToType->isReferenceType())
  4313. return TryReferenceInit(S, From, ToType,
  4314. /*FIXME:*/From->getLocStart(),
  4315. SuppressUserConversions,
  4316. AllowExplicit);
  4317. return TryImplicitConversion(S, From, ToType,
  4318. SuppressUserConversions,
  4319. /*AllowExplicit=*/false,
  4320. InOverloadResolution,
  4321. /*CStyle=*/false,
  4322. AllowObjCWritebackConversion,
  4323. /*AllowObjCConversionOnExplicit=*/false);
  4324. }
  4325. static bool TryCopyInitialization(const CanQualType FromQTy,
  4326. const CanQualType ToQTy,
  4327. Sema &S,
  4328. SourceLocation Loc,
  4329. ExprValueKind FromVK) {
  4330. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4331. ImplicitConversionSequence ICS =
  4332. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4333. return !ICS.isBad();
  4334. }
  4335. /// TryObjectArgumentInitialization - Try to initialize the object
  4336. /// parameter of the given member function (@c Method) from the
  4337. /// expression @p From.
  4338. static ImplicitConversionSequence
  4339. TryObjectArgumentInitialization(Sema &S, QualType FromType,
  4340. Expr::Classification FromClassification,
  4341. CXXMethodDecl *Method,
  4342. CXXRecordDecl *ActingContext) {
  4343. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4344. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4345. // const volatile object.
  4346. unsigned Quals = isa<CXXDestructorDecl>(Method) ?
  4347. Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
  4348. QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
  4349. // Set up the conversion sequence as a "bad" conversion, to allow us
  4350. // to exit early.
  4351. ImplicitConversionSequence ICS;
  4352. // We need to have an object of class type.
  4353. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4354. FromType = PT->getPointeeType();
  4355. // When we had a pointer, it's implicitly dereferenced, so we
  4356. // better have an lvalue.
  4357. assert(FromClassification.isLValue());
  4358. }
  4359. assert(FromType->isRecordType());
  4360. // C++0x [over.match.funcs]p4:
  4361. // For non-static member functions, the type of the implicit object
  4362. // parameter is
  4363. //
  4364. // - "lvalue reference to cv X" for functions declared without a
  4365. // ref-qualifier or with the & ref-qualifier
  4366. // - "rvalue reference to cv X" for functions declared with the &&
  4367. // ref-qualifier
  4368. //
  4369. // where X is the class of which the function is a member and cv is the
  4370. // cv-qualification on the member function declaration.
  4371. //
  4372. // However, when finding an implicit conversion sequence for the argument, we
  4373. // are not allowed to create temporaries or perform user-defined conversions
  4374. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4375. // reference binding here, that allows class rvalues to bind to
  4376. // non-constant references.
  4377. // First check the qualifiers.
  4378. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4379. // HLSL Change Starts - for calls other than subscript overloads, disregard const
  4380. FromTypeCanon.removeLocalRestrict(); // HLSL Change - disregard restrict.
  4381. if (!S.getLangOpts().HLSL ||
  4382. (Method != nullptr && Method->getDeclName() == S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  4383. // HLSL Change Ends
  4384. if (ImplicitParamType.getCVRQualifiers()
  4385. != FromTypeCanon.getLocalCVRQualifiers() &&
  4386. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4387. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4388. FromType, ImplicitParamType);
  4389. return ICS;
  4390. }
  4391. } // HLSL Change - end branch
  4392. // Check that we have either the same type or a derived type. It
  4393. // affects the conversion rank.
  4394. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4395. ImplicitConversionKind SecondKind;
  4396. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4397. SecondKind = ICK_Identity;
  4398. } else if (S.IsDerivedFrom(FromType, ClassType))
  4399. SecondKind = ICK_Derived_To_Base;
  4400. else {
  4401. ICS.setBad(BadConversionSequence::unrelated_class,
  4402. FromType, ImplicitParamType);
  4403. return ICS;
  4404. }
  4405. // Check the ref-qualifier.
  4406. switch (Method->getRefQualifier()) {
  4407. case RQ_None:
  4408. // Do nothing; we don't care about lvalueness or rvalueness.
  4409. break;
  4410. case RQ_LValue:
  4411. if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
  4412. // non-const lvalue reference cannot bind to an rvalue
  4413. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4414. ImplicitParamType);
  4415. return ICS;
  4416. }
  4417. break;
  4418. case RQ_RValue:
  4419. if (!FromClassification.isRValue()) {
  4420. // rvalue reference cannot bind to an lvalue
  4421. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4422. ImplicitParamType);
  4423. return ICS;
  4424. }
  4425. break;
  4426. }
  4427. // Success. Mark this as a reference binding.
  4428. ICS.setStandard();
  4429. ICS.Standard.setAsIdentityConversion();
  4430. ICS.Standard.Second = SecondKind;
  4431. ICS.Standard.setFromType(FromType);
  4432. ICS.Standard.setAllToTypes(ImplicitParamType);
  4433. ICS.Standard.ReferenceBinding = true;
  4434. ICS.Standard.DirectBinding = true;
  4435. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4436. ICS.Standard.BindsToFunctionLvalue = false;
  4437. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4438. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4439. = (Method->getRefQualifier() == RQ_None);
  4440. ICS.Standard.ComponentConversion = ICK_Identity;
  4441. return ICS;
  4442. }
  4443. // HLSL Change Starts
  4444. static void
  4445. InitCallParamConversions(Sema &S, const FunctionProtoType *Proto,
  4446. ParmVarDecl *Param, unsigned ArgIdx, Expr *Arg,
  4447. bool SuppressUserConversions,
  4448. bool InOverloadResolution, bool AllowExplicit,
  4449. ImplicitConversionSequence &InConversion,
  4450. ImplicitConversionSequence &OutConversion) {
  4451. hlsl::ParameterModifier paramMods = Proto->getParamMods()[ArgIdx];
  4452. QualType ParamType = Proto->getParamType(ArgIdx);
  4453. if (paramMods.isAnyIn()) {
  4454. InConversion =
  4455. TryCopyInitialization(S, Arg, ParamType, SuppressUserConversions,
  4456. InOverloadResolution, false, AllowExplicit);
  4457. }
  4458. if (paramMods.isAnyOut()) {
  4459. // TryCopyInitialization takes an expression but there isn't one at this
  4460. // point - we're just trying to figure out whether the result value can be
  4461. // converted back into the argument.
  4462. if (Arg->getType().isConstant(S.getASTContext()) || !Arg->isLValue()) {
  4463. OutConversion.setBad(
  4464. BadConversionSequence::FailureKind::rvalue_ref_to_lvalue, ParamType,
  4465. Arg->getType());
  4466. return;
  4467. }
  4468. Expr *OutFrom = DeclRefExpr::Create(
  4469. S.getASTContext(), NestedNameSpecifierLoc(), SourceLocation(), Param,
  4470. true, Param->getLocation(), ParamType.getNonReferenceType(), VK_RValue, nullptr);
  4471. OutConversion = TryCopyInitialization(
  4472. S, OutFrom, Arg->getType(), SuppressUserConversions,
  4473. InOverloadResolution, false, AllowExplicit);
  4474. }
  4475. }
  4476. // HLSL Change Ends
  4477. /// PerformObjectArgumentInitialization - Perform initialization of
  4478. /// the implicit object parameter for the given Method with the given
  4479. /// expression.
  4480. ExprResult
  4481. Sema::PerformObjectArgumentInitialization(Expr *From,
  4482. NestedNameSpecifier *Qualifier,
  4483. NamedDecl *FoundDecl,
  4484. CXXMethodDecl *Method) {
  4485. QualType FromRecordType, DestType;
  4486. QualType ImplicitParamRecordType =
  4487. Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
  4488. Expr::Classification FromClassification;
  4489. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4490. FromRecordType = PT->getPointeeType();
  4491. DestType = Method->getThisType(Context);
  4492. FromClassification = Expr::Classification::makeSimpleLValue();
  4493. } else {
  4494. FromRecordType = From->getType();
  4495. DestType = ImplicitParamRecordType;
  4496. FromClassification = From->Classify(Context);
  4497. }
  4498. // Note that we always use the true parent context when performing
  4499. // the actual argument initialization.
  4500. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4501. *this, From->getType(), FromClassification, Method, Method->getParent());
  4502. if (ICS.isBad()) {
  4503. if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
  4504. Qualifiers FromQs = FromRecordType.getQualifiers();
  4505. Qualifiers ToQs = DestType.getQualifiers();
  4506. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4507. if (CVR) {
  4508. Diag(From->getLocStart(),
  4509. diag::err_member_function_call_bad_cvr)
  4510. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4511. << From->getSourceRange();
  4512. Diag(Method->getLocation(), diag::note_previous_decl)
  4513. << Method->getDeclName();
  4514. return ExprError();
  4515. }
  4516. }
  4517. return Diag(From->getLocStart(),
  4518. diag::err_implicit_object_parameter_init)
  4519. << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
  4520. }
  4521. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4522. ExprResult FromRes =
  4523. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4524. if (FromRes.isInvalid())
  4525. return ExprError();
  4526. From = FromRes.get();
  4527. }
  4528. if (!Context.hasSameType(From->getType(), DestType))
  4529. From = ImpCastExprToType(From, DestType, CK_NoOp,
  4530. From->getValueKind()).get();
  4531. return From;
  4532. }
  4533. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4534. /// expression From to bool (C++0x [conv]p3).
  4535. static ImplicitConversionSequence
  4536. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4537. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4538. /*SuppressUserConversions=*/false,
  4539. /*AllowExplicit=*/true,
  4540. /*InOverloadResolution=*/false,
  4541. /*CStyle=*/false,
  4542. /*AllowObjCWritebackConversion=*/false,
  4543. /*AllowObjCConversionOnExplicit=*/false);
  4544. }
  4545. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4546. /// of the expression From to bool (C++0x [conv]p3).
  4547. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4548. if (checkPlaceholderForOverload(*this, From))
  4549. return ExprError();
  4550. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4551. if (!ICS.isBad())
  4552. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4553. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4554. return Diag(From->getLocStart(),
  4555. diag::err_typecheck_bool_condition)
  4556. << From->getType() << From->getSourceRange();
  4557. return ExprError();
  4558. }
  4559. /// Check that the specified conversion is permitted in a converted constant
  4560. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4561. /// is acceptable.
  4562. static bool CheckConvertedConstantConversions(Sema &S,
  4563. StandardConversionSequence &SCS) {
  4564. // Since we know that the target type is an integral or unscoped enumeration
  4565. // type, most conversion kinds are impossible. All possible First and Third
  4566. // conversions are fine.
  4567. switch (SCS.Second) {
  4568. case ICK_Identity:
  4569. case ICK_NoReturn_Adjustment:
  4570. case ICK_Integral_Promotion:
  4571. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4572. return true;
  4573. case ICK_Boolean_Conversion:
  4574. // Conversion from an integral or unscoped enumeration type to bool is
  4575. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4576. // conversion, so we allow it in a converted constant expression.
  4577. //
  4578. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4579. // a lot of popular code. We should at least add a warning for this
  4580. // (non-conforming) extension.
  4581. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4582. SCS.getToType(2)->isBooleanType();
  4583. case ICK_Pointer_Conversion:
  4584. case ICK_Pointer_Member:
  4585. // C++1z: null pointer conversions and null member pointer conversions are
  4586. // only permitted if the source type is std::nullptr_t.
  4587. return SCS.getFromType()->isNullPtrType();
  4588. case ICK_Floating_Promotion:
  4589. case ICK_Complex_Promotion:
  4590. case ICK_Floating_Conversion:
  4591. case ICK_Complex_Conversion:
  4592. case ICK_Floating_Integral:
  4593. case ICK_Compatible_Conversion:
  4594. case ICK_Derived_To_Base:
  4595. case ICK_Vector_Conversion:
  4596. case ICK_Vector_Splat:
  4597. case ICK_Complex_Real:
  4598. case ICK_Block_Pointer_Conversion:
  4599. case ICK_TransparentUnionConversion:
  4600. case ICK_Writeback_Conversion:
  4601. case ICK_Zero_Event_Conversion:
  4602. case ICK_Flat_Conversion: // HLSL Change
  4603. return false;
  4604. case ICK_Lvalue_To_Rvalue:
  4605. case ICK_Array_To_Pointer:
  4606. case ICK_Function_To_Pointer:
  4607. llvm_unreachable("found a first conversion kind in Second");
  4608. case ICK_Qualification:
  4609. llvm_unreachable("found a third conversion kind in Second");
  4610. case ICK_Num_Conversion_Kinds:
  4611. break;
  4612. }
  4613. llvm_unreachable("unknown conversion kind");
  4614. }
  4615. /// CheckConvertedConstantExpression - Check that the expression From is a
  4616. /// converted constant expression of type T, perform the conversion and produce
  4617. /// the converted expression, per C++11 [expr.const]p3.
  4618. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4619. QualType T, APValue &Value,
  4620. Sema::CCEKind CCE,
  4621. bool RequireInt) {
  4622. assert(S.getLangOpts().CPlusPlus11 || S.getLangOpts().HLSLVersion >= 2017 &&
  4623. "converted constant expression outside C++11");
  4624. if (checkPlaceholderForOverload(S, From))
  4625. return ExprError();
  4626. // C++1z [expr.const]p3:
  4627. // A converted constant expression of type T is an expression,
  4628. // implicitly converted to type T, where the converted
  4629. // expression is a constant expression and the implicit conversion
  4630. // sequence contains only [... list of conversions ...].
  4631. ImplicitConversionSequence ICS =
  4632. TryCopyInitialization(S, From, T,
  4633. /*SuppressUserConversions=*/false,
  4634. /*InOverloadResolution=*/false,
  4635. /*AllowObjcWritebackConversion=*/false,
  4636. /*AllowExplicit=*/false);
  4637. StandardConversionSequence *SCS = nullptr;
  4638. switch (ICS.getKind()) {
  4639. case ImplicitConversionSequence::StandardConversion:
  4640. SCS = &ICS.Standard;
  4641. break;
  4642. case ImplicitConversionSequence::UserDefinedConversion:
  4643. // We are converting to a non-class type, so the Before sequence
  4644. // must be trivial.
  4645. SCS = &ICS.UserDefined.After;
  4646. break;
  4647. case ImplicitConversionSequence::AmbiguousConversion:
  4648. case ImplicitConversionSequence::BadConversion:
  4649. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4650. return S.Diag(From->getLocStart(),
  4651. diag::err_typecheck_converted_constant_expression)
  4652. << From->getType() << From->getSourceRange() << T;
  4653. return ExprError();
  4654. case ImplicitConversionSequence::EllipsisConversion:
  4655. llvm_unreachable("ellipsis conversion in converted constant expression");
  4656. }
  4657. // Check that we would only use permitted conversions.
  4658. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4659. return S.Diag(From->getLocStart(),
  4660. diag::err_typecheck_converted_constant_expression_disallowed)
  4661. << From->getType() << From->getSourceRange() << T;
  4662. }
  4663. // [...] and where the reference binding (if any) binds directly.
  4664. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4665. return S.Diag(From->getLocStart(),
  4666. diag::err_typecheck_converted_constant_expression_indirect)
  4667. << From->getType() << From->getSourceRange() << T;
  4668. }
  4669. ExprResult Result =
  4670. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4671. if (Result.isInvalid())
  4672. return Result;
  4673. // Check for a narrowing implicit conversion.
  4674. APValue PreNarrowingValue;
  4675. QualType PreNarrowingType;
  4676. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4677. PreNarrowingType)) {
  4678. case NK_Variable_Narrowing:
  4679. // Implicit conversion to a narrower type, and the value is not a constant
  4680. // expression. We'll diagnose this in a moment.
  4681. case NK_Not_Narrowing:
  4682. break;
  4683. case NK_Constant_Narrowing:
  4684. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4685. << CCE << /*Constant*/1
  4686. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  4687. break;
  4688. case NK_Type_Narrowing:
  4689. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4690. << CCE << /*Constant*/0 << From->getType() << T;
  4691. break;
  4692. }
  4693. // Check the expression is a constant expression.
  4694. SmallVector<PartialDiagnosticAt, 8> Notes;
  4695. Expr::EvalResult Eval;
  4696. Eval.Diag = &Notes;
  4697. if ((T->isReferenceType()
  4698. ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
  4699. : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
  4700. (RequireInt && !Eval.Val.isInt())) {
  4701. // The expression can't be folded, so we can't keep it at this position in
  4702. // the AST.
  4703. Result = ExprError();
  4704. } else {
  4705. Value = Eval.Val;
  4706. if (Notes.empty()) {
  4707. // It's a constant expression.
  4708. return Result;
  4709. }
  4710. }
  4711. // It's not a constant expression. Produce an appropriate diagnostic.
  4712. if (Notes.size() == 1 &&
  4713. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  4714. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  4715. else {
  4716. S.Diag(From->getLocStart(), diag::err_expr_not_cce)
  4717. << CCE << From->getSourceRange();
  4718. for (unsigned I = 0; I < Notes.size(); ++I)
  4719. S.Diag(Notes[I].first, Notes[I].second);
  4720. }
  4721. return ExprError();
  4722. }
  4723. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4724. APValue &Value, CCEKind CCE) {
  4725. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  4726. }
  4727. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4728. llvm::APSInt &Value,
  4729. CCEKind CCE) {
  4730. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  4731. APValue V;
  4732. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  4733. if (!R.isInvalid())
  4734. Value = V.getInt();
  4735. return R;
  4736. }
  4737. /// dropPointerConversions - If the given standard conversion sequence
  4738. /// involves any pointer conversions, remove them. This may change
  4739. /// the result type of the conversion sequence.
  4740. static void dropPointerConversion(StandardConversionSequence &SCS) {
  4741. if (SCS.Second == ICK_Pointer_Conversion) {
  4742. SCS.Second = ICK_Identity;
  4743. SCS.Third = ICK_Identity;
  4744. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  4745. }
  4746. }
  4747. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  4748. /// convert the expression From to an Objective-C pointer type.
  4749. static ImplicitConversionSequence
  4750. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  4751. // Do an implicit conversion to 'id'.
  4752. QualType Ty = S.Context.getObjCIdType();
  4753. ImplicitConversionSequence ICS
  4754. = TryImplicitConversion(S, From, Ty,
  4755. // FIXME: Are these flags correct?
  4756. /*SuppressUserConversions=*/false,
  4757. /*AllowExplicit=*/true,
  4758. /*InOverloadResolution=*/false,
  4759. /*CStyle=*/false,
  4760. /*AllowObjCWritebackConversion=*/false,
  4761. /*AllowObjCConversionOnExplicit=*/true);
  4762. // Strip off any final conversions to 'id'.
  4763. switch (ICS.getKind()) {
  4764. case ImplicitConversionSequence::BadConversion:
  4765. case ImplicitConversionSequence::AmbiguousConversion:
  4766. case ImplicitConversionSequence::EllipsisConversion:
  4767. break;
  4768. case ImplicitConversionSequence::UserDefinedConversion:
  4769. dropPointerConversion(ICS.UserDefined.After);
  4770. break;
  4771. case ImplicitConversionSequence::StandardConversion:
  4772. dropPointerConversion(ICS.Standard);
  4773. break;
  4774. }
  4775. return ICS;
  4776. }
  4777. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  4778. /// conversion of the expression From to an Objective-C pointer type.
  4779. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  4780. if (checkPlaceholderForOverload(*this, From))
  4781. return ExprError();
  4782. QualType Ty = Context.getObjCIdType();
  4783. ImplicitConversionSequence ICS =
  4784. TryContextuallyConvertToObjCPointer(*this, From);
  4785. if (!ICS.isBad())
  4786. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  4787. return ExprError();
  4788. }
  4789. /// Determine whether the provided type is an integral type, or an enumeration
  4790. /// type of a permitted flavor.
  4791. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  4792. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  4793. : T->isIntegralOrUnscopedEnumerationType();
  4794. }
  4795. static ExprResult
  4796. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  4797. Sema::ContextualImplicitConverter &Converter,
  4798. QualType T, UnresolvedSetImpl &ViableConversions) {
  4799. if (Converter.Suppress)
  4800. return ExprError();
  4801. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  4802. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4803. CXXConversionDecl *Conv =
  4804. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  4805. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  4806. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  4807. }
  4808. return From;
  4809. }
  4810. static bool
  4811. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4812. Sema::ContextualImplicitConverter &Converter,
  4813. QualType T, bool HadMultipleCandidates,
  4814. UnresolvedSetImpl &ExplicitConversions) {
  4815. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  4816. DeclAccessPair Found = ExplicitConversions[0];
  4817. CXXConversionDecl *Conversion =
  4818. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4819. // The user probably meant to invoke the given explicit
  4820. // conversion; use it.
  4821. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  4822. std::string TypeStr;
  4823. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  4824. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  4825. << FixItHint::CreateInsertion(From->getLocStart(),
  4826. "static_cast<" + TypeStr + ">(")
  4827. << FixItHint::CreateInsertion(
  4828. SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
  4829. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  4830. // If we aren't in a SFINAE context, build a call to the
  4831. // explicit conversion function.
  4832. if (SemaRef.isSFINAEContext())
  4833. return true;
  4834. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4835. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4836. HadMultipleCandidates);
  4837. if (Result.isInvalid())
  4838. return true;
  4839. // Record usage of conversion in an implicit cast.
  4840. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4841. CK_UserDefinedConversion, Result.get(),
  4842. nullptr, Result.get()->getValueKind());
  4843. }
  4844. return false;
  4845. }
  4846. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4847. Sema::ContextualImplicitConverter &Converter,
  4848. QualType T, bool HadMultipleCandidates,
  4849. DeclAccessPair &Found) {
  4850. CXXConversionDecl *Conversion =
  4851. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4852. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4853. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  4854. if (!Converter.SuppressConversion) {
  4855. if (SemaRef.isSFINAEContext())
  4856. return true;
  4857. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  4858. << From->getSourceRange();
  4859. }
  4860. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4861. HadMultipleCandidates);
  4862. if (Result.isInvalid())
  4863. return true;
  4864. // Record usage of conversion in an implicit cast.
  4865. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4866. CK_UserDefinedConversion, Result.get(),
  4867. nullptr, Result.get()->getValueKind());
  4868. return false;
  4869. }
  4870. static ExprResult finishContextualImplicitConversion(
  4871. Sema &SemaRef, SourceLocation Loc, Expr *From,
  4872. Sema::ContextualImplicitConverter &Converter) {
  4873. if (!Converter.match(From->getType()) && !Converter.Suppress)
  4874. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  4875. << From->getSourceRange();
  4876. return SemaRef.DefaultLvalueConversion(From);
  4877. }
  4878. static void
  4879. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  4880. UnresolvedSetImpl &ViableConversions,
  4881. OverloadCandidateSet &CandidateSet) {
  4882. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4883. DeclAccessPair FoundDecl = ViableConversions[I];
  4884. NamedDecl *D = FoundDecl.getDecl();
  4885. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  4886. if (isa<UsingShadowDecl>(D))
  4887. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4888. CXXConversionDecl *Conv;
  4889. FunctionTemplateDecl *ConvTemplate;
  4890. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  4891. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4892. else
  4893. Conv = cast<CXXConversionDecl>(D);
  4894. if (ConvTemplate)
  4895. SemaRef.AddTemplateConversionCandidate(
  4896. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  4897. /*AllowObjCConversionOnExplicit=*/false);
  4898. else
  4899. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  4900. ToType, CandidateSet,
  4901. /*AllowObjCConversionOnExplicit=*/false);
  4902. }
  4903. }
  4904. /// \brief Attempt to convert the given expression to a type which is accepted
  4905. /// by the given converter.
  4906. ///
  4907. /// This routine will attempt to convert an expression of class type to a
  4908. /// type accepted by the specified converter. In C++11 and before, the class
  4909. /// must have a single non-explicit conversion function converting to a matching
  4910. /// type. In C++1y, there can be multiple such conversion functions, but only
  4911. /// one target type.
  4912. ///
  4913. /// \param Loc The source location of the construct that requires the
  4914. /// conversion.
  4915. ///
  4916. /// \param From The expression we're converting from.
  4917. ///
  4918. /// \param Converter Used to control and diagnose the conversion process.
  4919. ///
  4920. /// \returns The expression, converted to an integral or enumeration type if
  4921. /// successful.
  4922. ExprResult Sema::PerformContextualImplicitConversion(
  4923. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  4924. // We can't perform any more checking for type-dependent expressions.
  4925. if (From->isTypeDependent())
  4926. return From;
  4927. // Process placeholders immediately.
  4928. if (From->hasPlaceholderType()) {
  4929. ExprResult result = CheckPlaceholderExpr(From);
  4930. if (result.isInvalid())
  4931. return result;
  4932. From = result.get();
  4933. }
  4934. // If the expression already has a matching type, we're golden.
  4935. QualType T = From->getType();
  4936. if (Converter.match(T))
  4937. return DefaultLvalueConversion(From);
  4938. // FIXME: Check for missing '()' if T is a function type?
  4939. // We can only perform contextual implicit conversions on objects of class
  4940. // type.
  4941. const RecordType *RecordTy = T->getAs<RecordType>();
  4942. if (!RecordTy || !getLangOpts().CPlusPlus) {
  4943. if (!Converter.Suppress)
  4944. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  4945. return From;
  4946. }
  4947. // We must have a complete class type.
  4948. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  4949. ContextualImplicitConverter &Converter;
  4950. Expr *From;
  4951. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  4952. : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
  4953. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  4954. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  4955. }
  4956. } IncompleteDiagnoser(Converter, From);
  4957. if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
  4958. return From;
  4959. // Look for a conversion to an integral or enumeration type.
  4960. UnresolvedSet<4>
  4961. ViableConversions; // These are *potentially* viable in C++1y.
  4962. UnresolvedSet<4> ExplicitConversions;
  4963. const auto &Conversions =
  4964. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  4965. bool HadMultipleCandidates =
  4966. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  4967. // To check that there is only one target type, in C++1y:
  4968. QualType ToType;
  4969. bool HasUniqueTargetType = true;
  4970. // Collect explicit or viable (potentially in C++1y) conversions.
  4971. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4972. NamedDecl *D = (*I)->getUnderlyingDecl();
  4973. CXXConversionDecl *Conversion;
  4974. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4975. if (ConvTemplate) {
  4976. if (getLangOpts().CPlusPlus14)
  4977. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4978. else
  4979. continue; // C++11 does not consider conversion operator templates(?).
  4980. } else
  4981. Conversion = cast<CXXConversionDecl>(D);
  4982. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  4983. "Conversion operator templates are considered potentially "
  4984. "viable in C++1y");
  4985. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  4986. if (Converter.match(CurToType) || ConvTemplate) {
  4987. if (Conversion->isExplicit()) {
  4988. // FIXME: For C++1y, do we need this restriction?
  4989. // cf. diagnoseNoViableConversion()
  4990. if (!ConvTemplate)
  4991. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  4992. } else {
  4993. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  4994. if (ToType.isNull())
  4995. ToType = CurToType.getUnqualifiedType();
  4996. else if (HasUniqueTargetType &&
  4997. (CurToType.getUnqualifiedType() != ToType))
  4998. HasUniqueTargetType = false;
  4999. }
  5000. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5001. }
  5002. }
  5003. }
  5004. if (getLangOpts().CPlusPlus14) {
  5005. // C++1y [conv]p6:
  5006. // ... An expression e of class type E appearing in such a context
  5007. // is said to be contextually implicitly converted to a specified
  5008. // type T and is well-formed if and only if e can be implicitly
  5009. // converted to a type T that is determined as follows: E is searched
  5010. // for conversion functions whose return type is cv T or reference to
  5011. // cv T such that T is allowed by the context. There shall be
  5012. // exactly one such T.
  5013. // If no unique T is found:
  5014. if (ToType.isNull()) {
  5015. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5016. HadMultipleCandidates,
  5017. ExplicitConversions))
  5018. return ExprError();
  5019. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5020. }
  5021. // If more than one unique Ts are found:
  5022. if (!HasUniqueTargetType)
  5023. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5024. ViableConversions);
  5025. // If one unique T is found:
  5026. // First, build a candidate set from the previously recorded
  5027. // potentially viable conversions.
  5028. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5029. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5030. CandidateSet);
  5031. // Then, perform overload resolution over the candidate set.
  5032. OverloadCandidateSet::iterator Best;
  5033. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5034. case OR_Success: {
  5035. // Apply this conversion.
  5036. DeclAccessPair Found =
  5037. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5038. if (recordConversion(*this, Loc, From, Converter, T,
  5039. HadMultipleCandidates, Found))
  5040. return ExprError();
  5041. break;
  5042. }
  5043. case OR_Ambiguous:
  5044. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5045. ViableConversions);
  5046. case OR_No_Viable_Function:
  5047. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5048. HadMultipleCandidates,
  5049. ExplicitConversions))
  5050. return ExprError();
  5051. // fall through 'OR_Deleted' case.
  5052. case OR_Deleted:
  5053. // We'll complain below about a non-integral condition type.
  5054. break;
  5055. }
  5056. } else {
  5057. switch (ViableConversions.size()) {
  5058. case 0: {
  5059. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5060. HadMultipleCandidates,
  5061. ExplicitConversions))
  5062. return ExprError();
  5063. // We'll complain below about a non-integral condition type.
  5064. break;
  5065. }
  5066. case 1: {
  5067. // Apply this conversion.
  5068. DeclAccessPair Found = ViableConversions[0];
  5069. if (recordConversion(*this, Loc, From, Converter, T,
  5070. HadMultipleCandidates, Found))
  5071. return ExprError();
  5072. break;
  5073. }
  5074. default:
  5075. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5076. ViableConversions);
  5077. }
  5078. }
  5079. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5080. }
  5081. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5082. /// an acceptable non-member overloaded operator for a call whose
  5083. /// arguments have types T1 (and, if non-empty, T2). This routine
  5084. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5085. /// enumeration types.
  5086. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5087. FunctionDecl *Fn,
  5088. ArrayRef<Expr *> Args) {
  5089. QualType T1 = Args[0]->getType();
  5090. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5091. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5092. return true;
  5093. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5094. return true;
  5095. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5096. if (Proto->getNumParams() < 1)
  5097. return false;
  5098. if (T1->isEnumeralType()) {
  5099. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5100. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5101. return true;
  5102. }
  5103. if (Proto->getNumParams() < 2)
  5104. return false;
  5105. if (!T2.isNull() && T2->isEnumeralType()) {
  5106. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5107. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5108. return true;
  5109. }
  5110. return false;
  5111. }
  5112. /// AddOverloadCandidate - Adds the given function to the set of
  5113. /// candidate functions, using the given function call arguments. If
  5114. /// @p SuppressUserConversions, then don't allow user-defined
  5115. /// conversions via constructors or conversion operators.
  5116. ///
  5117. /// \param PartialOverloading true if we are performing "partial" overloading
  5118. /// based on an incomplete set of function arguments. This feature is used by
  5119. /// code completion.
  5120. void
  5121. Sema::AddOverloadCandidate(FunctionDecl *Function,
  5122. DeclAccessPair FoundDecl,
  5123. ArrayRef<Expr *> Args,
  5124. OverloadCandidateSet &CandidateSet,
  5125. bool SuppressUserConversions,
  5126. bool PartialOverloading,
  5127. bool AllowExplicit) {
  5128. const FunctionProtoType *Proto
  5129. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5130. assert(Proto && "Functions without a prototype cannot be overloaded");
  5131. assert(!Function->getDescribedFunctionTemplate() &&
  5132. "Use AddTemplateOverloadCandidate for function templates");
  5133. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5134. if (!isa<CXXConstructorDecl>(Method)) {
  5135. // If we get here, it's because we're calling a member function
  5136. // that is named without a member access expression (e.g.,
  5137. // "this->f") that was either written explicitly or created
  5138. // implicitly. This can happen with a qualified call to a member
  5139. // function, e.g., X::f(). We use an empty type for the implied
  5140. // object argument (C++ [over.call.func]p3), and the acting context
  5141. // is irrelevant.
  5142. AddMethodCandidate(Method, FoundDecl, Method->getParent(),
  5143. QualType(), Expr::Classification::makeSimpleLValue(),
  5144. Args, CandidateSet, SuppressUserConversions,
  5145. PartialOverloading);
  5146. return;
  5147. }
  5148. // We treat a constructor like a non-member function, since its object
  5149. // argument doesn't participate in overload resolution.
  5150. }
  5151. if (!CandidateSet.isNewCandidate(Function))
  5152. return;
  5153. // C++ [over.match.oper]p3:
  5154. // if no operand has a class type, only those non-member functions in the
  5155. // lookup set that have a first parameter of type T1 or "reference to
  5156. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5157. // is a right operand) a second parameter of type T2 or "reference to
  5158. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5159. // candidate functions.
  5160. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5161. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5162. return;
  5163. // C++11 [class.copy]p11: [DR1402]
  5164. // A defaulted move constructor that is defined as deleted is ignored by
  5165. // overload resolution.
  5166. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5167. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5168. Constructor->isMoveConstructor())
  5169. return;
  5170. // Overload resolution is always an unevaluated context.
  5171. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5172. // Add this candidate
  5173. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  5174. Candidate.FoundDecl = FoundDecl;
  5175. Candidate.Function = Function;
  5176. Candidate.Viable = true;
  5177. Candidate.IsSurrogate = false;
  5178. Candidate.IgnoreObjectArgument = false;
  5179. Candidate.ExplicitCallArguments = Args.size();
  5180. if (Constructor) {
  5181. // C++ [class.copy]p3:
  5182. // A member function template is never instantiated to perform the copy
  5183. // of a class object to an object of its class type.
  5184. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5185. if (Args.size() == 1 &&
  5186. Constructor->isSpecializationCopyingObject() &&
  5187. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5188. IsDerivedFrom(Args[0]->getType(), ClassType))) {
  5189. Candidate.Viable = false;
  5190. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5191. return;
  5192. }
  5193. }
  5194. unsigned NumParams = Proto->getNumParams();
  5195. // (C++ 13.3.2p2): A candidate function having fewer than m
  5196. // parameters is viable only if it has an ellipsis in its parameter
  5197. // list (8.3.5).
  5198. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5199. !Proto->isVariadic()) {
  5200. Candidate.Viable = false;
  5201. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5202. return;
  5203. }
  5204. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5205. // is viable only if the (m+1)st parameter has a default argument
  5206. // (8.3.6). For the purposes of overload resolution, the
  5207. // parameter list is truncated on the right, so that there are
  5208. // exactly m parameters.
  5209. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5210. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5211. // Not enough arguments.
  5212. Candidate.Viable = false;
  5213. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5214. return;
  5215. }
  5216. // (CUDA B.1): Check for invalid calls between targets.
  5217. if (getLangOpts().CUDA)
  5218. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5219. // Skip the check for callers that are implicit members, because in this
  5220. // case we may not yet know what the member's target is; the target is
  5221. // inferred for the member automatically, based on the bases and fields of
  5222. // the class.
  5223. if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
  5224. Candidate.Viable = false;
  5225. Candidate.FailureKind = ovl_fail_bad_target;
  5226. return;
  5227. }
  5228. // Determine the implicit conversion sequences for each of the
  5229. // arguments.
  5230. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5231. if (ArgIdx < NumParams) {
  5232. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5233. // exist for each argument an implicit conversion sequence
  5234. // (13.3.3.1) that converts that argument to the corresponding
  5235. // parameter of F.
  5236. // HLSL Change Starts
  5237. if (getLangOpts().HLSL) {
  5238. InitCallParamConversions(
  5239. *this, Proto, Function->getParamDecl(ArgIdx), ArgIdx, Args[ArgIdx],
  5240. SuppressUserConversions, true, AllowExplicit,
  5241. Candidate.Conversions[ArgIdx], Candidate.OutConversions[ArgIdx]);
  5242. } else {
  5243. QualType ParamType = Proto->getParamType(ArgIdx);
  5244. Candidate.Conversions[ArgIdx]
  5245. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5246. SuppressUserConversions,
  5247. /*InOverloadResolution=*/true,
  5248. /*AllowObjCWritebackConversion=*/
  5249. getLangOpts().ObjCAutoRefCount,
  5250. AllowExplicit);
  5251. }
  5252. // HLSL Change Ends
  5253. if (Candidate.Conversions[ArgIdx].isInitialized() && Candidate.Conversions[ArgIdx].isBad()
  5254. || Candidate.OutConversions[ArgIdx].isInitialized() && Candidate.OutConversions[ArgIdx].isBad()) { // HLSL Change - add out conversion, check initialized
  5255. Candidate.Viable = false;
  5256. Candidate.FailureKind = ovl_fail_bad_conversion;
  5257. return;
  5258. }
  5259. } else {
  5260. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5261. // argument for which there is no corresponding parameter is
  5262. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5263. Candidate.Conversions[ArgIdx].setEllipsis();
  5264. }
  5265. }
  5266. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5267. Candidate.Viable = false;
  5268. Candidate.FailureKind = ovl_fail_enable_if;
  5269. Candidate.DeductionFailure.Data = FailedAttr;
  5270. return;
  5271. }
  5272. }
  5273. ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
  5274. bool IsInstance) {
  5275. SmallVector<ObjCMethodDecl*, 4> Methods;
  5276. if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
  5277. return nullptr;
  5278. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5279. bool Match = true;
  5280. ObjCMethodDecl *Method = Methods[b];
  5281. unsigned NumNamedArgs = Sel.getNumArgs();
  5282. // Method might have more arguments than selector indicates. This is due
  5283. // to addition of c-style arguments in method.
  5284. if (Method->param_size() > NumNamedArgs)
  5285. NumNamedArgs = Method->param_size();
  5286. if (Args.size() < NumNamedArgs)
  5287. continue;
  5288. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5289. // We can't do any type-checking on a type-dependent argument.
  5290. if (Args[i]->isTypeDependent()) {
  5291. Match = false;
  5292. break;
  5293. }
  5294. ParmVarDecl *param = Method->parameters()[i];
  5295. Expr *argExpr = Args[i];
  5296. assert(argExpr && "SelectBestMethod(): missing expression");
  5297. // Strip the unbridged-cast placeholder expression off unless it's
  5298. // a consumed argument.
  5299. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5300. !param->hasAttr<CFConsumedAttr>())
  5301. argExpr = stripARCUnbridgedCast(argExpr);
  5302. // If the parameter is __unknown_anytype, move on to the next method.
  5303. if (param->getType() == Context.UnknownAnyTy) {
  5304. Match = false;
  5305. break;
  5306. }
  5307. ImplicitConversionSequence ConversionState
  5308. = TryCopyInitialization(*this, argExpr, param->getType(),
  5309. /*SuppressUserConversions*/false,
  5310. /*InOverloadResolution=*/true,
  5311. /*AllowObjCWritebackConversion=*/
  5312. getLangOpts().ObjCAutoRefCount,
  5313. /*AllowExplicit*/false);
  5314. if (ConversionState.isBad()) {
  5315. Match = false;
  5316. break;
  5317. }
  5318. }
  5319. // Promote additional arguments to variadic methods.
  5320. if (Match && Method->isVariadic()) {
  5321. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5322. if (Args[i]->isTypeDependent()) {
  5323. Match = false;
  5324. break;
  5325. }
  5326. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5327. nullptr);
  5328. if (Arg.isInvalid()) {
  5329. Match = false;
  5330. break;
  5331. }
  5332. }
  5333. } else {
  5334. // Check for extra arguments to non-variadic methods.
  5335. if (Args.size() != NumNamedArgs)
  5336. Match = false;
  5337. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5338. // Special case when selectors have no argument. In this case, select
  5339. // one with the most general result type of 'id'.
  5340. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5341. QualType ReturnT = Methods[b]->getReturnType();
  5342. if (ReturnT->isObjCIdType())
  5343. return Methods[b];
  5344. }
  5345. }
  5346. }
  5347. if (Match)
  5348. return Method;
  5349. }
  5350. return nullptr;
  5351. }
  5352. static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
  5353. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5354. bool MissingImplicitThis) {
  5355. // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
  5356. // we need to find the first failing one.
  5357. if (!Function->hasAttrs())
  5358. return nullptr;
  5359. AttrVec Attrs = Function->getAttrs();
  5360. AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
  5361. IsNotEnableIfAttr);
  5362. if (Attrs.begin() == E)
  5363. return nullptr;
  5364. std::reverse(Attrs.begin(), E);
  5365. SFINAETrap Trap(*this);
  5366. // Convert the arguments.
  5367. SmallVector<Expr *, 16> ConvertedArgs;
  5368. bool InitializationFailed = false;
  5369. bool ContainsValueDependentExpr = false;
  5370. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5371. if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
  5372. !cast<CXXMethodDecl>(Function)->isStatic() &&
  5373. !isa<CXXConstructorDecl>(Function)) {
  5374. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5375. ExprResult R =
  5376. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  5377. Method, Method);
  5378. if (R.isInvalid()) {
  5379. InitializationFailed = true;
  5380. break;
  5381. }
  5382. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5383. ConvertedArgs.push_back(R.get());
  5384. } else {
  5385. ExprResult R =
  5386. PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5387. Context,
  5388. Function->getParamDecl(i)),
  5389. SourceLocation(),
  5390. Args[i]);
  5391. if (R.isInvalid()) {
  5392. InitializationFailed = true;
  5393. break;
  5394. }
  5395. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5396. ConvertedArgs.push_back(R.get());
  5397. }
  5398. }
  5399. if (InitializationFailed || Trap.hasErrorOccurred())
  5400. return cast<EnableIfAttr>(Attrs[0]);
  5401. for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
  5402. APValue Result;
  5403. EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
  5404. if (EIA->getCond()->isValueDependent()) {
  5405. // Don't even try now, we'll examine it after instantiation.
  5406. continue;
  5407. }
  5408. if (!EIA->getCond()->EvaluateWithSubstitution(
  5409. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
  5410. if (!ContainsValueDependentExpr)
  5411. return EIA;
  5412. } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
  5413. return EIA;
  5414. }
  5415. }
  5416. return nullptr;
  5417. }
  5418. /// \brief Add all of the function declarations in the given function set to
  5419. /// the overload candidate set.
  5420. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5421. ArrayRef<Expr *> Args,
  5422. OverloadCandidateSet& CandidateSet,
  5423. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5424. bool SuppressUserConversions,
  5425. bool PartialOverloading) {
  5426. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5427. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5428. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  5429. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  5430. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5431. cast<CXXMethodDecl>(FD)->getParent(),
  5432. Args[0]->getType(), Args[0]->Classify(Context),
  5433. Args.slice(1), CandidateSet,
  5434. SuppressUserConversions, PartialOverloading);
  5435. else
  5436. AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
  5437. SuppressUserConversions, PartialOverloading);
  5438. } else {
  5439. FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
  5440. if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
  5441. !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
  5442. AddMethodTemplateCandidate(FunTmpl, F.getPair(),
  5443. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5444. ExplicitTemplateArgs,
  5445. Args[0]->getType(),
  5446. Args[0]->Classify(Context), Args.slice(1),
  5447. CandidateSet, SuppressUserConversions,
  5448. PartialOverloading);
  5449. else
  5450. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  5451. ExplicitTemplateArgs, Args,
  5452. CandidateSet, SuppressUserConversions,
  5453. PartialOverloading);
  5454. }
  5455. }
  5456. }
  5457. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5458. /// method) as a method candidate to the given overload set.
  5459. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
  5460. QualType ObjectType,
  5461. Expr::Classification ObjectClassification,
  5462. ArrayRef<Expr *> Args,
  5463. OverloadCandidateSet& CandidateSet,
  5464. bool SuppressUserConversions) {
  5465. NamedDecl *Decl = FoundDecl.getDecl();
  5466. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5467. if (isa<UsingShadowDecl>(Decl))
  5468. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5469. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5470. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5471. "Expected a member function template");
  5472. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5473. /*ExplicitArgs*/ nullptr,
  5474. ObjectType, ObjectClassification,
  5475. Args, CandidateSet,
  5476. SuppressUserConversions);
  5477. } else {
  5478. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5479. ObjectType, ObjectClassification,
  5480. Args,
  5481. CandidateSet, SuppressUserConversions);
  5482. }
  5483. }
  5484. /// AddMethodCandidate - Adds the given C++ member function to the set
  5485. /// of candidate functions, using the given function call arguments
  5486. /// and the object argument (@c Object). For example, in a call
  5487. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5488. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5489. /// allow user-defined conversions via constructors or conversion
  5490. /// operators.
  5491. void
  5492. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5493. CXXRecordDecl *ActingContext, QualType ObjectType,
  5494. Expr::Classification ObjectClassification,
  5495. ArrayRef<Expr *> Args,
  5496. OverloadCandidateSet &CandidateSet,
  5497. bool SuppressUserConversions,
  5498. bool PartialOverloading) {
  5499. const FunctionProtoType *Proto
  5500. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5501. assert(Proto && "Methods without a prototype cannot be overloaded");
  5502. assert(!isa<CXXConstructorDecl>(Method) &&
  5503. "Use AddOverloadCandidate for constructors");
  5504. if (!CandidateSet.isNewCandidate(Method))
  5505. return;
  5506. // C++11 [class.copy]p23: [DR1402]
  5507. // A defaulted move assignment operator that is defined as deleted is
  5508. // ignored by overload resolution.
  5509. if (Method->isDefaulted() && Method->isDeleted() &&
  5510. Method->isMoveAssignmentOperator())
  5511. return;
  5512. // Overload resolution is always an unevaluated context.
  5513. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5514. // Add this candidate
  5515. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5516. Candidate.FoundDecl = FoundDecl;
  5517. Candidate.Function = Method;
  5518. Candidate.IsSurrogate = false;
  5519. Candidate.IgnoreObjectArgument = false;
  5520. Candidate.ExplicitCallArguments = Args.size();
  5521. unsigned NumParams = Proto->getNumParams();
  5522. // (C++ 13.3.2p2): A candidate function having fewer than m
  5523. // parameters is viable only if it has an ellipsis in its parameter
  5524. // list (8.3.5).
  5525. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5526. !Proto->isVariadic()) {
  5527. Candidate.Viable = false;
  5528. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5529. return;
  5530. }
  5531. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5532. // is viable only if the (m+1)st parameter has a default argument
  5533. // (8.3.6). For the purposes of overload resolution, the
  5534. // parameter list is truncated on the right, so that there are
  5535. // exactly m parameters.
  5536. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  5537. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5538. // Not enough arguments.
  5539. Candidate.Viable = false;
  5540. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5541. return;
  5542. }
  5543. Candidate.Viable = true;
  5544. if (Method->isStatic() || ObjectType.isNull())
  5545. // The implicit object argument is ignored.
  5546. Candidate.IgnoreObjectArgument = true;
  5547. else {
  5548. // Determine the implicit conversion sequence for the object
  5549. // parameter.
  5550. Candidate.Conversions[0]
  5551. = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
  5552. Method, ActingContext);
  5553. if (Candidate.Conversions[0].isBad()) {
  5554. Candidate.Viable = false;
  5555. Candidate.FailureKind = ovl_fail_bad_conversion;
  5556. return;
  5557. }
  5558. }
  5559. // (CUDA B.1): Check for invalid calls between targets.
  5560. if (getLangOpts().CUDA)
  5561. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5562. if (CheckCUDATarget(Caller, Method)) {
  5563. Candidate.Viable = false;
  5564. Candidate.FailureKind = ovl_fail_bad_target;
  5565. return;
  5566. }
  5567. // Determine the implicit conversion sequences for each of the
  5568. // arguments.
  5569. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5570. if (ArgIdx < NumParams) {
  5571. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5572. // exist for each argument an implicit conversion sequence
  5573. // (13.3.3.1) that converts that argument to the corresponding
  5574. // parameter of F.
  5575. QualType ParamType = Proto->getParamType(ArgIdx);
  5576. // HLSL Change Starts
  5577. if (getLangOpts().HLSL && Method->getDeclName() == Context.DeclarationNames.getCXXOperatorName(OO_Subscript)) {
  5578. Candidate.Conversions[ArgIdx + 1] = hlsl::TrySubscriptIndexInitialization(
  5579. this, Args[ArgIdx], ParamType);
  5580. goto EvaluateCandidate;
  5581. }
  5582. // HLSL Change Ends
  5583. Candidate.Conversions[ArgIdx + 1]
  5584. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5585. SuppressUserConversions,
  5586. /*InOverloadResolution=*/true,
  5587. /*AllowObjCWritebackConversion=*/
  5588. getLangOpts().ObjCAutoRefCount);
  5589. EvaluateCandidate:// HLSL Change - present alterantive to TryCopyInitialization
  5590. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  5591. Candidate.Viable = false;
  5592. Candidate.FailureKind = ovl_fail_bad_conversion;
  5593. return;
  5594. }
  5595. } else {
  5596. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5597. // argument for which there is no corresponding parameter is
  5598. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  5599. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  5600. }
  5601. }
  5602. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  5603. Candidate.Viable = false;
  5604. Candidate.FailureKind = ovl_fail_enable_if;
  5605. Candidate.DeductionFailure.Data = FailedAttr;
  5606. return;
  5607. }
  5608. }
  5609. /// \brief Add a C++ member function template as a candidate to the candidate
  5610. /// set, using template argument deduction to produce an appropriate member
  5611. /// function template specialization.
  5612. void
  5613. Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
  5614. DeclAccessPair FoundDecl,
  5615. CXXRecordDecl *ActingContext,
  5616. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5617. QualType ObjectType,
  5618. Expr::Classification ObjectClassification,
  5619. ArrayRef<Expr *> Args,
  5620. OverloadCandidateSet& CandidateSet,
  5621. bool SuppressUserConversions,
  5622. bool PartialOverloading) {
  5623. if (!CandidateSet.isNewCandidate(MethodTmpl))
  5624. return;
  5625. // C++ [over.match.funcs]p7:
  5626. // In each case where a candidate is a function template, candidate
  5627. // function template specializations are generated using template argument
  5628. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5629. // candidate functions in the usual way.113) A given name can refer to one
  5630. // or more function templates and also to a set of overloaded non-template
  5631. // functions. In such a case, the candidate functions generated from each
  5632. // function template are combined with the set of non-template candidate
  5633. // functions.
  5634. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5635. FunctionDecl *Specialization = nullptr;
  5636. if (TemplateDeductionResult Result
  5637. = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
  5638. Specialization, Info, PartialOverloading)) {
  5639. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5640. Candidate.FoundDecl = FoundDecl;
  5641. Candidate.Function = MethodTmpl->getTemplatedDecl();
  5642. Candidate.Viable = false;
  5643. Candidate.FailureKind = ovl_fail_bad_deduction;
  5644. Candidate.IsSurrogate = false;
  5645. Candidate.IgnoreObjectArgument = false;
  5646. Candidate.ExplicitCallArguments = Args.size();
  5647. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5648. Info);
  5649. return;
  5650. }
  5651. // Add the function template specialization produced by template argument
  5652. // deduction as a candidate.
  5653. assert(Specialization && "Missing member function template specialization?");
  5654. assert(isa<CXXMethodDecl>(Specialization) &&
  5655. "Specialization is not a member function?");
  5656. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  5657. ActingContext, ObjectType, ObjectClassification, Args,
  5658. CandidateSet, SuppressUserConversions, PartialOverloading);
  5659. }
  5660. /// \brief Add a C++ function template specialization as a candidate
  5661. /// in the candidate set, using template argument deduction to produce
  5662. /// an appropriate function template specialization.
  5663. void
  5664. Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
  5665. DeclAccessPair FoundDecl,
  5666. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5667. ArrayRef<Expr *> Args,
  5668. OverloadCandidateSet& CandidateSet,
  5669. bool SuppressUserConversions,
  5670. bool PartialOverloading) {
  5671. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5672. return;
  5673. // C++ [over.match.funcs]p7:
  5674. // In each case where a candidate is a function template, candidate
  5675. // function template specializations are generated using template argument
  5676. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5677. // candidate functions in the usual way.113) A given name can refer to one
  5678. // or more function templates and also to a set of overloaded non-template
  5679. // functions. In such a case, the candidate functions generated from each
  5680. // function template are combined with the set of non-template candidate
  5681. // functions.
  5682. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5683. FunctionDecl *Specialization = nullptr;
  5684. if (TemplateDeductionResult Result
  5685. = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
  5686. Specialization, Info, PartialOverloading)) {
  5687. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5688. Candidate.FoundDecl = FoundDecl;
  5689. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5690. Candidate.Viable = false;
  5691. Candidate.FailureKind = ovl_fail_bad_deduction;
  5692. Candidate.IsSurrogate = false;
  5693. Candidate.IgnoreObjectArgument = false;
  5694. Candidate.ExplicitCallArguments = Args.size();
  5695. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5696. Info);
  5697. return;
  5698. }
  5699. // Add the function template specialization produced by template argument
  5700. // deduction as a candidate.
  5701. assert(Specialization && "Missing function template specialization?");
  5702. AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
  5703. SuppressUserConversions, PartialOverloading);
  5704. }
  5705. /// Determine whether this is an allowable conversion from the result
  5706. /// of an explicit conversion operator to the expected type, per C++
  5707. /// [over.match.conv]p1 and [over.match.ref]p1.
  5708. ///
  5709. /// \param ConvType The return type of the conversion function.
  5710. ///
  5711. /// \param ToType The type we are converting to.
  5712. ///
  5713. /// \param AllowObjCPointerConversion Allow a conversion from one
  5714. /// Objective-C pointer to another.
  5715. ///
  5716. /// \returns true if the conversion is allowable, false otherwise.
  5717. static bool isAllowableExplicitConversion(Sema &S,
  5718. QualType ConvType, QualType ToType,
  5719. bool AllowObjCPointerConversion) {
  5720. QualType ToNonRefType = ToType.getNonReferenceType();
  5721. // Easy case: the types are the same.
  5722. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  5723. return true;
  5724. // Allow qualification conversions.
  5725. bool ObjCLifetimeConversion;
  5726. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  5727. ObjCLifetimeConversion))
  5728. return true;
  5729. // If we're not allowed to consider Objective-C pointer conversions,
  5730. // we're done.
  5731. if (!AllowObjCPointerConversion)
  5732. return false;
  5733. // Is this an Objective-C pointer conversion?
  5734. bool IncompatibleObjC = false;
  5735. QualType ConvertedType;
  5736. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  5737. IncompatibleObjC);
  5738. }
  5739. /// AddConversionCandidate - Add a C++ conversion function as a
  5740. /// candidate in the candidate set (C++ [over.match.conv],
  5741. /// C++ [over.match.copy]). From is the expression we're converting from,
  5742. /// and ToType is the type that we're eventually trying to convert to
  5743. /// (which may or may not be the same type as the type that the
  5744. /// conversion function produces).
  5745. void
  5746. Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
  5747. DeclAccessPair FoundDecl,
  5748. CXXRecordDecl *ActingContext,
  5749. Expr *From, QualType ToType,
  5750. OverloadCandidateSet& CandidateSet,
  5751. bool AllowObjCConversionOnExplicit) {
  5752. assert(!Conversion->getDescribedFunctionTemplate() &&
  5753. "Conversion function templates use AddTemplateConversionCandidate");
  5754. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  5755. if (!CandidateSet.isNewCandidate(Conversion))
  5756. return;
  5757. // If the conversion function has an undeduced return type, trigger its
  5758. // deduction now.
  5759. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  5760. if (DeduceReturnType(Conversion, From->getExprLoc()))
  5761. return;
  5762. ConvType = Conversion->getConversionType().getNonReferenceType();
  5763. }
  5764. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  5765. // operator is only a candidate if its return type is the target type or
  5766. // can be converted to the target type with a qualification conversion.
  5767. if (Conversion->isExplicit() &&
  5768. !isAllowableExplicitConversion(*this, ConvType, ToType,
  5769. AllowObjCConversionOnExplicit))
  5770. return;
  5771. // Overload resolution is always an unevaluated context.
  5772. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5773. // Add this candidate
  5774. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  5775. Candidate.FoundDecl = FoundDecl;
  5776. Candidate.Function = Conversion;
  5777. Candidate.IsSurrogate = false;
  5778. Candidate.IgnoreObjectArgument = false;
  5779. Candidate.FinalConversion.setAsIdentityConversion();
  5780. Candidate.FinalConversion.setFromType(ConvType);
  5781. Candidate.FinalConversion.setAllToTypes(ToType);
  5782. Candidate.Viable = true;
  5783. Candidate.ExplicitCallArguments = 1;
  5784. // C++ [over.match.funcs]p4:
  5785. // For conversion functions, the function is considered to be a member of
  5786. // the class of the implicit implied object argument for the purpose of
  5787. // defining the type of the implicit object parameter.
  5788. //
  5789. // Determine the implicit conversion sequence for the implicit
  5790. // object parameter.
  5791. QualType ImplicitParamType = From->getType();
  5792. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  5793. ImplicitParamType = FromPtrType->getPointeeType();
  5794. CXXRecordDecl *ConversionContext
  5795. = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
  5796. Candidate.Conversions[0]
  5797. = TryObjectArgumentInitialization(*this, From->getType(),
  5798. From->Classify(Context),
  5799. Conversion, ConversionContext);
  5800. if (Candidate.Conversions[0].isBad()) {
  5801. Candidate.Viable = false;
  5802. Candidate.FailureKind = ovl_fail_bad_conversion;
  5803. return;
  5804. }
  5805. // We won't go through a user-defined type conversion function to convert a
  5806. // derived to base as such conversions are given Conversion Rank. They only
  5807. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  5808. QualType FromCanon
  5809. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  5810. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  5811. if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
  5812. Candidate.Viable = false;
  5813. Candidate.FailureKind = ovl_fail_trivial_conversion;
  5814. return;
  5815. }
  5816. // To determine what the conversion from the result of calling the
  5817. // conversion function to the type we're eventually trying to
  5818. // convert to (ToType), we need to synthesize a call to the
  5819. // conversion function and attempt copy initialization from it. This
  5820. // makes sure that we get the right semantics with respect to
  5821. // lvalues/rvalues and the type. Fortunately, we can allocate this
  5822. // call on the stack and we don't need its arguments to be
  5823. // well-formed.
  5824. DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
  5825. VK_LValue, From->getLocStart());
  5826. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  5827. Context.getPointerType(Conversion->getType()),
  5828. CK_FunctionToPointerDecay,
  5829. &ConversionRef, VK_RValue);
  5830. QualType ConversionType = Conversion->getConversionType();
  5831. if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
  5832. Candidate.Viable = false;
  5833. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5834. return;
  5835. }
  5836. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  5837. // Note that it is safe to allocate CallExpr on the stack here because
  5838. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  5839. // allocator).
  5840. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  5841. CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
  5842. From->getLocStart());
  5843. ImplicitConversionSequence ICS =
  5844. TryCopyInitialization(*this, &Call, ToType,
  5845. /*SuppressUserConversions=*/true,
  5846. /*InOverloadResolution=*/false,
  5847. /*AllowObjCWritebackConversion=*/false);
  5848. switch (ICS.getKind()) {
  5849. case ImplicitConversionSequence::StandardConversion:
  5850. Candidate.FinalConversion = ICS.Standard;
  5851. // C++ [over.ics.user]p3:
  5852. // If the user-defined conversion is specified by a specialization of a
  5853. // conversion function template, the second standard conversion sequence
  5854. // shall have exact match rank.
  5855. if (Conversion->getPrimaryTemplate() &&
  5856. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  5857. Candidate.Viable = false;
  5858. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  5859. return;
  5860. }
  5861. // C++0x [dcl.init.ref]p5:
  5862. // In the second case, if the reference is an rvalue reference and
  5863. // the second standard conversion sequence of the user-defined
  5864. // conversion sequence includes an lvalue-to-rvalue conversion, the
  5865. // program is ill-formed.
  5866. if (ToType->isRValueReferenceType() &&
  5867. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5868. Candidate.Viable = false;
  5869. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5870. return;
  5871. }
  5872. break;
  5873. case ImplicitConversionSequence::BadConversion:
  5874. Candidate.Viable = false;
  5875. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5876. return;
  5877. default:
  5878. llvm_unreachable(
  5879. "Can only end up with a standard conversion sequence or failure");
  5880. }
  5881. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  5882. Candidate.Viable = false;
  5883. Candidate.FailureKind = ovl_fail_enable_if;
  5884. Candidate.DeductionFailure.Data = FailedAttr;
  5885. return;
  5886. }
  5887. }
  5888. /// \brief Adds a conversion function template specialization
  5889. /// candidate to the overload set, using template argument deduction
  5890. /// to deduce the template arguments of the conversion function
  5891. /// template from the type that we are converting to (C++
  5892. /// [temp.deduct.conv]).
  5893. void
  5894. Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
  5895. DeclAccessPair FoundDecl,
  5896. CXXRecordDecl *ActingDC,
  5897. Expr *From, QualType ToType,
  5898. OverloadCandidateSet &CandidateSet,
  5899. bool AllowObjCConversionOnExplicit) {
  5900. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  5901. "Only conversion function templates permitted here");
  5902. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5903. return;
  5904. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5905. CXXConversionDecl *Specialization = nullptr;
  5906. if (TemplateDeductionResult Result
  5907. = DeduceTemplateArguments(FunctionTemplate, ToType,
  5908. Specialization, Info)) {
  5909. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5910. Candidate.FoundDecl = FoundDecl;
  5911. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5912. Candidate.Viable = false;
  5913. Candidate.FailureKind = ovl_fail_bad_deduction;
  5914. Candidate.IsSurrogate = false;
  5915. Candidate.IgnoreObjectArgument = false;
  5916. Candidate.ExplicitCallArguments = 1;
  5917. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5918. Info);
  5919. return;
  5920. }
  5921. // Add the conversion function template specialization produced by
  5922. // template argument deduction as a candidate.
  5923. assert(Specialization && "Missing function template specialization?");
  5924. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  5925. CandidateSet, AllowObjCConversionOnExplicit);
  5926. }
  5927. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  5928. /// converts the given @c Object to a function pointer via the
  5929. /// conversion function @c Conversion, and then attempts to call it
  5930. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  5931. /// the type of function that we'll eventually be calling.
  5932. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  5933. DeclAccessPair FoundDecl,
  5934. CXXRecordDecl *ActingContext,
  5935. const FunctionProtoType *Proto,
  5936. Expr *Object,
  5937. ArrayRef<Expr *> Args,
  5938. OverloadCandidateSet& CandidateSet) {
  5939. if (!CandidateSet.isNewCandidate(Conversion))
  5940. return;
  5941. // Overload resolution is always an unevaluated context.
  5942. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5943. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5944. Candidate.FoundDecl = FoundDecl;
  5945. Candidate.Function = nullptr;
  5946. Candidate.Surrogate = Conversion;
  5947. Candidate.Viable = true;
  5948. Candidate.IsSurrogate = true;
  5949. Candidate.IgnoreObjectArgument = false;
  5950. Candidate.ExplicitCallArguments = Args.size();
  5951. // Determine the implicit conversion sequence for the implicit
  5952. // object parameter.
  5953. ImplicitConversionSequence ObjectInit
  5954. = TryObjectArgumentInitialization(*this, Object->getType(),
  5955. Object->Classify(Context),
  5956. Conversion, ActingContext);
  5957. if (ObjectInit.isBad()) {
  5958. Candidate.Viable = false;
  5959. Candidate.FailureKind = ovl_fail_bad_conversion;
  5960. Candidate.Conversions[0] = ObjectInit;
  5961. return;
  5962. }
  5963. // The first conversion is actually a user-defined conversion whose
  5964. // first conversion is ObjectInit's standard conversion (which is
  5965. // effectively a reference binding). Record it as such.
  5966. Candidate.Conversions[0].setUserDefined();
  5967. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  5968. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  5969. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  5970. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  5971. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  5972. Candidate.Conversions[0].UserDefined.After
  5973. = Candidate.Conversions[0].UserDefined.Before;
  5974. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  5975. // Find the
  5976. unsigned NumParams = Proto->getNumParams();
  5977. // (C++ 13.3.2p2): A candidate function having fewer than m
  5978. // parameters is viable only if it has an ellipsis in its parameter
  5979. // list (8.3.5).
  5980. if (Args.size() > NumParams && !Proto->isVariadic()) {
  5981. Candidate.Viable = false;
  5982. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5983. return;
  5984. }
  5985. // Function types don't have any default arguments, so just check if
  5986. // we have enough arguments.
  5987. if (Args.size() < NumParams) {
  5988. // Not enough arguments.
  5989. Candidate.Viable = false;
  5990. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5991. return;
  5992. }
  5993. // Determine the implicit conversion sequences for each of the
  5994. // arguments.
  5995. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  5996. if (ArgIdx < NumParams) {
  5997. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5998. // exist for each argument an implicit conversion sequence
  5999. // (13.3.3.1) that converts that argument to the corresponding
  6000. // parameter of F.
  6001. QualType ParamType = Proto->getParamType(ArgIdx);
  6002. Candidate.Conversions[ArgIdx + 1]
  6003. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6004. /*SuppressUserConversions=*/false,
  6005. /*InOverloadResolution=*/false,
  6006. /*AllowObjCWritebackConversion=*/
  6007. getLangOpts().ObjCAutoRefCount);
  6008. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6009. Candidate.Viable = false;
  6010. Candidate.FailureKind = ovl_fail_bad_conversion;
  6011. return;
  6012. }
  6013. } else {
  6014. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6015. // argument for which there is no corresponding parameter is
  6016. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6017. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6018. }
  6019. }
  6020. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6021. Candidate.Viable = false;
  6022. Candidate.FailureKind = ovl_fail_enable_if;
  6023. Candidate.DeductionFailure.Data = FailedAttr;
  6024. return;
  6025. }
  6026. }
  6027. /// \brief Add overload candidates for overloaded operators that are
  6028. /// member functions.
  6029. ///
  6030. /// Add the overloaded operator candidates that are member functions
  6031. /// for the operator Op that was used in an operator expression such
  6032. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6033. /// CandidateSet will store the added overload candidates. (C++
  6034. /// [over.match.oper]).
  6035. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6036. SourceLocation OpLoc,
  6037. ArrayRef<Expr *> Args,
  6038. OverloadCandidateSet& CandidateSet,
  6039. SourceRange OpRange) {
  6040. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6041. // C++ [over.match.oper]p3:
  6042. // For a unary operator @ with an operand of a type whose
  6043. // cv-unqualified version is T1, and for a binary operator @ with
  6044. // a left operand of a type whose cv-unqualified version is T1 and
  6045. // a right operand of a type whose cv-unqualified version is T2,
  6046. // three sets of candidate functions, designated member
  6047. // candidates, non-member candidates and built-in candidates, are
  6048. // constructed as follows:
  6049. QualType T1 = Args[0]->getType();
  6050. // -- If T1 is a complete class type or a class currently being
  6051. // defined, the set of member candidates is the result of the
  6052. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6053. // the set of member candidates is empty.
  6054. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6055. // Complete the type if it can be completed.
  6056. RequireCompleteType(OpLoc, T1, 0);
  6057. // If the type is neither complete nor being defined, bail out now.
  6058. if (!T1Rec->getDecl()->getDefinition())
  6059. return;
  6060. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6061. LookupQualifiedName(Operators, T1Rec->getDecl());
  6062. Operators.suppressDiagnostics();
  6063. for (LookupResult::iterator Oper = Operators.begin(),
  6064. OperEnd = Operators.end();
  6065. Oper != OperEnd;
  6066. ++Oper)
  6067. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6068. Args[0]->Classify(Context),
  6069. Args.slice(1),
  6070. CandidateSet,
  6071. /* SuppressUserConversions = */ false);
  6072. }
  6073. }
  6074. /// AddBuiltinCandidate - Add a candidate for a built-in
  6075. /// operator. ResultTy and ParamTys are the result and parameter types
  6076. /// of the built-in candidate, respectively. Args and NumArgs are the
  6077. /// arguments being passed to the candidate. IsAssignmentOperator
  6078. /// should be true when this built-in candidate is an assignment
  6079. /// operator. NumContextualBoolArguments is the number of arguments
  6080. /// (at the beginning of the argument list) that will be contextually
  6081. /// converted to bool.
  6082. void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
  6083. ArrayRef<Expr *> Args,
  6084. OverloadCandidateSet& CandidateSet,
  6085. bool IsAssignmentOperator,
  6086. unsigned NumContextualBoolArguments) {
  6087. // Overload resolution is always an unevaluated context.
  6088. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  6089. // Add this candidate
  6090. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6091. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6092. Candidate.Function = nullptr;
  6093. Candidate.IsSurrogate = false;
  6094. Candidate.IgnoreObjectArgument = false;
  6095. Candidate.BuiltinTypes.ResultTy = ResultTy;
  6096. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  6097. Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
  6098. // Determine the implicit conversion sequences for each of the
  6099. // arguments.
  6100. Candidate.Viable = true;
  6101. Candidate.ExplicitCallArguments = Args.size();
  6102. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6103. // C++ [over.match.oper]p4:
  6104. // For the built-in assignment operators, conversions of the
  6105. // left operand are restricted as follows:
  6106. // -- no temporaries are introduced to hold the left operand, and
  6107. // -- no user-defined conversions are applied to the left
  6108. // operand to achieve a type match with the left-most
  6109. // parameter of a built-in candidate.
  6110. //
  6111. // We block these conversions by turning off user-defined
  6112. // conversions, since that is the only way that initialization of
  6113. // a reference to a non-class type can occur from something that
  6114. // is not of the same type.
  6115. if (ArgIdx < NumContextualBoolArguments) {
  6116. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6117. "Contextual conversion to bool requires bool type");
  6118. Candidate.Conversions[ArgIdx]
  6119. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6120. } else {
  6121. Candidate.Conversions[ArgIdx]
  6122. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6123. ArgIdx == 0 && IsAssignmentOperator,
  6124. /*InOverloadResolution=*/false,
  6125. /*AllowObjCWritebackConversion=*/
  6126. getLangOpts().ObjCAutoRefCount);
  6127. }
  6128. if (Candidate.Conversions[ArgIdx].isBad()) {
  6129. Candidate.Viable = false;
  6130. Candidate.FailureKind = ovl_fail_bad_conversion;
  6131. break;
  6132. }
  6133. }
  6134. }
  6135. namespace {
  6136. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6137. /// candidate operator functions for built-in operators (C++
  6138. /// [over.built]). The types are separated into pointer types and
  6139. /// enumeration types.
  6140. class BuiltinCandidateTypeSet {
  6141. /// TypeSet - A set of types.
  6142. typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
  6143. /// PointerTypes - The set of pointer types that will be used in the
  6144. /// built-in candidates.
  6145. TypeSet PointerTypes;
  6146. /// MemberPointerTypes - The set of member pointer types that will be
  6147. /// used in the built-in candidates.
  6148. TypeSet MemberPointerTypes;
  6149. /// EnumerationTypes - The set of enumeration types that will be
  6150. /// used in the built-in candidates.
  6151. TypeSet EnumerationTypes;
  6152. /// \brief The set of vector types that will be used in the built-in
  6153. /// candidates.
  6154. TypeSet VectorTypes;
  6155. /// \brief A flag indicating non-record types are viable candidates
  6156. bool HasNonRecordTypes;
  6157. /// \brief A flag indicating whether either arithmetic or enumeration types
  6158. /// were present in the candidate set.
  6159. bool HasArithmeticOrEnumeralTypes;
  6160. /// \brief A flag indicating whether the nullptr type was present in the
  6161. /// candidate set.
  6162. bool HasNullPtrType;
  6163. /// Sema - The semantic analysis instance where we are building the
  6164. /// candidate type set.
  6165. Sema &SemaRef;
  6166. /// Context - The AST context in which we will build the type sets.
  6167. ASTContext &Context;
  6168. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6169. const Qualifiers &VisibleQuals);
  6170. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6171. public:
  6172. /// iterator - Iterates through the types that are part of the set.
  6173. typedef TypeSet::iterator iterator;
  6174. BuiltinCandidateTypeSet(Sema &SemaRef)
  6175. : HasNonRecordTypes(false),
  6176. HasArithmeticOrEnumeralTypes(false),
  6177. HasNullPtrType(false),
  6178. SemaRef(SemaRef),
  6179. Context(SemaRef.Context) { }
  6180. void AddTypesConvertedFrom(QualType Ty,
  6181. SourceLocation Loc,
  6182. bool AllowUserConversions,
  6183. bool AllowExplicitConversions,
  6184. const Qualifiers &VisibleTypeConversionsQuals);
  6185. /// pointer_begin - First pointer type found;
  6186. iterator pointer_begin() { return PointerTypes.begin(); }
  6187. /// pointer_end - Past the last pointer type found;
  6188. iterator pointer_end() { return PointerTypes.end(); }
  6189. /// member_pointer_begin - First member pointer type found;
  6190. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6191. /// member_pointer_end - Past the last member pointer type found;
  6192. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6193. /// enumeration_begin - First enumeration type found;
  6194. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6195. /// enumeration_end - Past the last enumeration type found;
  6196. iterator enumeration_end() { return EnumerationTypes.end(); }
  6197. iterator vector_begin() { return VectorTypes.begin(); }
  6198. iterator vector_end() { return VectorTypes.end(); }
  6199. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6200. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6201. bool hasNullPtrType() const { return HasNullPtrType; }
  6202. };
  6203. } // end anonymous namespace
  6204. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6205. /// the set of pointer types along with any more-qualified variants of
  6206. /// that type. For example, if @p Ty is "int const *", this routine
  6207. /// will add "int const *", "int const volatile *", "int const
  6208. /// restrict *", and "int const volatile restrict *" to the set of
  6209. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6210. /// false otherwise.
  6211. ///
  6212. /// FIXME: what to do about extended qualifiers?
  6213. bool
  6214. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6215. const Qualifiers &VisibleQuals) {
  6216. // Insert this type.
  6217. if (!PointerTypes.insert(Ty).second)
  6218. return false;
  6219. QualType PointeeTy;
  6220. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6221. bool buildObjCPtr = false;
  6222. if (!PointerTy) {
  6223. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6224. PointeeTy = PTy->getPointeeType();
  6225. buildObjCPtr = true;
  6226. } else {
  6227. PointeeTy = PointerTy->getPointeeType();
  6228. }
  6229. // Don't add qualified variants of arrays. For one, they're not allowed
  6230. // (the qualifier would sink to the element type), and for another, the
  6231. // only overload situation where it matters is subscript or pointer +- int,
  6232. // and those shouldn't have qualifier variants anyway.
  6233. if (PointeeTy->isArrayType())
  6234. return true;
  6235. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6236. bool hasVolatile = VisibleQuals.hasVolatile();
  6237. bool hasRestrict = VisibleQuals.hasRestrict();
  6238. // Iterate through all strict supersets of BaseCVR.
  6239. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6240. if ((CVR | BaseCVR) != CVR) continue;
  6241. // Skip over volatile if no volatile found anywhere in the types.
  6242. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6243. // Skip over restrict if no restrict found anywhere in the types, or if
  6244. // the type cannot be restrict-qualified.
  6245. if ((CVR & Qualifiers::Restrict) &&
  6246. (!hasRestrict ||
  6247. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6248. continue;
  6249. // Build qualified pointee type.
  6250. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6251. // Build qualified pointer type.
  6252. QualType QPointerTy;
  6253. if (!buildObjCPtr)
  6254. QPointerTy = Context.getPointerType(QPointeeTy);
  6255. else
  6256. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6257. // Insert qualified pointer type.
  6258. PointerTypes.insert(QPointerTy);
  6259. }
  6260. return true;
  6261. }
  6262. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6263. /// to the set of pointer types along with any more-qualified variants of
  6264. /// that type. For example, if @p Ty is "int const *", this routine
  6265. /// will add "int const *", "int const volatile *", "int const
  6266. /// restrict *", and "int const volatile restrict *" to the set of
  6267. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6268. /// false otherwise.
  6269. ///
  6270. /// FIXME: what to do about extended qualifiers?
  6271. bool
  6272. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6273. QualType Ty) {
  6274. // Insert this type.
  6275. if (!MemberPointerTypes.insert(Ty).second)
  6276. return false;
  6277. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6278. assert(PointerTy && "type was not a member pointer type!");
  6279. QualType PointeeTy = PointerTy->getPointeeType();
  6280. // Don't add qualified variants of arrays. For one, they're not allowed
  6281. // (the qualifier would sink to the element type), and for another, the
  6282. // only overload situation where it matters is subscript or pointer +- int,
  6283. // and those shouldn't have qualifier variants anyway.
  6284. if (PointeeTy->isArrayType())
  6285. return true;
  6286. const Type *ClassTy = PointerTy->getClass();
  6287. // Iterate through all strict supersets of the pointee type's CVR
  6288. // qualifiers.
  6289. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6290. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6291. if ((CVR | BaseCVR) != CVR) continue;
  6292. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6293. MemberPointerTypes.insert(
  6294. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6295. }
  6296. return true;
  6297. }
  6298. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6299. /// Ty can be implicit converted to the given set of @p Types. We're
  6300. /// primarily interested in pointer types and enumeration types. We also
  6301. /// take member pointer types, for the conditional operator.
  6302. /// AllowUserConversions is true if we should look at the conversion
  6303. /// functions of a class type, and AllowExplicitConversions if we
  6304. /// should also include the explicit conversion functions of a class
  6305. /// type.
  6306. void
  6307. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6308. SourceLocation Loc,
  6309. bool AllowUserConversions,
  6310. bool AllowExplicitConversions,
  6311. const Qualifiers &VisibleQuals) {
  6312. // Only deal with canonical types.
  6313. Ty = Context.getCanonicalType(Ty);
  6314. // Look through reference types; they aren't part of the type of an
  6315. // expression for the purposes of conversions.
  6316. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6317. Ty = RefTy->getPointeeType();
  6318. // If we're dealing with an array type, decay to the pointer.
  6319. if (Ty->isArrayType())
  6320. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6321. // Otherwise, we don't care about qualifiers on the type.
  6322. Ty = Ty.getLocalUnqualifiedType();
  6323. // Flag if we ever add a non-record type.
  6324. const RecordType *TyRec = Ty->getAs<RecordType>();
  6325. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6326. // Flag if we encounter an arithmetic type.
  6327. HasArithmeticOrEnumeralTypes =
  6328. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6329. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6330. PointerTypes.insert(Ty);
  6331. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6332. // Insert our type, and its more-qualified variants, into the set
  6333. // of types.
  6334. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6335. return;
  6336. } else if (Ty->isMemberPointerType()) {
  6337. // Member pointers are far easier, since the pointee can't be converted.
  6338. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6339. return;
  6340. } else if (Ty->isEnumeralType()) {
  6341. HasArithmeticOrEnumeralTypes = true;
  6342. EnumerationTypes.insert(Ty);
  6343. } else if (Ty->isVectorType()) {
  6344. // We treat vector types as arithmetic types in many contexts as an
  6345. // extension.
  6346. HasArithmeticOrEnumeralTypes = true;
  6347. VectorTypes.insert(Ty);
  6348. } else if (Ty->isNullPtrType()) {
  6349. HasNullPtrType = true;
  6350. } else if (AllowUserConversions && TyRec) {
  6351. // No conversion functions in incomplete types.
  6352. if (SemaRef.RequireCompleteType(Loc, Ty, 0))
  6353. return;
  6354. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6355. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6356. if (isa<UsingShadowDecl>(D))
  6357. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6358. // Skip conversion function templates; they don't tell us anything
  6359. // about which builtin types we can convert to.
  6360. if (isa<FunctionTemplateDecl>(D))
  6361. continue;
  6362. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6363. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6364. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6365. VisibleQuals);
  6366. }
  6367. }
  6368. }
  6369. }
  6370. /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
  6371. /// the volatile- and non-volatile-qualified assignment operators for the
  6372. /// given type to the candidate set.
  6373. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  6374. QualType T,
  6375. ArrayRef<Expr *> Args,
  6376. OverloadCandidateSet &CandidateSet) {
  6377. QualType ParamTypes[2];
  6378. // T& operator=(T&, T)
  6379. ParamTypes[0] = S.Context.getLValueReferenceType(T);
  6380. ParamTypes[1] = T;
  6381. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6382. /*IsAssignmentOperator=*/true);
  6383. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  6384. // volatile T& operator=(volatile T&, T)
  6385. ParamTypes[0]
  6386. = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
  6387. ParamTypes[1] = T;
  6388. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6389. /*IsAssignmentOperator=*/true);
  6390. }
  6391. }
  6392. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  6393. /// if any, found in visible type conversion functions found in ArgExpr's type.
  6394. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  6395. Qualifiers VRQuals;
  6396. const RecordType *TyRec;
  6397. if (const MemberPointerType *RHSMPType =
  6398. ArgExpr->getType()->getAs<MemberPointerType>())
  6399. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  6400. else
  6401. TyRec = ArgExpr->getType()->getAs<RecordType>();
  6402. if (!TyRec) {
  6403. // Just to be safe, assume the worst case.
  6404. VRQuals.addVolatile();
  6405. VRQuals.addRestrict();
  6406. return VRQuals;
  6407. }
  6408. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6409. if (!ClassDecl->hasDefinition())
  6410. return VRQuals;
  6411. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6412. if (isa<UsingShadowDecl>(D))
  6413. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6414. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  6415. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  6416. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  6417. CanTy = ResTypeRef->getPointeeType();
  6418. // Need to go down the pointer/mempointer chain and add qualifiers
  6419. // as see them.
  6420. bool done = false;
  6421. while (!done) {
  6422. if (CanTy.isRestrictQualified())
  6423. VRQuals.addRestrict();
  6424. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  6425. CanTy = ResTypePtr->getPointeeType();
  6426. else if (const MemberPointerType *ResTypeMPtr =
  6427. CanTy->getAs<MemberPointerType>())
  6428. CanTy = ResTypeMPtr->getPointeeType();
  6429. else
  6430. done = true;
  6431. if (CanTy.isVolatileQualified())
  6432. VRQuals.addVolatile();
  6433. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  6434. return VRQuals;
  6435. }
  6436. }
  6437. }
  6438. return VRQuals;
  6439. }
  6440. namespace {
  6441. /// \brief Helper class to manage the addition of builtin operator overload
  6442. /// candidates. It provides shared state and utility methods used throughout
  6443. /// the process, as well as a helper method to add each group of builtin
  6444. /// operator overloads from the standard to a candidate set.
  6445. class BuiltinOperatorOverloadBuilder {
  6446. // Common instance state available to all overload candidate addition methods.
  6447. Sema &S;
  6448. ArrayRef<Expr *> Args;
  6449. Qualifiers VisibleTypeConversionsQuals;
  6450. bool HasArithmeticOrEnumeralCandidateType;
  6451. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  6452. OverloadCandidateSet &CandidateSet;
  6453. // Define some constants used to index and iterate over the arithemetic types
  6454. // provided via the getArithmeticType() method below.
  6455. // The "promoted arithmetic types" are the arithmetic
  6456. // types are that preserved by promotion (C++ [over.built]p2).
  6457. static const unsigned FirstIntegralType = 3;
  6458. static const unsigned LastIntegralType = 20;
  6459. static const unsigned FirstPromotedIntegralType = 3,
  6460. LastPromotedIntegralType = 11;
  6461. static const unsigned FirstPromotedArithmeticType = 0,
  6462. LastPromotedArithmeticType = 11;
  6463. static const unsigned NumArithmeticTypes = 20;
  6464. /// \brief Get the canonical type for a given arithmetic type index.
  6465. CanQualType getArithmeticType(unsigned index) {
  6466. assert(index < NumArithmeticTypes);
  6467. static CanQualType ASTContext::* const
  6468. ArithmeticTypes[NumArithmeticTypes] = {
  6469. // Start of promoted types.
  6470. &ASTContext::FloatTy,
  6471. &ASTContext::DoubleTy,
  6472. &ASTContext::LongDoubleTy,
  6473. // Start of integral types.
  6474. &ASTContext::IntTy,
  6475. &ASTContext::LongTy,
  6476. &ASTContext::LongLongTy,
  6477. &ASTContext::Int128Ty,
  6478. &ASTContext::UnsignedIntTy,
  6479. &ASTContext::UnsignedLongTy,
  6480. &ASTContext::UnsignedLongLongTy,
  6481. &ASTContext::UnsignedInt128Ty,
  6482. // End of promoted types.
  6483. &ASTContext::BoolTy,
  6484. &ASTContext::CharTy,
  6485. &ASTContext::WCharTy,
  6486. &ASTContext::Char16Ty,
  6487. &ASTContext::Char32Ty,
  6488. &ASTContext::SignedCharTy,
  6489. &ASTContext::ShortTy,
  6490. &ASTContext::UnsignedCharTy,
  6491. &ASTContext::UnsignedShortTy,
  6492. // End of integral types.
  6493. // FIXME: What about complex? What about half?
  6494. };
  6495. return S.Context.*ArithmeticTypes[index];
  6496. }
  6497. /// \brief Gets the canonical type resulting from the usual arithemetic
  6498. /// converions for the given arithmetic types.
  6499. CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
  6500. // Accelerator table for performing the usual arithmetic conversions.
  6501. // The rules are basically:
  6502. // - if either is floating-point, use the wider floating-point
  6503. // - if same signedness, use the higher rank
  6504. // - if same size, use unsigned of the higher rank
  6505. // - use the larger type
  6506. // These rules, together with the axiom that higher ranks are
  6507. // never smaller, are sufficient to precompute all of these results
  6508. // *except* when dealing with signed types of higher rank.
  6509. // (we could precompute SLL x UI for all known platforms, but it's
  6510. // better not to make any assumptions).
  6511. // We assume that int128 has a higher rank than long long on all platforms.
  6512. enum PromotedType {
  6513. Dep=-1,
  6514. Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
  6515. };
  6516. static const PromotedType ConversionsTable[LastPromotedArithmeticType]
  6517. [LastPromotedArithmeticType] = {
  6518. /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
  6519. /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
  6520. /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
  6521. /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
  6522. /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
  6523. /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
  6524. /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
  6525. /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
  6526. /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
  6527. /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
  6528. /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
  6529. };
  6530. assert(L < LastPromotedArithmeticType);
  6531. assert(R < LastPromotedArithmeticType);
  6532. int Idx = ConversionsTable[L][R];
  6533. // Fast path: the table gives us a concrete answer.
  6534. if (Idx != Dep) return getArithmeticType(Idx);
  6535. // Slow path: we need to compare widths.
  6536. // An invariant is that the signed type has higher rank.
  6537. CanQualType LT = getArithmeticType(L),
  6538. RT = getArithmeticType(R);
  6539. unsigned LW = S.Context.getIntWidth(LT),
  6540. RW = S.Context.getIntWidth(RT);
  6541. // If they're different widths, use the signed type.
  6542. if (LW > RW) return LT;
  6543. else if (LW < RW) return RT;
  6544. // Otherwise, use the unsigned type of the signed type's rank.
  6545. if (L == SL || R == SL) return S.Context.UnsignedLongTy;
  6546. assert(L == SLL || R == SLL);
  6547. return S.Context.UnsignedLongLongTy;
  6548. }
  6549. /// \brief Helper method to factor out the common pattern of adding overloads
  6550. /// for '++' and '--' builtin operators.
  6551. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  6552. bool HasVolatile,
  6553. bool HasRestrict) {
  6554. QualType ParamTypes[2] = {
  6555. S.Context.getLValueReferenceType(CandidateTy),
  6556. S.Context.IntTy
  6557. };
  6558. // Non-volatile version.
  6559. if (Args.size() == 1)
  6560. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6561. else
  6562. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6563. // Use a heuristic to reduce number of builtin candidates in the set:
  6564. // add volatile version only if there are conversions to a volatile type.
  6565. if (HasVolatile) {
  6566. ParamTypes[0] =
  6567. S.Context.getLValueReferenceType(
  6568. S.Context.getVolatileType(CandidateTy));
  6569. if (Args.size() == 1)
  6570. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6571. else
  6572. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6573. }
  6574. // Add restrict version only if there are conversions to a restrict type
  6575. // and our candidate type is a non-restrict-qualified pointer.
  6576. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  6577. !CandidateTy.isRestrictQualified()) {
  6578. ParamTypes[0]
  6579. = S.Context.getLValueReferenceType(
  6580. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  6581. if (Args.size() == 1)
  6582. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6583. else
  6584. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6585. if (HasVolatile) {
  6586. ParamTypes[0]
  6587. = S.Context.getLValueReferenceType(
  6588. S.Context.getCVRQualifiedType(CandidateTy,
  6589. (Qualifiers::Volatile |
  6590. Qualifiers::Restrict)));
  6591. if (Args.size() == 1)
  6592. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6593. else
  6594. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6595. }
  6596. }
  6597. }
  6598. public:
  6599. BuiltinOperatorOverloadBuilder(
  6600. Sema &S, ArrayRef<Expr *> Args,
  6601. Qualifiers VisibleTypeConversionsQuals,
  6602. bool HasArithmeticOrEnumeralCandidateType,
  6603. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  6604. OverloadCandidateSet &CandidateSet)
  6605. : S(S), Args(Args),
  6606. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  6607. HasArithmeticOrEnumeralCandidateType(
  6608. HasArithmeticOrEnumeralCandidateType),
  6609. CandidateTypes(CandidateTypes),
  6610. CandidateSet(CandidateSet) {
  6611. // Validate some of our static helper constants in debug builds.
  6612. assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
  6613. "Invalid first promoted integral type");
  6614. assert(getArithmeticType(LastPromotedIntegralType - 1)
  6615. == S.Context.UnsignedInt128Ty &&
  6616. "Invalid last promoted integral type");
  6617. assert(getArithmeticType(FirstPromotedArithmeticType)
  6618. == S.Context.FloatTy &&
  6619. "Invalid first promoted arithmetic type");
  6620. assert(getArithmeticType(LastPromotedArithmeticType - 1)
  6621. == S.Context.UnsignedInt128Ty &&
  6622. "Invalid last promoted arithmetic type");
  6623. }
  6624. // C++ [over.built]p3:
  6625. //
  6626. // For every pair (T, VQ), where T is an arithmetic type, and VQ
  6627. // is either volatile or empty, there exist candidate operator
  6628. // functions of the form
  6629. //
  6630. // VQ T& operator++(VQ T&);
  6631. // T operator++(VQ T&, int);
  6632. //
  6633. // C++ [over.built]p4:
  6634. //
  6635. // For every pair (T, VQ), where T is an arithmetic type other
  6636. // than bool, and VQ is either volatile or empty, there exist
  6637. // candidate operator functions of the form
  6638. //
  6639. // VQ T& operator--(VQ T&);
  6640. // T operator--(VQ T&, int);
  6641. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  6642. if (!HasArithmeticOrEnumeralCandidateType)
  6643. return;
  6644. for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
  6645. Arith < NumArithmeticTypes; ++Arith) {
  6646. addPlusPlusMinusMinusStyleOverloads(
  6647. getArithmeticType(Arith),
  6648. VisibleTypeConversionsQuals.hasVolatile(),
  6649. VisibleTypeConversionsQuals.hasRestrict());
  6650. }
  6651. }
  6652. // C++ [over.built]p5:
  6653. //
  6654. // For every pair (T, VQ), where T is a cv-qualified or
  6655. // cv-unqualified object type, and VQ is either volatile or
  6656. // empty, there exist candidate operator functions of the form
  6657. //
  6658. // T*VQ& operator++(T*VQ&);
  6659. // T*VQ& operator--(T*VQ&);
  6660. // T* operator++(T*VQ&, int);
  6661. // T* operator--(T*VQ&, int);
  6662. void addPlusPlusMinusMinusPointerOverloads() {
  6663. for (BuiltinCandidateTypeSet::iterator
  6664. Ptr = CandidateTypes[0].pointer_begin(),
  6665. PtrEnd = CandidateTypes[0].pointer_end();
  6666. Ptr != PtrEnd; ++Ptr) {
  6667. // Skip pointer types that aren't pointers to object types.
  6668. if (!(*Ptr)->getPointeeType()->isObjectType())
  6669. continue;
  6670. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  6671. (!(*Ptr).isVolatileQualified() &&
  6672. VisibleTypeConversionsQuals.hasVolatile()),
  6673. (!(*Ptr).isRestrictQualified() &&
  6674. VisibleTypeConversionsQuals.hasRestrict()));
  6675. }
  6676. }
  6677. // C++ [over.built]p6:
  6678. // For every cv-qualified or cv-unqualified object type T, there
  6679. // exist candidate operator functions of the form
  6680. //
  6681. // T& operator*(T*);
  6682. //
  6683. // C++ [over.built]p7:
  6684. // For every function type T that does not have cv-qualifiers or a
  6685. // ref-qualifier, there exist candidate operator functions of the form
  6686. // T& operator*(T*);
  6687. void addUnaryStarPointerOverloads() {
  6688. for (BuiltinCandidateTypeSet::iterator
  6689. Ptr = CandidateTypes[0].pointer_begin(),
  6690. PtrEnd = CandidateTypes[0].pointer_end();
  6691. Ptr != PtrEnd; ++Ptr) {
  6692. QualType ParamTy = *Ptr;
  6693. QualType PointeeTy = ParamTy->getPointeeType();
  6694. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  6695. continue;
  6696. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  6697. if (Proto->getTypeQuals() || Proto->getRefQualifier())
  6698. continue;
  6699. S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
  6700. &ParamTy, Args, CandidateSet);
  6701. }
  6702. }
  6703. // C++ [over.built]p9:
  6704. // For every promoted arithmetic type T, there exist candidate
  6705. // operator functions of the form
  6706. //
  6707. // T operator+(T);
  6708. // T operator-(T);
  6709. void addUnaryPlusOrMinusArithmeticOverloads() {
  6710. if (!HasArithmeticOrEnumeralCandidateType)
  6711. return;
  6712. for (unsigned Arith = FirstPromotedArithmeticType;
  6713. Arith < LastPromotedArithmeticType; ++Arith) {
  6714. QualType ArithTy = getArithmeticType(Arith);
  6715. S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
  6716. }
  6717. // Extension: We also add these operators for vector types.
  6718. for (BuiltinCandidateTypeSet::iterator
  6719. Vec = CandidateTypes[0].vector_begin(),
  6720. VecEnd = CandidateTypes[0].vector_end();
  6721. Vec != VecEnd; ++Vec) {
  6722. QualType VecTy = *Vec;
  6723. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6724. }
  6725. }
  6726. // C++ [over.built]p8:
  6727. // For every type T, there exist candidate operator functions of
  6728. // the form
  6729. //
  6730. // T* operator+(T*);
  6731. void addUnaryPlusPointerOverloads() {
  6732. for (BuiltinCandidateTypeSet::iterator
  6733. Ptr = CandidateTypes[0].pointer_begin(),
  6734. PtrEnd = CandidateTypes[0].pointer_end();
  6735. Ptr != PtrEnd; ++Ptr) {
  6736. QualType ParamTy = *Ptr;
  6737. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
  6738. }
  6739. }
  6740. // C++ [over.built]p10:
  6741. // For every promoted integral type T, there exist candidate
  6742. // operator functions of the form
  6743. //
  6744. // T operator~(T);
  6745. void addUnaryTildePromotedIntegralOverloads() {
  6746. if (!HasArithmeticOrEnumeralCandidateType)
  6747. return;
  6748. for (unsigned Int = FirstPromotedIntegralType;
  6749. Int < LastPromotedIntegralType; ++Int) {
  6750. QualType IntTy = getArithmeticType(Int);
  6751. S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
  6752. }
  6753. // Extension: We also add this operator for vector types.
  6754. for (BuiltinCandidateTypeSet::iterator
  6755. Vec = CandidateTypes[0].vector_begin(),
  6756. VecEnd = CandidateTypes[0].vector_end();
  6757. Vec != VecEnd; ++Vec) {
  6758. QualType VecTy = *Vec;
  6759. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6760. }
  6761. }
  6762. // C++ [over.match.oper]p16:
  6763. // For every pointer to member type T, there exist candidate operator
  6764. // functions of the form
  6765. //
  6766. // bool operator==(T,T);
  6767. // bool operator!=(T,T);
  6768. void addEqualEqualOrNotEqualMemberPointerOverloads() {
  6769. /// Set of (canonical) types that we've already handled.
  6770. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6771. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6772. for (BuiltinCandidateTypeSet::iterator
  6773. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6774. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6775. MemPtr != MemPtrEnd;
  6776. ++MemPtr) {
  6777. // Don't add the same builtin candidate twice.
  6778. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  6779. continue;
  6780. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  6781. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6782. }
  6783. }
  6784. }
  6785. // C++ [over.built]p15:
  6786. //
  6787. // For every T, where T is an enumeration type, a pointer type, or
  6788. // std::nullptr_t, there exist candidate operator functions of the form
  6789. //
  6790. // bool operator<(T, T);
  6791. // bool operator>(T, T);
  6792. // bool operator<=(T, T);
  6793. // bool operator>=(T, T);
  6794. // bool operator==(T, T);
  6795. // bool operator!=(T, T);
  6796. void addRelationalPointerOrEnumeralOverloads() {
  6797. // C++ [over.match.oper]p3:
  6798. // [...]the built-in candidates include all of the candidate operator
  6799. // functions defined in 13.6 that, compared to the given operator, [...]
  6800. // do not have the same parameter-type-list as any non-template non-member
  6801. // candidate.
  6802. //
  6803. // Note that in practice, this only affects enumeration types because there
  6804. // aren't any built-in candidates of record type, and a user-defined operator
  6805. // must have an operand of record or enumeration type. Also, the only other
  6806. // overloaded operator with enumeration arguments, operator=,
  6807. // cannot be overloaded for enumeration types, so this is the only place
  6808. // where we must suppress candidates like this.
  6809. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  6810. UserDefinedBinaryOperators;
  6811. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6812. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  6813. CandidateTypes[ArgIdx].enumeration_end()) {
  6814. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  6815. CEnd = CandidateSet.end();
  6816. C != CEnd; ++C) {
  6817. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  6818. continue;
  6819. if (C->Function->isFunctionTemplateSpecialization())
  6820. continue;
  6821. QualType FirstParamType =
  6822. C->Function->getParamDecl(0)->getType().getUnqualifiedType();
  6823. QualType SecondParamType =
  6824. C->Function->getParamDecl(1)->getType().getUnqualifiedType();
  6825. // Skip if either parameter isn't of enumeral type.
  6826. if (!FirstParamType->isEnumeralType() ||
  6827. !SecondParamType->isEnumeralType())
  6828. continue;
  6829. // Add this operator to the set of known user-defined operators.
  6830. UserDefinedBinaryOperators.insert(
  6831. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  6832. S.Context.getCanonicalType(SecondParamType)));
  6833. }
  6834. }
  6835. }
  6836. /// Set of (canonical) types that we've already handled.
  6837. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6838. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6839. for (BuiltinCandidateTypeSet::iterator
  6840. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  6841. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  6842. Ptr != PtrEnd; ++Ptr) {
  6843. // Don't add the same builtin candidate twice.
  6844. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6845. continue;
  6846. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6847. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6848. }
  6849. for (BuiltinCandidateTypeSet::iterator
  6850. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6851. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6852. Enum != EnumEnd; ++Enum) {
  6853. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  6854. // Don't add the same builtin candidate twice, or if a user defined
  6855. // candidate exists.
  6856. if (!AddedTypes.insert(CanonType).second ||
  6857. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  6858. CanonType)))
  6859. continue;
  6860. QualType ParamTypes[2] = { *Enum, *Enum };
  6861. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6862. }
  6863. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  6864. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  6865. if (AddedTypes.insert(NullPtrTy).second &&
  6866. !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
  6867. NullPtrTy))) {
  6868. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  6869. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
  6870. CandidateSet);
  6871. }
  6872. }
  6873. }
  6874. }
  6875. // C++ [over.built]p13:
  6876. //
  6877. // For every cv-qualified or cv-unqualified object type T
  6878. // there exist candidate operator functions of the form
  6879. //
  6880. // T* operator+(T*, ptrdiff_t);
  6881. // T& operator[](T*, ptrdiff_t); [BELOW]
  6882. // T* operator-(T*, ptrdiff_t);
  6883. // T* operator+(ptrdiff_t, T*);
  6884. // T& operator[](ptrdiff_t, T*); [BELOW]
  6885. //
  6886. // C++ [over.built]p14:
  6887. //
  6888. // For every T, where T is a pointer to object type, there
  6889. // exist candidate operator functions of the form
  6890. //
  6891. // ptrdiff_t operator-(T, T);
  6892. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  6893. /// Set of (canonical) types that we've already handled.
  6894. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6895. for (int Arg = 0; Arg < 2; ++Arg) {
  6896. QualType AsymetricParamTypes[2] = {
  6897. S.Context.getPointerDiffType(),
  6898. S.Context.getPointerDiffType(),
  6899. };
  6900. for (BuiltinCandidateTypeSet::iterator
  6901. Ptr = CandidateTypes[Arg].pointer_begin(),
  6902. PtrEnd = CandidateTypes[Arg].pointer_end();
  6903. Ptr != PtrEnd; ++Ptr) {
  6904. QualType PointeeTy = (*Ptr)->getPointeeType();
  6905. if (!PointeeTy->isObjectType())
  6906. continue;
  6907. AsymetricParamTypes[Arg] = *Ptr;
  6908. if (Arg == 0 || Op == OO_Plus) {
  6909. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  6910. // T* operator+(ptrdiff_t, T*);
  6911. S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
  6912. }
  6913. if (Op == OO_Minus) {
  6914. // ptrdiff_t operator-(T, T);
  6915. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6916. continue;
  6917. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6918. S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
  6919. Args, CandidateSet);
  6920. }
  6921. }
  6922. }
  6923. }
  6924. // C++ [over.built]p12:
  6925. //
  6926. // For every pair of promoted arithmetic types L and R, there
  6927. // exist candidate operator functions of the form
  6928. //
  6929. // LR operator*(L, R);
  6930. // LR operator/(L, R);
  6931. // LR operator+(L, R);
  6932. // LR operator-(L, R);
  6933. // bool operator<(L, R);
  6934. // bool operator>(L, R);
  6935. // bool operator<=(L, R);
  6936. // bool operator>=(L, R);
  6937. // bool operator==(L, R);
  6938. // bool operator!=(L, R);
  6939. //
  6940. // where LR is the result of the usual arithmetic conversions
  6941. // between types L and R.
  6942. //
  6943. // C++ [over.built]p24:
  6944. //
  6945. // For every pair of promoted arithmetic types L and R, there exist
  6946. // candidate operator functions of the form
  6947. //
  6948. // LR operator?(bool, L, R);
  6949. //
  6950. // where LR is the result of the usual arithmetic conversions
  6951. // between types L and R.
  6952. // Our candidates ignore the first parameter.
  6953. void addGenericBinaryArithmeticOverloads(bool isComparison) {
  6954. if (!HasArithmeticOrEnumeralCandidateType)
  6955. return;
  6956. for (unsigned Left = FirstPromotedArithmeticType;
  6957. Left < LastPromotedArithmeticType; ++Left) {
  6958. for (unsigned Right = FirstPromotedArithmeticType;
  6959. Right < LastPromotedArithmeticType; ++Right) {
  6960. QualType LandR[2] = { getArithmeticType(Left),
  6961. getArithmeticType(Right) };
  6962. QualType Result =
  6963. isComparison ? S.Context.BoolTy
  6964. : getUsualArithmeticConversions(Left, Right);
  6965. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6966. }
  6967. }
  6968. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  6969. // conditional operator for vector types.
  6970. for (BuiltinCandidateTypeSet::iterator
  6971. Vec1 = CandidateTypes[0].vector_begin(),
  6972. Vec1End = CandidateTypes[0].vector_end();
  6973. Vec1 != Vec1End; ++Vec1) {
  6974. for (BuiltinCandidateTypeSet::iterator
  6975. Vec2 = CandidateTypes[1].vector_begin(),
  6976. Vec2End = CandidateTypes[1].vector_end();
  6977. Vec2 != Vec2End; ++Vec2) {
  6978. QualType LandR[2] = { *Vec1, *Vec2 };
  6979. QualType Result = S.Context.BoolTy;
  6980. if (!isComparison) {
  6981. if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
  6982. Result = *Vec1;
  6983. else
  6984. Result = *Vec2;
  6985. }
  6986. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6987. }
  6988. }
  6989. }
  6990. // C++ [over.built]p17:
  6991. //
  6992. // For every pair of promoted integral types L and R, there
  6993. // exist candidate operator functions of the form
  6994. //
  6995. // LR operator%(L, R);
  6996. // LR operator&(L, R);
  6997. // LR operator^(L, R);
  6998. // LR operator|(L, R);
  6999. // L operator<<(L, R);
  7000. // L operator>>(L, R);
  7001. //
  7002. // where LR is the result of the usual arithmetic conversions
  7003. // between types L and R.
  7004. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7005. if (!HasArithmeticOrEnumeralCandidateType)
  7006. return;
  7007. for (unsigned Left = FirstPromotedIntegralType;
  7008. Left < LastPromotedIntegralType; ++Left) {
  7009. for (unsigned Right = FirstPromotedIntegralType;
  7010. Right < LastPromotedIntegralType; ++Right) {
  7011. QualType LandR[2] = { getArithmeticType(Left),
  7012. getArithmeticType(Right) };
  7013. QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
  7014. ? LandR[0]
  7015. : getUsualArithmeticConversions(Left, Right);
  7016. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  7017. }
  7018. }
  7019. }
  7020. // C++ [over.built]p20:
  7021. //
  7022. // For every pair (T, VQ), where T is an enumeration or
  7023. // pointer to member type and VQ is either volatile or
  7024. // empty, there exist candidate operator functions of the form
  7025. //
  7026. // VQ T& operator=(VQ T&, T);
  7027. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7028. /// Set of (canonical) types that we've already handled.
  7029. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7030. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7031. for (BuiltinCandidateTypeSet::iterator
  7032. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7033. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7034. Enum != EnumEnd; ++Enum) {
  7035. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7036. continue;
  7037. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7038. }
  7039. for (BuiltinCandidateTypeSet::iterator
  7040. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7041. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7042. MemPtr != MemPtrEnd; ++MemPtr) {
  7043. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7044. continue;
  7045. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7046. }
  7047. }
  7048. }
  7049. // C++ [over.built]p19:
  7050. //
  7051. // For every pair (T, VQ), where T is any type and VQ is either
  7052. // volatile or empty, there exist candidate operator functions
  7053. // of the form
  7054. //
  7055. // T*VQ& operator=(T*VQ&, T*);
  7056. //
  7057. // C++ [over.built]p21:
  7058. //
  7059. // For every pair (T, VQ), where T is a cv-qualified or
  7060. // cv-unqualified object type and VQ is either volatile or
  7061. // empty, there exist candidate operator functions of the form
  7062. //
  7063. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7064. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7065. void addAssignmentPointerOverloads(bool isEqualOp) {
  7066. /// Set of (canonical) types that we've already handled.
  7067. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7068. for (BuiltinCandidateTypeSet::iterator
  7069. Ptr = CandidateTypes[0].pointer_begin(),
  7070. PtrEnd = CandidateTypes[0].pointer_end();
  7071. Ptr != PtrEnd; ++Ptr) {
  7072. // If this is operator=, keep track of the builtin candidates we added.
  7073. if (isEqualOp)
  7074. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7075. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7076. continue;
  7077. // non-volatile version
  7078. QualType ParamTypes[2] = {
  7079. S.Context.getLValueReferenceType(*Ptr),
  7080. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7081. };
  7082. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7083. /*IsAssigmentOperator=*/ isEqualOp);
  7084. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7085. VisibleTypeConversionsQuals.hasVolatile();
  7086. if (NeedVolatile) {
  7087. // volatile version
  7088. ParamTypes[0] =
  7089. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7090. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7091. /*IsAssigmentOperator=*/isEqualOp);
  7092. }
  7093. if (!(*Ptr).isRestrictQualified() &&
  7094. VisibleTypeConversionsQuals.hasRestrict()) {
  7095. // restrict version
  7096. ParamTypes[0]
  7097. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7098. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7099. /*IsAssigmentOperator=*/isEqualOp);
  7100. if (NeedVolatile) {
  7101. // volatile restrict version
  7102. ParamTypes[0]
  7103. = S.Context.getLValueReferenceType(
  7104. S.Context.getCVRQualifiedType(*Ptr,
  7105. (Qualifiers::Volatile |
  7106. Qualifiers::Restrict)));
  7107. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7108. /*IsAssigmentOperator=*/isEqualOp);
  7109. }
  7110. }
  7111. }
  7112. if (isEqualOp) {
  7113. for (BuiltinCandidateTypeSet::iterator
  7114. Ptr = CandidateTypes[1].pointer_begin(),
  7115. PtrEnd = CandidateTypes[1].pointer_end();
  7116. Ptr != PtrEnd; ++Ptr) {
  7117. // Make sure we don't add the same candidate twice.
  7118. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7119. continue;
  7120. QualType ParamTypes[2] = {
  7121. S.Context.getLValueReferenceType(*Ptr),
  7122. *Ptr,
  7123. };
  7124. // non-volatile version
  7125. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7126. /*IsAssigmentOperator=*/true);
  7127. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7128. VisibleTypeConversionsQuals.hasVolatile();
  7129. if (NeedVolatile) {
  7130. // volatile version
  7131. ParamTypes[0] =
  7132. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7133. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7134. /*IsAssigmentOperator=*/true);
  7135. }
  7136. if (!(*Ptr).isRestrictQualified() &&
  7137. VisibleTypeConversionsQuals.hasRestrict()) {
  7138. // restrict version
  7139. ParamTypes[0]
  7140. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7141. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7142. /*IsAssigmentOperator=*/true);
  7143. if (NeedVolatile) {
  7144. // volatile restrict version
  7145. ParamTypes[0]
  7146. = S.Context.getLValueReferenceType(
  7147. S.Context.getCVRQualifiedType(*Ptr,
  7148. (Qualifiers::Volatile |
  7149. Qualifiers::Restrict)));
  7150. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7151. /*IsAssigmentOperator=*/true);
  7152. }
  7153. }
  7154. }
  7155. }
  7156. }
  7157. // C++ [over.built]p18:
  7158. //
  7159. // For every triple (L, VQ, R), where L is an arithmetic type,
  7160. // VQ is either volatile or empty, and R is a promoted
  7161. // arithmetic type, there exist candidate operator functions of
  7162. // the form
  7163. //
  7164. // VQ L& operator=(VQ L&, R);
  7165. // VQ L& operator*=(VQ L&, R);
  7166. // VQ L& operator/=(VQ L&, R);
  7167. // VQ L& operator+=(VQ L&, R);
  7168. // VQ L& operator-=(VQ L&, R);
  7169. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7170. if (!HasArithmeticOrEnumeralCandidateType)
  7171. return;
  7172. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7173. for (unsigned Right = FirstPromotedArithmeticType;
  7174. Right < LastPromotedArithmeticType; ++Right) {
  7175. QualType ParamTypes[2];
  7176. ParamTypes[1] = getArithmeticType(Right);
  7177. // Add this built-in operator as a candidate (VQ is empty).
  7178. ParamTypes[0] =
  7179. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7180. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7181. /*IsAssigmentOperator=*/isEqualOp);
  7182. // Add this built-in operator as a candidate (VQ is 'volatile').
  7183. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7184. ParamTypes[0] =
  7185. S.Context.getVolatileType(getArithmeticType(Left));
  7186. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7187. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7188. /*IsAssigmentOperator=*/isEqualOp);
  7189. }
  7190. }
  7191. }
  7192. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7193. for (BuiltinCandidateTypeSet::iterator
  7194. Vec1 = CandidateTypes[0].vector_begin(),
  7195. Vec1End = CandidateTypes[0].vector_end();
  7196. Vec1 != Vec1End; ++Vec1) {
  7197. for (BuiltinCandidateTypeSet::iterator
  7198. Vec2 = CandidateTypes[1].vector_begin(),
  7199. Vec2End = CandidateTypes[1].vector_end();
  7200. Vec2 != Vec2End; ++Vec2) {
  7201. QualType ParamTypes[2];
  7202. ParamTypes[1] = *Vec2;
  7203. // Add this built-in operator as a candidate (VQ is empty).
  7204. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7205. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7206. /*IsAssigmentOperator=*/isEqualOp);
  7207. // Add this built-in operator as a candidate (VQ is 'volatile').
  7208. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7209. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7210. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7211. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7212. /*IsAssigmentOperator=*/isEqualOp);
  7213. }
  7214. }
  7215. }
  7216. }
  7217. // C++ [over.built]p22:
  7218. //
  7219. // For every triple (L, VQ, R), where L is an integral type, VQ
  7220. // is either volatile or empty, and R is a promoted integral
  7221. // type, there exist candidate operator functions of the form
  7222. //
  7223. // VQ L& operator%=(VQ L&, R);
  7224. // VQ L& operator<<=(VQ L&, R);
  7225. // VQ L& operator>>=(VQ L&, R);
  7226. // VQ L& operator&=(VQ L&, R);
  7227. // VQ L& operator^=(VQ L&, R);
  7228. // VQ L& operator|=(VQ L&, R);
  7229. void addAssignmentIntegralOverloads() {
  7230. if (!HasArithmeticOrEnumeralCandidateType)
  7231. return;
  7232. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7233. for (unsigned Right = FirstPromotedIntegralType;
  7234. Right < LastPromotedIntegralType; ++Right) {
  7235. QualType ParamTypes[2];
  7236. ParamTypes[1] = getArithmeticType(Right);
  7237. // Add this built-in operator as a candidate (VQ is empty).
  7238. ParamTypes[0] =
  7239. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7240. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7241. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7242. // Add this built-in operator as a candidate (VQ is 'volatile').
  7243. ParamTypes[0] = getArithmeticType(Left);
  7244. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7245. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7246. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7247. }
  7248. }
  7249. }
  7250. }
  7251. // C++ [over.operator]p23:
  7252. //
  7253. // There also exist candidate operator functions of the form
  7254. //
  7255. // bool operator!(bool);
  7256. // bool operator&&(bool, bool);
  7257. // bool operator||(bool, bool);
  7258. void addExclaimOverload() {
  7259. QualType ParamTy = S.Context.BoolTy;
  7260. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
  7261. /*IsAssignmentOperator=*/false,
  7262. /*NumContextualBoolArguments=*/1);
  7263. }
  7264. void addAmpAmpOrPipePipeOverload() {
  7265. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7266. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
  7267. /*IsAssignmentOperator=*/false,
  7268. /*NumContextualBoolArguments=*/2);
  7269. }
  7270. // C++ [over.built]p13:
  7271. //
  7272. // For every cv-qualified or cv-unqualified object type T there
  7273. // exist candidate operator functions of the form
  7274. //
  7275. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7276. // T& operator[](T*, ptrdiff_t);
  7277. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7278. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7279. // T& operator[](ptrdiff_t, T*);
  7280. void addSubscriptOverloads() {
  7281. for (BuiltinCandidateTypeSet::iterator
  7282. Ptr = CandidateTypes[0].pointer_begin(),
  7283. PtrEnd = CandidateTypes[0].pointer_end();
  7284. Ptr != PtrEnd; ++Ptr) {
  7285. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7286. QualType PointeeType = (*Ptr)->getPointeeType();
  7287. if (!PointeeType->isObjectType())
  7288. continue;
  7289. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7290. // T& operator[](T*, ptrdiff_t)
  7291. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7292. }
  7293. for (BuiltinCandidateTypeSet::iterator
  7294. Ptr = CandidateTypes[1].pointer_begin(),
  7295. PtrEnd = CandidateTypes[1].pointer_end();
  7296. Ptr != PtrEnd; ++Ptr) {
  7297. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7298. QualType PointeeType = (*Ptr)->getPointeeType();
  7299. if (!PointeeType->isObjectType())
  7300. continue;
  7301. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7302. // T& operator[](ptrdiff_t, T*)
  7303. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7304. }
  7305. }
  7306. // C++ [over.built]p11:
  7307. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7308. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7309. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7310. // there exist candidate operator functions of the form
  7311. //
  7312. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7313. //
  7314. // where CV12 is the union of CV1 and CV2.
  7315. void addArrowStarOverloads() {
  7316. for (BuiltinCandidateTypeSet::iterator
  7317. Ptr = CandidateTypes[0].pointer_begin(),
  7318. PtrEnd = CandidateTypes[0].pointer_end();
  7319. Ptr != PtrEnd; ++Ptr) {
  7320. QualType C1Ty = (*Ptr);
  7321. QualType C1;
  7322. QualifierCollector Q1;
  7323. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7324. if (!isa<RecordType>(C1))
  7325. continue;
  7326. // heuristic to reduce number of builtin candidates in the set.
  7327. // Add volatile/restrict version only if there are conversions to a
  7328. // volatile/restrict type.
  7329. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7330. continue;
  7331. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7332. continue;
  7333. for (BuiltinCandidateTypeSet::iterator
  7334. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7335. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7336. MemPtr != MemPtrEnd; ++MemPtr) {
  7337. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7338. QualType C2 = QualType(mptr->getClass(), 0);
  7339. C2 = C2.getUnqualifiedType();
  7340. if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
  7341. break;
  7342. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7343. // build CV12 T&
  7344. QualType T = mptr->getPointeeType();
  7345. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7346. T.isVolatileQualified())
  7347. continue;
  7348. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7349. T.isRestrictQualified())
  7350. continue;
  7351. T = Q1.apply(S.Context, T);
  7352. QualType ResultTy = S.Context.getLValueReferenceType(T);
  7353. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7354. }
  7355. }
  7356. }
  7357. // Note that we don't consider the first argument, since it has been
  7358. // contextually converted to bool long ago. The candidates below are
  7359. // therefore added as binary.
  7360. //
  7361. // C++ [over.built]p25:
  7362. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7363. // enumeration type, there exist candidate operator functions of the form
  7364. //
  7365. // T operator?(bool, T, T);
  7366. //
  7367. void addConditionalOperatorOverloads() {
  7368. /// Set of (canonical) types that we've already handled.
  7369. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7370. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7371. for (BuiltinCandidateTypeSet::iterator
  7372. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7373. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7374. Ptr != PtrEnd; ++Ptr) {
  7375. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7376. continue;
  7377. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7378. S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
  7379. }
  7380. for (BuiltinCandidateTypeSet::iterator
  7381. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7382. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7383. MemPtr != MemPtrEnd; ++MemPtr) {
  7384. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7385. continue;
  7386. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7387. S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
  7388. }
  7389. if (S.getLangOpts().CPlusPlus11) {
  7390. for (BuiltinCandidateTypeSet::iterator
  7391. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7392. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7393. Enum != EnumEnd; ++Enum) {
  7394. if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
  7395. continue;
  7396. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7397. continue;
  7398. QualType ParamTypes[2] = { *Enum, *Enum };
  7399. S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
  7400. }
  7401. }
  7402. }
  7403. }
  7404. };
  7405. } // end anonymous namespace
  7406. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  7407. /// operator overloads to the candidate set (C++ [over.built]), based
  7408. /// on the operator @p Op and the arguments given. For example, if the
  7409. /// operator is a binary '+', this routine might add "int
  7410. /// operator+(int, int)" to cover integer addition.
  7411. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  7412. SourceLocation OpLoc,
  7413. ArrayRef<Expr *> Args,
  7414. OverloadCandidateSet &CandidateSet) {
  7415. // Find all of the types that the arguments can convert to, but only
  7416. // if the operator we're looking at has built-in operator candidates
  7417. // that make use of these types. Also record whether we encounter non-record
  7418. // candidate types or either arithmetic or enumeral candidate types.
  7419. Qualifiers VisibleTypeConversionsQuals;
  7420. VisibleTypeConversionsQuals.addConst();
  7421. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  7422. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  7423. bool HasNonRecordCandidateType = false;
  7424. bool HasArithmeticOrEnumeralCandidateType = false;
  7425. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  7426. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7427. CandidateTypes.emplace_back(*this);
  7428. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  7429. OpLoc,
  7430. true,
  7431. (Op == OO_Exclaim ||
  7432. Op == OO_AmpAmp ||
  7433. Op == OO_PipePipe),
  7434. VisibleTypeConversionsQuals);
  7435. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  7436. CandidateTypes[ArgIdx].hasNonRecordTypes();
  7437. HasArithmeticOrEnumeralCandidateType =
  7438. HasArithmeticOrEnumeralCandidateType ||
  7439. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  7440. }
  7441. // Exit early when no non-record types have been added to the candidate set
  7442. // for any of the arguments to the operator.
  7443. //
  7444. // We can't exit early for !, ||, or &&, since there we have always have
  7445. // 'bool' overloads.
  7446. if (!HasNonRecordCandidateType &&
  7447. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  7448. return;
  7449. // Setup an object to manage the common state for building overloads.
  7450. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  7451. VisibleTypeConversionsQuals,
  7452. HasArithmeticOrEnumeralCandidateType,
  7453. CandidateTypes, CandidateSet);
  7454. // Dispatch over the operation to add in only those overloads which apply.
  7455. switch (Op) {
  7456. case OO_None:
  7457. case NUM_OVERLOADED_OPERATORS:
  7458. llvm_unreachable("Expected an overloaded operator");
  7459. case OO_New:
  7460. case OO_Delete:
  7461. case OO_Array_New:
  7462. case OO_Array_Delete:
  7463. case OO_Call:
  7464. llvm_unreachable(
  7465. "Special operators don't use AddBuiltinOperatorCandidates");
  7466. case OO_Comma:
  7467. case OO_Arrow:
  7468. // C++ [over.match.oper]p3:
  7469. // -- For the operator ',', the unary operator '&', or the
  7470. // operator '->', the built-in candidates set is empty.
  7471. break;
  7472. case OO_Plus: // '+' is either unary or binary
  7473. if (Args.size() == 1)
  7474. OpBuilder.addUnaryPlusPointerOverloads();
  7475. // Fall through.
  7476. case OO_Minus: // '-' is either unary or binary
  7477. if (Args.size() == 1) {
  7478. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  7479. } else {
  7480. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  7481. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7482. }
  7483. break;
  7484. case OO_Star: // '*' is either unary or binary
  7485. if (Args.size() == 1)
  7486. OpBuilder.addUnaryStarPointerOverloads();
  7487. else
  7488. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7489. break;
  7490. case OO_Slash:
  7491. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7492. break;
  7493. case OO_PlusPlus:
  7494. case OO_MinusMinus:
  7495. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  7496. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  7497. break;
  7498. case OO_EqualEqual:
  7499. case OO_ExclaimEqual:
  7500. OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
  7501. // Fall through.
  7502. case OO_Less:
  7503. case OO_Greater:
  7504. case OO_LessEqual:
  7505. case OO_GreaterEqual:
  7506. OpBuilder.addRelationalPointerOrEnumeralOverloads();
  7507. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
  7508. break;
  7509. case OO_Percent:
  7510. case OO_Caret:
  7511. case OO_Pipe:
  7512. case OO_LessLess:
  7513. case OO_GreaterGreater:
  7514. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7515. break;
  7516. case OO_Amp: // '&' is either unary or binary
  7517. if (Args.size() == 1)
  7518. // C++ [over.match.oper]p3:
  7519. // -- For the operator ',', the unary operator '&', or the
  7520. // operator '->', the built-in candidates set is empty.
  7521. break;
  7522. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7523. break;
  7524. case OO_Tilde:
  7525. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  7526. break;
  7527. case OO_Equal:
  7528. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  7529. // Fall through.
  7530. case OO_PlusEqual:
  7531. case OO_MinusEqual:
  7532. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  7533. // Fall through.
  7534. case OO_StarEqual:
  7535. case OO_SlashEqual:
  7536. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  7537. break;
  7538. case OO_PercentEqual:
  7539. case OO_LessLessEqual:
  7540. case OO_GreaterGreaterEqual:
  7541. case OO_AmpEqual:
  7542. case OO_CaretEqual:
  7543. case OO_PipeEqual:
  7544. OpBuilder.addAssignmentIntegralOverloads();
  7545. break;
  7546. case OO_Exclaim:
  7547. OpBuilder.addExclaimOverload();
  7548. break;
  7549. case OO_AmpAmp:
  7550. case OO_PipePipe:
  7551. OpBuilder.addAmpAmpOrPipePipeOverload();
  7552. break;
  7553. case OO_Subscript:
  7554. OpBuilder.addSubscriptOverloads();
  7555. break;
  7556. case OO_ArrowStar:
  7557. OpBuilder.addArrowStarOverloads();
  7558. break;
  7559. case OO_Conditional:
  7560. OpBuilder.addConditionalOperatorOverloads();
  7561. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7562. break;
  7563. }
  7564. }
  7565. /// \brief Add function candidates found via argument-dependent lookup
  7566. /// to the set of overloading candidates.
  7567. ///
  7568. /// This routine performs argument-dependent name lookup based on the
  7569. /// given function name (which may also be an operator name) and adds
  7570. /// all of the overload candidates found by ADL to the overload
  7571. /// candidate set (C++ [basic.lookup.argdep]).
  7572. void
  7573. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  7574. SourceLocation Loc,
  7575. ArrayRef<Expr *> Args,
  7576. TemplateArgumentListInfo *ExplicitTemplateArgs,
  7577. OverloadCandidateSet& CandidateSet,
  7578. bool PartialOverloading) {
  7579. ADLResult Fns;
  7580. // FIXME: This approach for uniquing ADL results (and removing
  7581. // redundant candidates from the set) relies on pointer-equality,
  7582. // which means we need to key off the canonical decl. However,
  7583. // always going back to the canonical decl might not get us the
  7584. // right set of default arguments. What default arguments are
  7585. // we supposed to consider on ADL candidates, anyway?
  7586. // FIXME: Pass in the explicit template arguments?
  7587. ArgumentDependentLookup(Name, Loc, Args, Fns);
  7588. // Erase all of the candidates we already knew about.
  7589. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  7590. CandEnd = CandidateSet.end();
  7591. Cand != CandEnd; ++Cand)
  7592. if (Cand->Function) {
  7593. Fns.erase(Cand->Function);
  7594. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  7595. Fns.erase(FunTmpl);
  7596. }
  7597. // For each of the ADL candidates we found, add it to the overload
  7598. // set.
  7599. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  7600. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  7601. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  7602. if (ExplicitTemplateArgs)
  7603. continue;
  7604. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
  7605. PartialOverloading);
  7606. } else
  7607. AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
  7608. FoundDecl, ExplicitTemplateArgs,
  7609. Args, CandidateSet, PartialOverloading);
  7610. }
  7611. }
  7612. /// isBetterOverloadCandidate - Determines whether the first overload
  7613. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  7614. bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
  7615. const OverloadCandidate &Cand2,
  7616. SourceLocation Loc,
  7617. bool UserDefinedConversion) {
  7618. // Define viable functions to be better candidates than non-viable
  7619. // functions.
  7620. if (!Cand2.Viable)
  7621. return Cand1.Viable;
  7622. else if (!Cand1.Viable)
  7623. return false;
  7624. // C++ [over.match.best]p1:
  7625. //
  7626. // -- if F is a static member function, ICS1(F) is defined such
  7627. // that ICS1(F) is neither better nor worse than ICS1(G) for
  7628. // any function G, and, symmetrically, ICS1(G) is neither
  7629. // better nor worse than ICS1(F).
  7630. unsigned StartArg = 0;
  7631. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  7632. StartArg = 1;
  7633. // C++ [over.match.best]p1:
  7634. // A viable function F1 is defined to be a better function than another
  7635. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  7636. // conversion sequence than ICSi(F2), and then...
  7637. unsigned NumArgs = Cand1.NumConversions;
  7638. assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
  7639. bool HasBetterConversion = false;
  7640. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  7641. switch (CompareImplicitConversionSequences(S,
  7642. Cand1.Conversions[ArgIdx],
  7643. Cand2.Conversions[ArgIdx])) {
  7644. case ImplicitConversionSequence::Better:
  7645. // Cand1 has a better conversion sequence.
  7646. HasBetterConversion = true;
  7647. break;
  7648. case ImplicitConversionSequence::Worse:
  7649. // Cand1 can't be better than Cand2.
  7650. return false;
  7651. case ImplicitConversionSequence::Indistinguishable:
  7652. // Do nothing.
  7653. break;
  7654. }
  7655. }
  7656. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  7657. // ICSj(F2), or, if not that,
  7658. if (HasBetterConversion)
  7659. return true;
  7660. // -- the context is an initialization by user-defined conversion
  7661. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  7662. // from the return type of F1 to the destination type (i.e.,
  7663. // the type of the entity being initialized) is a better
  7664. // conversion sequence than the standard conversion sequence
  7665. // from the return type of F2 to the destination type.
  7666. if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
  7667. isa<CXXConversionDecl>(Cand1.Function) &&
  7668. isa<CXXConversionDecl>(Cand2.Function)) {
  7669. // First check whether we prefer one of the conversion functions over the
  7670. // other. This only distinguishes the results in non-standard, extension
  7671. // cases such as the conversion from a lambda closure type to a function
  7672. // pointer or block.
  7673. ImplicitConversionSequence::CompareKind Result =
  7674. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  7675. if (Result == ImplicitConversionSequence::Indistinguishable)
  7676. Result = CompareStandardConversionSequences(S,
  7677. Cand1.FinalConversion,
  7678. Cand2.FinalConversion);
  7679. if (Result != ImplicitConversionSequence::Indistinguishable)
  7680. return Result == ImplicitConversionSequence::Better;
  7681. // FIXME: Compare kind of reference binding if conversion functions
  7682. // convert to a reference type used in direct reference binding, per
  7683. // C++14 [over.match.best]p1 section 2 bullet 3.
  7684. }
  7685. // -- F1 is a non-template function and F2 is a function template
  7686. // specialization, or, if not that,
  7687. bool Cand1IsSpecialization = Cand1.Function &&
  7688. Cand1.Function->getPrimaryTemplate();
  7689. bool Cand2IsSpecialization = Cand2.Function &&
  7690. Cand2.Function->getPrimaryTemplate();
  7691. if (Cand1IsSpecialization != Cand2IsSpecialization)
  7692. return Cand2IsSpecialization;
  7693. // -- F1 and F2 are function template specializations, and the function
  7694. // template for F1 is more specialized than the template for F2
  7695. // according to the partial ordering rules described in 14.5.5.2, or,
  7696. // if not that,
  7697. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  7698. if (FunctionTemplateDecl *BetterTemplate
  7699. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  7700. Cand2.Function->getPrimaryTemplate(),
  7701. Loc,
  7702. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  7703. : TPOC_Call,
  7704. Cand1.ExplicitCallArguments,
  7705. Cand2.ExplicitCallArguments))
  7706. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  7707. }
  7708. // Check for enable_if value-based overload resolution.
  7709. if (Cand1.Function && Cand2.Function &&
  7710. (Cand1.Function->hasAttr<EnableIfAttr>() ||
  7711. Cand2.Function->hasAttr<EnableIfAttr>())) {
  7712. // FIXME: The next several lines are just
  7713. // specific_attr_iterator<EnableIfAttr> but going in declaration order,
  7714. // instead of reverse order which is how they're stored in the AST.
  7715. AttrVec Cand1Attrs;
  7716. if (Cand1.Function->hasAttrs()) {
  7717. Cand1Attrs = Cand1.Function->getAttrs();
  7718. Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
  7719. IsNotEnableIfAttr),
  7720. Cand1Attrs.end());
  7721. std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
  7722. }
  7723. AttrVec Cand2Attrs;
  7724. if (Cand2.Function->hasAttrs()) {
  7725. Cand2Attrs = Cand2.Function->getAttrs();
  7726. Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
  7727. IsNotEnableIfAttr),
  7728. Cand2Attrs.end());
  7729. std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
  7730. }
  7731. // Candidate 1 is better if it has strictly more attributes and
  7732. // the common sequence is identical.
  7733. if (Cand1Attrs.size() <= Cand2Attrs.size())
  7734. return false;
  7735. auto Cand1I = Cand1Attrs.begin();
  7736. for (auto &Cand2A : Cand2Attrs) {
  7737. auto &Cand1A = *Cand1I++;
  7738. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  7739. cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
  7740. S.getASTContext(), true);
  7741. cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
  7742. S.getASTContext(), true);
  7743. if (Cand1ID != Cand2ID)
  7744. return false;
  7745. }
  7746. return true;
  7747. }
  7748. return false;
  7749. }
  7750. /// \brief Computes the best viable function (C++ 13.3.3)
  7751. /// within an overload candidate set.
  7752. ///
  7753. /// \param Loc The location of the function name (or operator symbol) for
  7754. /// which overload resolution occurs.
  7755. ///
  7756. /// \param Best If overload resolution was successful or found a deleted
  7757. /// function, \p Best points to the candidate function found.
  7758. ///
  7759. /// \returns The result of overload resolution.
  7760. OverloadingResult
  7761. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  7762. iterator &Best,
  7763. bool UserDefinedConversion) {
  7764. // HLSL Change Starts
  7765. // Function calls should use HLSL-style overloading. operator[] overloads
  7766. // (used for const support) aren't supported by the defined rules, so
  7767. // use C++ overload resolution for those.
  7768. if (S.getLangOpts().HLSL && !empty() && begin()->Function != nullptr &&
  7769. (begin()->Function->getDeclName() !=
  7770. S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  7771. return ::hlsl::GetBestViableFunction(S, Loc, *this, Best);
  7772. }
  7773. // HLSL Change Ends
  7774. // Find the best viable function.
  7775. Best = end();
  7776. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7777. if (Cand->Viable)
  7778. if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
  7779. UserDefinedConversion))
  7780. Best = Cand;
  7781. }
  7782. // If we didn't find any viable functions, abort.
  7783. if (Best == end())
  7784. return OR_No_Viable_Function;
  7785. // Make sure that this function is better than every other viable
  7786. // function. If not, we have an ambiguity.
  7787. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7788. if (Cand->Viable &&
  7789. Cand != Best &&
  7790. !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
  7791. UserDefinedConversion)) {
  7792. Best = end();
  7793. return OR_Ambiguous;
  7794. }
  7795. }
  7796. // Best is the best viable function.
  7797. if (Best->Function &&
  7798. (Best->Function->isDeleted() ||
  7799. S.isFunctionConsideredUnavailable(Best->Function)))
  7800. return OR_Deleted;
  7801. return OR_Success;
  7802. }
  7803. namespace {
  7804. enum OverloadCandidateKind {
  7805. oc_function,
  7806. oc_method,
  7807. oc_constructor,
  7808. oc_function_template,
  7809. oc_method_template,
  7810. oc_constructor_template,
  7811. oc_implicit_default_constructor,
  7812. oc_implicit_copy_constructor,
  7813. oc_implicit_move_constructor,
  7814. oc_implicit_copy_assignment,
  7815. oc_implicit_move_assignment,
  7816. oc_implicit_inherited_constructor
  7817. };
  7818. OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
  7819. FunctionDecl *Fn,
  7820. std::string &Description) {
  7821. bool isTemplate = false;
  7822. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  7823. isTemplate = true;
  7824. Description = S.getTemplateArgumentBindingsText(
  7825. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  7826. }
  7827. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7828. if (!Ctor->isImplicit())
  7829. return isTemplate ? oc_constructor_template : oc_constructor;
  7830. if (Ctor->getInheritedConstructor())
  7831. return oc_implicit_inherited_constructor;
  7832. if (Ctor->isDefaultConstructor())
  7833. return oc_implicit_default_constructor;
  7834. if (Ctor->isMoveConstructor())
  7835. return oc_implicit_move_constructor;
  7836. assert(Ctor->isCopyConstructor() &&
  7837. "unexpected sort of implicit constructor");
  7838. return oc_implicit_copy_constructor;
  7839. }
  7840. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  7841. if (S.getLangOpts().HLSL) return isTemplate ? oc_method_template : oc_method; // HLSL Change - all intrinsics are implicit, doesn't imply conversion
  7842. // This actually gets spelled 'candidate function' for now, but
  7843. // it doesn't hurt to split it out.
  7844. if (!Meth->isImplicit())
  7845. return isTemplate ? oc_method_template : oc_method;
  7846. if (Meth->isMoveAssignmentOperator())
  7847. return oc_implicit_move_assignment;
  7848. if (Meth->isCopyAssignmentOperator())
  7849. return oc_implicit_copy_assignment;
  7850. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  7851. return oc_method;
  7852. }
  7853. return isTemplate ? oc_function_template : oc_function;
  7854. }
  7855. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
  7856. const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
  7857. if (!Ctor) return;
  7858. Ctor = Ctor->getInheritedConstructor();
  7859. if (!Ctor) return;
  7860. S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
  7861. }
  7862. } // end anonymous namespace
  7863. // Notes the location of an overload candidate.
  7864. void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
  7865. std::string FnDesc;
  7866. OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
  7867. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  7868. << (unsigned) K << FnDesc;
  7869. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  7870. Diag(Fn->getLocation(), PD);
  7871. MaybeEmitInheritedConstructorNote(*this, Fn);
  7872. }
  7873. // Notes the location of all overload candidates designated through
  7874. // OverloadedExpr
  7875. void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
  7876. assert(OverloadedExpr->getType() == Context.OverloadTy);
  7877. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  7878. OverloadExpr *OvlExpr = Ovl.Expression;
  7879. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  7880. IEnd = OvlExpr->decls_end();
  7881. I != IEnd; ++I) {
  7882. if (FunctionTemplateDecl *FunTmpl =
  7883. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  7884. NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
  7885. } else if (FunctionDecl *Fun
  7886. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  7887. NoteOverloadCandidate(Fun, DestType);
  7888. }
  7889. }
  7890. }
  7891. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  7892. /// "lead" diagnostic; it will be given two arguments, the source and
  7893. /// target types of the conversion.
  7894. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  7895. Sema &S,
  7896. SourceLocation CaretLoc,
  7897. const PartialDiagnostic &PDiag) const {
  7898. S.Diag(CaretLoc, PDiag)
  7899. << Ambiguous.getFromType() << Ambiguous.getToType();
  7900. // FIXME: The note limiting machinery is borrowed from
  7901. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  7902. // refactoring here.
  7903. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  7904. unsigned CandsShown = 0;
  7905. AmbiguousConversionSequence::const_iterator I, E;
  7906. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  7907. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  7908. break;
  7909. ++CandsShown;
  7910. S.NoteOverloadCandidate(*I);
  7911. }
  7912. if (I != E)
  7913. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  7914. }
  7915. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  7916. unsigned I, const ImplicitConversionSequence &Conv, SourceLocation OpLoc) { // HLSL Change: add OpLoc and Conv
  7917. // const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  7918. assert(Conv.isBad());
  7919. assert(Cand->Function && "for now, candidate must be a function");
  7920. FunctionDecl *Fn = Cand->Function;
  7921. // There's a conversion slot for the object argument if this is a
  7922. // non-constructor method. Note that 'I' corresponds the
  7923. // conversion-slot index.
  7924. bool isObjectArgument = false;
  7925. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  7926. if (I == 0)
  7927. isObjectArgument = true;
  7928. else
  7929. I--;
  7930. }
  7931. std::string FnDesc;
  7932. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  7933. Expr *FromExpr = Conv.Bad.FromExpr;
  7934. QualType FromTy = Conv.Bad.getFromType();
  7935. QualType ToTy = Conv.Bad.getToType();
  7936. // HLSL Change: replace Fn->getLocation() in diagnostics with FnDiagLocation
  7937. // and avoid notes that try to point to built-in targets
  7938. SourceLocation FnDiagLocation = Fn->getLocation().isValid() ? Fn->getLocation() : OpLoc;
  7939. if (FromTy == S.Context.OverloadTy) {
  7940. assert(FromExpr && "overload set argument came from implicit argument?");
  7941. Expr *E = FromExpr->IgnoreParens();
  7942. if (isa<UnaryOperator>(E))
  7943. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  7944. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  7945. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_overload) // HLSL Change - FnDiagLocation
  7946. << (unsigned) FnKind << FnDesc
  7947. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7948. << ToTy << Name << I+1;
  7949. MaybeEmitInheritedConstructorNote(S, Fn);
  7950. return;
  7951. }
  7952. // Do some hand-waving analysis to see if the non-viability is due
  7953. // to a qualifier mismatch.
  7954. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  7955. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  7956. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  7957. CToTy = RT->getPointeeType();
  7958. else {
  7959. // TODO: detect and diagnose the full richness of const mismatches.
  7960. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  7961. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
  7962. CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
  7963. }
  7964. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  7965. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  7966. Qualifiers FromQs = CFromTy.getQualifiers();
  7967. Qualifiers ToQs = CToTy.getQualifiers();
  7968. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  7969. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_addrspace)
  7970. << (unsigned) FnKind << FnDesc
  7971. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7972. << FromTy
  7973. << FromQs.getAddressSpace() << ToQs.getAddressSpace()
  7974. << (unsigned) isObjectArgument << I+1;
  7975. MaybeEmitInheritedConstructorNote(S, Fn);
  7976. return;
  7977. }
  7978. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  7979. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_ownership)
  7980. << (unsigned) FnKind << FnDesc
  7981. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7982. << FromTy
  7983. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  7984. << (unsigned) isObjectArgument << I+1;
  7985. MaybeEmitInheritedConstructorNote(S, Fn);
  7986. return;
  7987. }
  7988. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  7989. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_gc)
  7990. << (unsigned) FnKind << FnDesc
  7991. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7992. << FromTy
  7993. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  7994. << (unsigned) isObjectArgument << I+1;
  7995. MaybeEmitInheritedConstructorNote(S, Fn);
  7996. return;
  7997. }
  7998. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  7999. assert(CVR && "unexpected qualifiers mismatch");
  8000. if (isObjectArgument) {
  8001. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr_this)
  8002. << (unsigned) FnKind << FnDesc
  8003. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8004. << FromTy << (CVR - 1);
  8005. } else {
  8006. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr)
  8007. << (unsigned) FnKind << FnDesc
  8008. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8009. << FromTy << (CVR - 1) << I+1;
  8010. }
  8011. MaybeEmitInheritedConstructorNote(S, Fn);
  8012. return;
  8013. }
  8014. // Special diagnostic for failure to convert an initializer list, since
  8015. // telling the user that it has type void is not useful.
  8016. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8017. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_list_argument)
  8018. << (unsigned) FnKind << FnDesc
  8019. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8020. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8021. MaybeEmitInheritedConstructorNote(S, Fn);
  8022. return;
  8023. }
  8024. // Diagnose references or pointers to incomplete types differently,
  8025. // since it's far from impossible that the incompleteness triggered
  8026. // the failure.
  8027. QualType TempFromTy = FromTy.getNonReferenceType();
  8028. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8029. TempFromTy = PTy->getPointeeType();
  8030. if (TempFromTy->isIncompleteType()) {
  8031. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_conv_incomplete)
  8032. << (unsigned) FnKind << FnDesc
  8033. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8034. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8035. MaybeEmitInheritedConstructorNote(S, Fn);
  8036. return;
  8037. }
  8038. // Diagnose base -> derived pointer conversions.
  8039. unsigned BaseToDerivedConversion = 0;
  8040. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8041. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8042. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8043. FromPtrTy->getPointeeType()) &&
  8044. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8045. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8046. S.IsDerivedFrom(ToPtrTy->getPointeeType(),
  8047. FromPtrTy->getPointeeType()))
  8048. BaseToDerivedConversion = 1;
  8049. }
  8050. } else if (const ObjCObjectPointerType *FromPtrTy
  8051. = FromTy->getAs<ObjCObjectPointerType>()) {
  8052. if (const ObjCObjectPointerType *ToPtrTy
  8053. = ToTy->getAs<ObjCObjectPointerType>())
  8054. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8055. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8056. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8057. FromPtrTy->getPointeeType()) &&
  8058. FromIface->isSuperClassOf(ToIface))
  8059. BaseToDerivedConversion = 2;
  8060. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  8061. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  8062. !FromTy->isIncompleteType() &&
  8063. !ToRefTy->getPointeeType()->isIncompleteType() &&
  8064. S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
  8065. BaseToDerivedConversion = 3;
  8066. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  8067. ToTy.getNonReferenceType().getCanonicalType() ==
  8068. FromTy.getNonReferenceType().getCanonicalType()) {
  8069. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_lvalue)
  8070. << (unsigned) FnKind << FnDesc
  8071. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8072. << (unsigned) isObjectArgument << I + 1;
  8073. MaybeEmitInheritedConstructorNote(S, Fn);
  8074. return;
  8075. }
  8076. }
  8077. if (BaseToDerivedConversion) {
  8078. S.Diag(FnDiagLocation,
  8079. diag::note_ovl_candidate_bad_base_to_derived_conv)
  8080. << (unsigned) FnKind << FnDesc
  8081. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8082. << (BaseToDerivedConversion - 1)
  8083. << FromTy << ToTy << I+1;
  8084. MaybeEmitInheritedConstructorNote(S, Fn);
  8085. return;
  8086. }
  8087. if (isa<ObjCObjectPointerType>(CFromTy) &&
  8088. isa<PointerType>(CToTy)) {
  8089. Qualifiers FromQs = CFromTy.getQualifiers();
  8090. Qualifiers ToQs = CToTy.getQualifiers();
  8091. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8092. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_arc_conv)
  8093. << (unsigned) FnKind << FnDesc
  8094. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8095. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8096. MaybeEmitInheritedConstructorNote(S, Fn);
  8097. return;
  8098. }
  8099. }
  8100. // Emit the generic diagnostic and, optionally, add the hints to it.
  8101. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  8102. FDiag << (unsigned) FnKind << FnDesc
  8103. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8104. << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
  8105. << (unsigned) (Cand->Fix.Kind);
  8106. // If we can fix the conversion, suggest the FixIts.
  8107. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  8108. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  8109. FDiag << *HI;
  8110. S.Diag(FnDiagLocation, FDiag);
  8111. MaybeEmitInheritedConstructorNote(S, Fn);
  8112. }
  8113. /// Additional arity mismatch diagnosis specific to a function overload
  8114. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  8115. /// over a candidate in any candidate set.
  8116. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  8117. unsigned NumArgs) {
  8118. FunctionDecl *Fn = Cand->Function;
  8119. unsigned MinParams = Fn->getMinRequiredArguments();
  8120. // With invalid overloaded operators, it's possible that we think we
  8121. // have an arity mismatch when in fact it looks like we have the
  8122. // right number of arguments, because only overloaded operators have
  8123. // the weird behavior of overloading member and non-member functions.
  8124. // Just don't report anything.
  8125. if (Fn->isInvalidDecl() &&
  8126. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  8127. return true;
  8128. if (NumArgs < MinParams) {
  8129. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  8130. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8131. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  8132. } else {
  8133. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  8134. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8135. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  8136. }
  8137. return false;
  8138. }
  8139. /// General arity mismatch diagnosis over a candidate in a candidate set.
  8140. static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8141. assert(isa<FunctionDecl>(D) &&
  8142. "The templated declaration should at least be a function"
  8143. " when diagnosing bad template argument deduction due to too many"
  8144. " or too few arguments");
  8145. FunctionDecl *Fn = cast<FunctionDecl>(D);
  8146. // TODO: treat calls to a missing default constructor as a special case
  8147. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  8148. unsigned MinParams = Fn->getMinRequiredArguments();
  8149. // at least / at most / exactly
  8150. unsigned mode, modeCount;
  8151. if (NumFormalArgs < MinParams) {
  8152. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  8153. FnTy->isTemplateVariadic())
  8154. mode = 0; // "at least"
  8155. else
  8156. mode = 2; // "exactly"
  8157. modeCount = MinParams;
  8158. } else {
  8159. if (MinParams != FnTy->getNumParams())
  8160. mode = 1; // "at most"
  8161. else
  8162. mode = 2; // "exactly"
  8163. modeCount = FnTy->getNumParams();
  8164. }
  8165. std::string Description;
  8166. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
  8167. // HLSL Change Starts - fallback for built-ins
  8168. SourceLocation DiagLoc = Fn->getLocation();
  8169. if (DiagLoc.isInvalid()) DiagLoc = OpLoc;
  8170. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  8171. S.Diag(DiagLoc, diag::note_ovl_candidate_arity_one)
  8172. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8173. << mode << Fn->getParamDecl(0) << NumFormalArgs;
  8174. else
  8175. S.Diag(DiagLoc, diag::note_ovl_candidate_arity)
  8176. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8177. << mode << modeCount << NumFormalArgs;
  8178. // HLSL Change Ends
  8179. MaybeEmitInheritedConstructorNote(S, Fn);
  8180. }
  8181. /// Arity mismatch diagnosis specific to a function overload candidate.
  8182. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  8183. unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8184. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  8185. DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs, OpLoc);
  8186. }
  8187. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  8188. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
  8189. return FD->getDescribedFunctionTemplate();
  8190. else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
  8191. return RD->getDescribedClassTemplate();
  8192. llvm_unreachable("Unsupported: Getting the described template declaration"
  8193. " for bad deduction diagnosis");
  8194. }
  8195. /// Diagnose a failed template-argument deduction.
  8196. static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
  8197. DeductionFailureInfo &DeductionFailure,
  8198. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8199. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  8200. NamedDecl *ParamD;
  8201. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  8202. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  8203. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  8204. switch (DeductionFailure.Result) {
  8205. case Sema::TDK_Success:
  8206. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8207. case Sema::TDK_Incomplete: {
  8208. assert(ParamD && "no parameter found for incomplete deduction result");
  8209. S.Diag(Templated->getLocation(),
  8210. diag::note_ovl_candidate_incomplete_deduction)
  8211. << ParamD->getDeclName();
  8212. MaybeEmitInheritedConstructorNote(S, Templated);
  8213. return;
  8214. }
  8215. case Sema::TDK_Underqualified: {
  8216. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  8217. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  8218. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  8219. // Param will have been canonicalized, but it should just be a
  8220. // qualified version of ParamD, so move the qualifiers to that.
  8221. QualifierCollector Qs;
  8222. Qs.strip(Param);
  8223. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  8224. assert(S.Context.hasSameType(Param, NonCanonParam));
  8225. // Arg has also been canonicalized, but there's nothing we can do
  8226. // about that. It also doesn't matter as much, because it won't
  8227. // have any template parameters in it (because deduction isn't
  8228. // done on dependent types).
  8229. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  8230. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  8231. << ParamD->getDeclName() << Arg << NonCanonParam;
  8232. MaybeEmitInheritedConstructorNote(S, Templated);
  8233. return;
  8234. }
  8235. case Sema::TDK_Inconsistent: {
  8236. assert(ParamD && "no parameter found for inconsistent deduction result");
  8237. int which = 0;
  8238. if (isa<TemplateTypeParmDecl>(ParamD))
  8239. which = 0;
  8240. else if (isa<NonTypeTemplateParmDecl>(ParamD))
  8241. which = 1;
  8242. else {
  8243. which = 2;
  8244. }
  8245. S.Diag(Templated->getLocation(),
  8246. diag::note_ovl_candidate_inconsistent_deduction)
  8247. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  8248. << *DeductionFailure.getSecondArg();
  8249. MaybeEmitInheritedConstructorNote(S, Templated);
  8250. return;
  8251. }
  8252. case Sema::TDK_InvalidExplicitArguments:
  8253. assert(ParamD && "no parameter found for invalid explicit arguments");
  8254. if (ParamD->getDeclName())
  8255. S.Diag(Templated->getLocation(),
  8256. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  8257. << ParamD->getDeclName();
  8258. else {
  8259. int index = 0;
  8260. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  8261. index = TTP->getIndex();
  8262. else if (NonTypeTemplateParmDecl *NTTP
  8263. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  8264. index = NTTP->getIndex();
  8265. else
  8266. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  8267. S.Diag(Templated->getLocation(),
  8268. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  8269. << (index + 1);
  8270. }
  8271. MaybeEmitInheritedConstructorNote(S, Templated);
  8272. return;
  8273. case Sema::TDK_TooManyArguments:
  8274. case Sema::TDK_TooFewArguments:
  8275. DiagnoseArityMismatch(S, Templated, NumArgs, OpLoc);
  8276. return;
  8277. case Sema::TDK_InstantiationDepth:
  8278. S.Diag(Templated->getLocation(),
  8279. diag::note_ovl_candidate_instantiation_depth);
  8280. MaybeEmitInheritedConstructorNote(S, Templated);
  8281. return;
  8282. case Sema::TDK_SubstitutionFailure: {
  8283. // Format the template argument list into the argument string.
  8284. SmallString<128> TemplateArgString;
  8285. if (TemplateArgumentList *Args =
  8286. DeductionFailure.getTemplateArgumentList()) {
  8287. TemplateArgString = " ";
  8288. TemplateArgString += S.getTemplateArgumentBindingsText(
  8289. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  8290. }
  8291. // If this candidate was disabled by enable_if, say so.
  8292. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  8293. if (PDiag && PDiag->second.getDiagID() ==
  8294. diag::err_typename_nested_not_found_enable_if) {
  8295. // FIXME: Use the source range of the condition, and the fully-qualified
  8296. // name of the enable_if template. These are both present in PDiag.
  8297. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  8298. << "'enable_if'" << TemplateArgString;
  8299. return;
  8300. }
  8301. // Format the SFINAE diagnostic into the argument string.
  8302. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  8303. // formatted message in another diagnostic.
  8304. SmallString<128> SFINAEArgString;
  8305. SourceRange R;
  8306. if (PDiag) {
  8307. SFINAEArgString = ": ";
  8308. R = SourceRange(PDiag->first, PDiag->first);
  8309. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  8310. }
  8311. S.Diag(Templated->getLocation(),
  8312. diag::note_ovl_candidate_substitution_failure)
  8313. << TemplateArgString << SFINAEArgString << R;
  8314. MaybeEmitInheritedConstructorNote(S, Templated);
  8315. return;
  8316. }
  8317. case Sema::TDK_FailedOverloadResolution: {
  8318. OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
  8319. S.Diag(Templated->getLocation(),
  8320. diag::note_ovl_candidate_failed_overload_resolution)
  8321. << R.Expression->getName();
  8322. return;
  8323. }
  8324. case Sema::TDK_NonDeducedMismatch: {
  8325. // FIXME: Provide a source location to indicate what we couldn't match.
  8326. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  8327. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  8328. if (FirstTA.getKind() == TemplateArgument::Template &&
  8329. SecondTA.getKind() == TemplateArgument::Template) {
  8330. TemplateName FirstTN = FirstTA.getAsTemplate();
  8331. TemplateName SecondTN = SecondTA.getAsTemplate();
  8332. if (FirstTN.getKind() == TemplateName::Template &&
  8333. SecondTN.getKind() == TemplateName::Template) {
  8334. if (FirstTN.getAsTemplateDecl()->getName() ==
  8335. SecondTN.getAsTemplateDecl()->getName()) {
  8336. // FIXME: This fixes a bad diagnostic where both templates are named
  8337. // the same. This particular case is a bit difficult since:
  8338. // 1) It is passed as a string to the diagnostic printer.
  8339. // 2) The diagnostic printer only attempts to find a better
  8340. // name for types, not decls.
  8341. // Ideally, this should folded into the diagnostic printer.
  8342. S.Diag(Templated->getLocation(),
  8343. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  8344. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  8345. return;
  8346. }
  8347. }
  8348. }
  8349. // HLSL Change Starts
  8350. // The implementation for template argument deducation does not yet provide
  8351. // FirstArg and SecondArg information for failure cases; ellide the note in
  8352. // this case.
  8353. if (FirstTA.isNull() || SecondTA.isNull()) return;
  8354. // HLSL Change Ends
  8355. // FIXME: For generic lambda parameters, check if the function is a lambda
  8356. // call operator, and if so, emit a prettier and more informative
  8357. // diagnostic that mentions 'auto' and lambda in addition to
  8358. // (or instead of?) the canonical template type parameters.
  8359. S.Diag(Templated->getLocation(),
  8360. diag::note_ovl_candidate_non_deduced_mismatch)
  8361. << FirstTA << SecondTA;
  8362. return;
  8363. }
  8364. // TODO: diagnose these individually, then kill off
  8365. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  8366. case Sema::TDK_MiscellaneousDeductionFailure:
  8367. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  8368. MaybeEmitInheritedConstructorNote(S, Templated);
  8369. return;
  8370. }
  8371. }
  8372. /// Diagnose a failed template-argument deduction, for function calls.
  8373. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  8374. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8375. unsigned TDK = Cand->DeductionFailure.Result;
  8376. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  8377. if (CheckArityMismatch(S, Cand, NumArgs))
  8378. return;
  8379. }
  8380. DiagnoseBadDeduction(S, Cand->Function, // pattern
  8381. Cand->DeductionFailure, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8382. }
  8383. /// CUDA: diagnose an invalid call across targets.
  8384. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  8385. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  8386. FunctionDecl *Callee = Cand->Function;
  8387. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  8388. CalleeTarget = S.IdentifyCUDATarget(Callee);
  8389. std::string FnDesc;
  8390. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
  8391. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  8392. << (unsigned)FnKind << CalleeTarget << CallerTarget;
  8393. // This could be an implicit constructor for which we could not infer the
  8394. // target due to a collsion. Diagnose that case.
  8395. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  8396. if (Meth != nullptr && Meth->isImplicit()) {
  8397. CXXRecordDecl *ParentClass = Meth->getParent();
  8398. Sema::CXXSpecialMember CSM;
  8399. switch (FnKind) {
  8400. default:
  8401. return;
  8402. case oc_implicit_default_constructor:
  8403. CSM = Sema::CXXDefaultConstructor;
  8404. break;
  8405. case oc_implicit_copy_constructor:
  8406. CSM = Sema::CXXCopyConstructor;
  8407. break;
  8408. case oc_implicit_move_constructor:
  8409. CSM = Sema::CXXMoveConstructor;
  8410. break;
  8411. case oc_implicit_copy_assignment:
  8412. CSM = Sema::CXXCopyAssignment;
  8413. break;
  8414. case oc_implicit_move_assignment:
  8415. CSM = Sema::CXXMoveAssignment;
  8416. break;
  8417. };
  8418. bool ConstRHS = false;
  8419. if (Meth->getNumParams()) {
  8420. if (const ReferenceType *RT =
  8421. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  8422. ConstRHS = RT->getPointeeType().isConstQualified();
  8423. }
  8424. }
  8425. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  8426. /* ConstRHS */ ConstRHS,
  8427. /* Diagnose */ true);
  8428. }
  8429. }
  8430. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  8431. FunctionDecl *Callee = Cand->Function;
  8432. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  8433. S.Diag(Callee->getLocation(),
  8434. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  8435. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  8436. }
  8437. /// Generates a 'note' diagnostic for an overload candidate. We've
  8438. /// already generated a primary error at the call site.
  8439. ///
  8440. /// It really does need to be a single diagnostic with its caret
  8441. /// pointed at the candidate declaration. Yes, this creates some
  8442. /// major challenges of technical writing. Yes, this makes pointing
  8443. /// out problems with specific arguments quite awkward. It's still
  8444. /// better than generating twenty screens of text for every failed
  8445. /// overload.
  8446. ///
  8447. /// It would be great to be able to express per-candidate problems
  8448. /// more richly for those diagnostic clients that cared, but we'd
  8449. /// still have to be just as careful with the default diagnostics.
  8450. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  8451. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change: add OpLoc
  8452. FunctionDecl *Fn = Cand->Function;
  8453. // Note deleted candidates, but only if they're viable.
  8454. if (Cand->Viable && (Fn->isDeleted() ||
  8455. S.isFunctionConsideredUnavailable(Fn))) {
  8456. std::string FnDesc;
  8457. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  8458. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  8459. << FnKind << FnDesc
  8460. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  8461. MaybeEmitInheritedConstructorNote(S, Fn);
  8462. return;
  8463. }
  8464. // We don't really have anything else to say about viable candidates.
  8465. if (Cand->Viable) {
  8466. S.NoteOverloadCandidate(Fn);
  8467. return;
  8468. }
  8469. switch (Cand->FailureKind) {
  8470. case ovl_fail_too_many_arguments:
  8471. case ovl_fail_too_few_arguments:
  8472. return DiagnoseArityMismatch(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8473. case ovl_fail_bad_deduction:
  8474. return DiagnoseBadDeduction(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8475. case ovl_fail_illegal_constructor: {
  8476. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  8477. << (Fn->getPrimaryTemplate() ? 1 : 0);
  8478. MaybeEmitInheritedConstructorNote(S, Fn);
  8479. return;
  8480. }
  8481. case ovl_fail_trivial_conversion:
  8482. case ovl_fail_bad_final_conversion:
  8483. case ovl_fail_final_conversion_not_exact:
  8484. return S.NoteOverloadCandidate(Fn);
  8485. case ovl_fail_bad_conversion: {
  8486. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  8487. for (unsigned N = Cand->NumConversions; I != N; ++I)
  8488. if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8489. return DiagnoseBadConversion(S, Cand, I, Cand->Conversions[I], OpLoc); // HLSL Change: add OpLoc
  8490. if (Cand->OutConversions[I].isInitialized() && Cand->OutConversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8491. return DiagnoseBadConversion(S, Cand, I, Cand->OutConversions[I], OpLoc); // HLSL Change: add OpLoc
  8492. // FIXME: this currently happens when we're called from SemaInit
  8493. // when user-conversion overload fails. Figure out how to handle
  8494. // those conditions and diagnose them well.
  8495. return S.NoteOverloadCandidate(Fn);
  8496. }
  8497. case ovl_fail_bad_target:
  8498. return DiagnoseBadTarget(S, Cand);
  8499. case ovl_fail_enable_if:
  8500. return DiagnoseFailedEnableIfAttr(S, Cand);
  8501. }
  8502. }
  8503. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  8504. // Desugar the type of the surrogate down to a function type,
  8505. // retaining as many typedefs as possible while still showing
  8506. // the function type (and, therefore, its parameter types).
  8507. QualType FnType = Cand->Surrogate->getConversionType();
  8508. bool isLValueReference = false;
  8509. bool isRValueReference = false;
  8510. bool isPointer = false;
  8511. if (const LValueReferenceType *FnTypeRef =
  8512. FnType->getAs<LValueReferenceType>()) {
  8513. FnType = FnTypeRef->getPointeeType();
  8514. isLValueReference = true;
  8515. } else if (const RValueReferenceType *FnTypeRef =
  8516. FnType->getAs<RValueReferenceType>()) {
  8517. FnType = FnTypeRef->getPointeeType();
  8518. isRValueReference = true;
  8519. }
  8520. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  8521. FnType = FnTypePtr->getPointeeType();
  8522. isPointer = true;
  8523. }
  8524. // Desugar down to a function type.
  8525. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  8526. // Reconstruct the pointer/reference as appropriate.
  8527. if (isPointer) FnType = S.Context.getPointerType(FnType);
  8528. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  8529. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  8530. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  8531. << FnType;
  8532. MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
  8533. }
  8534. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  8535. SourceLocation OpLoc,
  8536. OverloadCandidate *Cand) {
  8537. assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
  8538. std::string TypeStr("operator");
  8539. TypeStr += Opc;
  8540. TypeStr += "(";
  8541. TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
  8542. if (Cand->NumConversions == 1) {
  8543. TypeStr += ")";
  8544. S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
  8545. } else {
  8546. TypeStr += ", ";
  8547. TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
  8548. TypeStr += ")";
  8549. S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
  8550. }
  8551. }
  8552. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  8553. OverloadCandidate *Cand) {
  8554. unsigned NoOperands = Cand->NumConversions;
  8555. for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
  8556. const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
  8557. if (ICS.isBad()) break; // all meaningless after first invalid
  8558. if (!ICS.isAmbiguous()) continue;
  8559. ICS.DiagnoseAmbiguousConversion(S, OpLoc,
  8560. S.PDiag(diag::note_ambiguous_type_conversion));
  8561. }
  8562. }
  8563. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  8564. if (Cand->Function)
  8565. return Cand->Function->getLocation();
  8566. if (Cand->IsSurrogate)
  8567. return Cand->Surrogate->getLocation();
  8568. return SourceLocation();
  8569. }
  8570. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  8571. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  8572. case Sema::TDK_Success:
  8573. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8574. case Sema::TDK_Invalid:
  8575. case Sema::TDK_Incomplete:
  8576. return 1;
  8577. case Sema::TDK_Underqualified:
  8578. case Sema::TDK_Inconsistent:
  8579. return 2;
  8580. case Sema::TDK_SubstitutionFailure:
  8581. case Sema::TDK_NonDeducedMismatch:
  8582. case Sema::TDK_MiscellaneousDeductionFailure:
  8583. return 3;
  8584. case Sema::TDK_InstantiationDepth:
  8585. case Sema::TDK_FailedOverloadResolution:
  8586. return 4;
  8587. case Sema::TDK_InvalidExplicitArguments:
  8588. return 5;
  8589. case Sema::TDK_TooManyArguments:
  8590. case Sema::TDK_TooFewArguments:
  8591. return 6;
  8592. }
  8593. llvm_unreachable("Unhandled deduction result");
  8594. }
  8595. namespace {
  8596. struct CompareOverloadCandidatesForDisplay {
  8597. Sema &S;
  8598. size_t NumArgs;
  8599. CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
  8600. : S(S), NumArgs(nArgs) {}
  8601. bool operator()(const OverloadCandidate *L,
  8602. const OverloadCandidate *R) {
  8603. // Fast-path this check.
  8604. if (L == R) return false;
  8605. // Order first by viability.
  8606. if (L->Viable) {
  8607. if (!R->Viable) return true;
  8608. // TODO: introduce a tri-valued comparison for overload
  8609. // candidates. Would be more worthwhile if we had a sort
  8610. // that could exploit it.
  8611. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
  8612. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
  8613. } else if (R->Viable)
  8614. return false;
  8615. assert(L->Viable == R->Viable);
  8616. // Criteria by which we can sort non-viable candidates:
  8617. if (!L->Viable) {
  8618. // 1. Arity mismatches come after other candidates.
  8619. if (L->FailureKind == ovl_fail_too_many_arguments ||
  8620. L->FailureKind == ovl_fail_too_few_arguments) {
  8621. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8622. R->FailureKind == ovl_fail_too_few_arguments) {
  8623. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  8624. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  8625. if (LDist == RDist) {
  8626. if (L->FailureKind == R->FailureKind)
  8627. // Sort non-surrogates before surrogates.
  8628. return !L->IsSurrogate && R->IsSurrogate;
  8629. // Sort candidates requiring fewer parameters than there were
  8630. // arguments given after candidates requiring more parameters
  8631. // than there were arguments given.
  8632. return L->FailureKind == ovl_fail_too_many_arguments;
  8633. }
  8634. return LDist < RDist;
  8635. }
  8636. return false;
  8637. }
  8638. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8639. R->FailureKind == ovl_fail_too_few_arguments)
  8640. return true;
  8641. // 2. Bad conversions come first and are ordered by the number
  8642. // of bad conversions and quality of good conversions.
  8643. if (L->FailureKind == ovl_fail_bad_conversion) {
  8644. if (R->FailureKind != ovl_fail_bad_conversion)
  8645. return true;
  8646. // The conversion that can be fixed with a smaller number of changes,
  8647. // comes first.
  8648. unsigned numLFixes = L->Fix.NumConversionsFixed;
  8649. unsigned numRFixes = R->Fix.NumConversionsFixed;
  8650. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  8651. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  8652. if (numLFixes != numRFixes) {
  8653. return numLFixes < numRFixes;
  8654. }
  8655. // If there's any ordering between the defined conversions...
  8656. // FIXME: this might not be transitive.
  8657. assert(L->NumConversions == R->NumConversions);
  8658. int leftBetter = 0;
  8659. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  8660. for (unsigned E = L->NumConversions; I != E; ++I) {
  8661. switch (CompareImplicitConversionSequences(S,
  8662. L->Conversions[I],
  8663. R->Conversions[I])) {
  8664. case ImplicitConversionSequence::Better:
  8665. leftBetter++;
  8666. break;
  8667. case ImplicitConversionSequence::Worse:
  8668. leftBetter--;
  8669. break;
  8670. case ImplicitConversionSequence::Indistinguishable:
  8671. break;
  8672. }
  8673. }
  8674. if (leftBetter > 0) return true;
  8675. if (leftBetter < 0) return false;
  8676. } else if (R->FailureKind == ovl_fail_bad_conversion)
  8677. return false;
  8678. if (L->FailureKind == ovl_fail_bad_deduction) {
  8679. if (R->FailureKind != ovl_fail_bad_deduction)
  8680. return true;
  8681. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8682. return RankDeductionFailure(L->DeductionFailure)
  8683. < RankDeductionFailure(R->DeductionFailure);
  8684. } else if (R->FailureKind == ovl_fail_bad_deduction)
  8685. return false;
  8686. // TODO: others?
  8687. }
  8688. // Sort everything else by location.
  8689. SourceLocation LLoc = GetLocationForCandidate(L);
  8690. SourceLocation RLoc = GetLocationForCandidate(R);
  8691. // Put candidates without locations (e.g. builtins) at the end.
  8692. if (LLoc.isInvalid()) return false;
  8693. if (RLoc.isInvalid()) return true;
  8694. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8695. }
  8696. };
  8697. }
  8698. /// CompleteNonViableCandidate - Normally, overload resolution only
  8699. /// computes up to the first. Produces the FixIt set if possible.
  8700. static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  8701. ArrayRef<Expr *> Args) {
  8702. assert(!Cand->Viable);
  8703. // Don't do anything on failures other than bad conversion.
  8704. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  8705. // We only want the FixIts if all the arguments can be corrected.
  8706. bool Unfixable = false;
  8707. // Use a implicit copy initialization to check conversion fixes.
  8708. Cand->Fix.setConversionChecker(TryCopyInitialization);
  8709. // Skip forward to the first bad conversion.
  8710. unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
  8711. unsigned ConvCount = Cand->NumConversions;
  8712. while (true) {
  8713. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  8714. ConvIdx++;
  8715. if (Cand->Conversions[ConvIdx - 1].isInitialized() && Cand->Conversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8716. Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
  8717. break;
  8718. }
  8719. // HLSL Change Starts - check out conversions
  8720. if (Cand->OutConversions[ConvIdx - 1].isInitialized() && Cand->OutConversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8721. // Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); - consider suggesting a fix
  8722. Unfixable = true;
  8723. break;
  8724. }
  8725. // HLSL Change End
  8726. }
  8727. if (ConvIdx == ConvCount)
  8728. return;
  8729. assert(!Cand->Conversions[ConvIdx].isInitialized() &&
  8730. "remaining conversion is initialized?");
  8731. // FIXME: this should probably be preserved from the overload
  8732. // operation somehow.
  8733. bool SuppressUserConversions = false;
  8734. const FunctionProtoType* Proto;
  8735. unsigned ArgIdx = ConvIdx;
  8736. if (Cand->IsSurrogate) {
  8737. QualType ConvType
  8738. = Cand->Surrogate->getConversionType().getNonReferenceType();
  8739. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  8740. ConvType = ConvPtrType->getPointeeType();
  8741. Proto = ConvType->getAs<FunctionProtoType>();
  8742. ArgIdx--;
  8743. } else if (Cand->Function) {
  8744. Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
  8745. if (isa<CXXMethodDecl>(Cand->Function) &&
  8746. !isa<CXXConstructorDecl>(Cand->Function))
  8747. ArgIdx--;
  8748. } else {
  8749. // Builtin binary operator with a bad first conversion.
  8750. assert(ConvCount <= 3);
  8751. for (; ConvIdx != ConvCount && ConvIdx < 3; ++ConvIdx) // HLSL Change: explicit about ConvIdx < 3
  8752. Cand->Conversions[ConvIdx]
  8753. = TryCopyInitialization(S, Args[ConvIdx],
  8754. Cand->BuiltinTypes.ParamTypes[ConvIdx],
  8755. SuppressUserConversions,
  8756. /*InOverloadResolution*/ true,
  8757. /*AllowObjCWritebackConversion=*/
  8758. S.getLangOpts().ObjCAutoRefCount);
  8759. return;
  8760. }
  8761. // Fill in the rest of the conversions.
  8762. unsigned NumParams = Proto->getNumParams();
  8763. for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
  8764. if (ArgIdx < NumParams) {
  8765. Cand->Conversions[ConvIdx] = TryCopyInitialization(
  8766. S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
  8767. /*InOverloadResolution=*/true,
  8768. /*AllowObjCWritebackConversion=*/
  8769. S.getLangOpts().ObjCAutoRefCount);
  8770. // Store the FixIt in the candidate if it exists.
  8771. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  8772. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  8773. }
  8774. else
  8775. Cand->Conversions[ConvIdx].setEllipsis();
  8776. }
  8777. }
  8778. /// PrintOverloadCandidates - When overload resolution fails, prints
  8779. /// diagnostic messages containing the candidates in the candidate
  8780. /// set.
  8781. void OverloadCandidateSet::NoteCandidates(Sema &S,
  8782. OverloadCandidateDisplayKind OCD,
  8783. ArrayRef<Expr *> Args,
  8784. StringRef Opc,
  8785. SourceLocation OpLoc) {
  8786. // Sort the candidates by viability and position. Sorting directly would
  8787. // be prohibitive, so we make a set of pointers and sort those.
  8788. SmallVector<OverloadCandidate*, 32> Cands;
  8789. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  8790. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8791. if (Cand->Viable)
  8792. Cands.push_back(Cand);
  8793. else if (OCD == OCD_AllCandidates) {
  8794. CompleteNonViableCandidate(S, Cand, Args);
  8795. if (Cand->Function || Cand->IsSurrogate)
  8796. Cands.push_back(Cand);
  8797. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  8798. // want to list every possible builtin candidate.
  8799. }
  8800. }
  8801. std::sort(Cands.begin(), Cands.end(),
  8802. CompareOverloadCandidatesForDisplay(S, Args.size()));
  8803. bool ReportedAmbiguousConversions = false;
  8804. SmallVectorImpl<OverloadCandidate*>::iterator I, E;
  8805. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8806. unsigned CandsShown = 0;
  8807. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8808. OverloadCandidate *Cand = *I;
  8809. // Set an arbitrary limit on the number of candidate functions we'll spam
  8810. // the user with. FIXME: This limit should depend on details of the
  8811. // candidate list.
  8812. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  8813. break;
  8814. }
  8815. ++CandsShown;
  8816. if (Cand->Function)
  8817. NoteFunctionCandidate(S, Cand, Args.size(), OpLoc); // HLSL Change: add OpLoc
  8818. else if (Cand->IsSurrogate)
  8819. NoteSurrogateCandidate(S, Cand);
  8820. else {
  8821. assert(Cand->Viable &&
  8822. "Non-viable built-in candidates are not added to Cands.");
  8823. // Generally we only see ambiguities including viable builtin
  8824. // operators if overload resolution got screwed up by an
  8825. // ambiguous user-defined conversion.
  8826. //
  8827. // FIXME: It's quite possible for different conversions to see
  8828. // different ambiguities, though.
  8829. if (!ReportedAmbiguousConversions) {
  8830. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  8831. ReportedAmbiguousConversions = true;
  8832. }
  8833. // If this is a viable builtin, print it.
  8834. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  8835. }
  8836. }
  8837. if (I != E)
  8838. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  8839. }
  8840. static SourceLocation
  8841. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  8842. return Cand->Specialization ? Cand->Specialization->getLocation()
  8843. : SourceLocation();
  8844. }
  8845. namespace {
  8846. struct CompareTemplateSpecCandidatesForDisplay {
  8847. Sema &S;
  8848. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  8849. bool operator()(const TemplateSpecCandidate *L,
  8850. const TemplateSpecCandidate *R) {
  8851. // Fast-path this check.
  8852. if (L == R)
  8853. return false;
  8854. // Assuming that both candidates are not matches...
  8855. // Sort by the ranking of deduction failures.
  8856. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8857. return RankDeductionFailure(L->DeductionFailure) <
  8858. RankDeductionFailure(R->DeductionFailure);
  8859. // Sort everything else by location.
  8860. SourceLocation LLoc = GetLocationForCandidate(L);
  8861. SourceLocation RLoc = GetLocationForCandidate(R);
  8862. // Put candidates without locations (e.g. builtins) at the end.
  8863. if (LLoc.isInvalid())
  8864. return false;
  8865. if (RLoc.isInvalid())
  8866. return true;
  8867. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8868. }
  8869. };
  8870. }
  8871. /// Diagnose a template argument deduction failure.
  8872. /// We are treating these failures as overload failures due to bad
  8873. /// deductions.
  8874. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
  8875. DiagnoseBadDeduction(S, Specialization, // pattern
  8876. DeductionFailure, /*NumArgs=*/0, SourceLocation()); // HLSL Change - add OpLoc
  8877. }
  8878. void TemplateSpecCandidateSet::destroyCandidates() {
  8879. for (iterator i = begin(), e = end(); i != e; ++i) {
  8880. i->DeductionFailure.Destroy();
  8881. }
  8882. }
  8883. void TemplateSpecCandidateSet::clear() {
  8884. destroyCandidates();
  8885. Candidates.clear();
  8886. }
  8887. /// NoteCandidates - When no template specialization match is found, prints
  8888. /// diagnostic messages containing the non-matching specializations that form
  8889. /// the candidate set.
  8890. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  8891. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  8892. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  8893. // Sort the candidates by position (assuming no candidate is a match).
  8894. // Sorting directly would be prohibitive, so we make a set of pointers
  8895. // and sort those.
  8896. SmallVector<TemplateSpecCandidate *, 32> Cands;
  8897. Cands.reserve(size());
  8898. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8899. if (Cand->Specialization)
  8900. Cands.push_back(Cand);
  8901. // Otherwise, this is a non-matching builtin candidate. We do not,
  8902. // in general, want to list every possible builtin candidate.
  8903. }
  8904. std::sort(Cands.begin(), Cands.end(),
  8905. CompareTemplateSpecCandidatesForDisplay(S));
  8906. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  8907. // for generalization purposes (?).
  8908. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8909. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  8910. unsigned CandsShown = 0;
  8911. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8912. TemplateSpecCandidate *Cand = *I;
  8913. // Set an arbitrary limit on the number of candidates we'll spam
  8914. // the user with. FIXME: This limit should depend on details of the
  8915. // candidate list.
  8916. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8917. break;
  8918. ++CandsShown;
  8919. assert(Cand->Specialization &&
  8920. "Non-matching built-in candidates are not added to Cands.");
  8921. Cand->NoteDeductionFailure(S);
  8922. }
  8923. if (I != E)
  8924. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  8925. }
  8926. // [PossiblyAFunctionType] --> [Return]
  8927. // NonFunctionType --> NonFunctionType
  8928. // R (A) --> R(A)
  8929. // R (*)(A) --> R (A)
  8930. // R (&)(A) --> R (A)
  8931. // R (S::*)(A) --> R (A)
  8932. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  8933. QualType Ret = PossiblyAFunctionType;
  8934. if (const PointerType *ToTypePtr =
  8935. PossiblyAFunctionType->getAs<PointerType>())
  8936. Ret = ToTypePtr->getPointeeType();
  8937. else if (const ReferenceType *ToTypeRef =
  8938. PossiblyAFunctionType->getAs<ReferenceType>())
  8939. Ret = ToTypeRef->getPointeeType();
  8940. else if (const MemberPointerType *MemTypePtr =
  8941. PossiblyAFunctionType->getAs<MemberPointerType>())
  8942. Ret = MemTypePtr->getPointeeType();
  8943. Ret =
  8944. Context.getCanonicalType(Ret).getUnqualifiedType();
  8945. return Ret;
  8946. }
  8947. namespace {
  8948. // A helper class to help with address of function resolution
  8949. // - allows us to avoid passing around all those ugly parameters
  8950. class AddressOfFunctionResolver {
  8951. Sema& S;
  8952. Expr* SourceExpr;
  8953. const QualType& TargetType;
  8954. QualType TargetFunctionType; // Extracted function type from target type
  8955. bool Complain;
  8956. //DeclAccessPair& ResultFunctionAccessPair;
  8957. ASTContext& Context;
  8958. bool TargetTypeIsNonStaticMemberFunction;
  8959. bool FoundNonTemplateFunction;
  8960. bool StaticMemberFunctionFromBoundPointer;
  8961. OverloadExpr::FindResult OvlExprInfo;
  8962. OverloadExpr *OvlExpr;
  8963. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  8964. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  8965. TemplateSpecCandidateSet FailedCandidates;
  8966. public:
  8967. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  8968. const QualType &TargetType, bool Complain)
  8969. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  8970. Complain(Complain), Context(S.getASTContext()),
  8971. TargetTypeIsNonStaticMemberFunction(
  8972. !!TargetType->getAs<MemberPointerType>()),
  8973. FoundNonTemplateFunction(false),
  8974. StaticMemberFunctionFromBoundPointer(false),
  8975. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  8976. OvlExpr(OvlExprInfo.Expression),
  8977. FailedCandidates(OvlExpr->getNameLoc()) {
  8978. ExtractUnqualifiedFunctionTypeFromTargetType();
  8979. if (TargetFunctionType->isFunctionType()) {
  8980. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  8981. if (!UME->isImplicitAccess() &&
  8982. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  8983. StaticMemberFunctionFromBoundPointer = true;
  8984. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  8985. DeclAccessPair dap;
  8986. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  8987. OvlExpr, false, &dap)) {
  8988. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  8989. if (!Method->isStatic()) {
  8990. // If the target type is a non-function type and the function found
  8991. // is a non-static member function, pretend as if that was the
  8992. // target, it's the only possible type to end up with.
  8993. TargetTypeIsNonStaticMemberFunction = true;
  8994. // And skip adding the function if its not in the proper form.
  8995. // We'll diagnose this due to an empty set of functions.
  8996. if (!OvlExprInfo.HasFormOfMemberPointer)
  8997. return;
  8998. }
  8999. Matches.push_back(std::make_pair(dap, Fn));
  9000. }
  9001. return;
  9002. }
  9003. if (OvlExpr->hasExplicitTemplateArgs())
  9004. OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
  9005. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  9006. // C++ [over.over]p4:
  9007. // If more than one function is selected, [...]
  9008. if (Matches.size() > 1) {
  9009. if (FoundNonTemplateFunction)
  9010. EliminateAllTemplateMatches();
  9011. else
  9012. EliminateAllExceptMostSpecializedTemplate();
  9013. }
  9014. }
  9015. }
  9016. private:
  9017. bool isTargetTypeAFunction() const {
  9018. return TargetFunctionType->isFunctionType();
  9019. }
  9020. // [ToType] [Return]
  9021. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  9022. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  9023. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  9024. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  9025. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  9026. }
  9027. // return true if any matching specializations were found
  9028. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  9029. const DeclAccessPair& CurAccessFunPair) {
  9030. if (CXXMethodDecl *Method
  9031. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  9032. // Skip non-static function templates when converting to pointer, and
  9033. // static when converting to member pointer.
  9034. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9035. return false;
  9036. }
  9037. else if (TargetTypeIsNonStaticMemberFunction)
  9038. return false;
  9039. // C++ [over.over]p2:
  9040. // If the name is a function template, template argument deduction is
  9041. // done (14.8.2.2), and if the argument deduction succeeds, the
  9042. // resulting template argument list is used to generate a single
  9043. // function template specialization, which is added to the set of
  9044. // overloaded functions considered.
  9045. FunctionDecl *Specialization = nullptr;
  9046. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9047. if (Sema::TemplateDeductionResult Result
  9048. = S.DeduceTemplateArguments(FunctionTemplate,
  9049. &OvlExplicitTemplateArgs,
  9050. TargetFunctionType, Specialization,
  9051. Info, /*InOverloadResolution=*/true)) {
  9052. // Make a note of the failed deduction for diagnostics.
  9053. FailedCandidates.addCandidate()
  9054. .set(FunctionTemplate->getTemplatedDecl(),
  9055. MakeDeductionFailureInfo(Context, Result, Info));
  9056. return false;
  9057. }
  9058. // Template argument deduction ensures that we have an exact match or
  9059. // compatible pointer-to-function arguments that would be adjusted by ICS.
  9060. // This function template specicalization works.
  9061. Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
  9062. assert(S.isSameOrCompatibleFunctionType(
  9063. Context.getCanonicalType(Specialization->getType()),
  9064. Context.getCanonicalType(TargetFunctionType)));
  9065. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  9066. return true;
  9067. }
  9068. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  9069. const DeclAccessPair& CurAccessFunPair) {
  9070. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  9071. // Skip non-static functions when converting to pointer, and static
  9072. // when converting to member pointer.
  9073. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9074. return false;
  9075. }
  9076. else if (TargetTypeIsNonStaticMemberFunction)
  9077. return false;
  9078. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  9079. if (S.getLangOpts().CUDA)
  9080. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  9081. if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
  9082. return false;
  9083. // If any candidate has a placeholder return type, trigger its deduction
  9084. // now.
  9085. if (S.getLangOpts().CPlusPlus14 &&
  9086. FunDecl->getReturnType()->isUndeducedType() &&
  9087. S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
  9088. return false;
  9089. QualType ResultTy;
  9090. if (Context.hasSameUnqualifiedType(TargetFunctionType,
  9091. FunDecl->getType()) ||
  9092. S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
  9093. ResultTy)) {
  9094. Matches.push_back(std::make_pair(CurAccessFunPair,
  9095. cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  9096. FoundNonTemplateFunction = true;
  9097. return true;
  9098. }
  9099. }
  9100. return false;
  9101. }
  9102. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  9103. bool Ret = false;
  9104. // If the overload expression doesn't have the form of a pointer to
  9105. // member, don't try to convert it to a pointer-to-member type.
  9106. if (IsInvalidFormOfPointerToMemberFunction())
  9107. return false;
  9108. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9109. E = OvlExpr->decls_end();
  9110. I != E; ++I) {
  9111. // Look through any using declarations to find the underlying function.
  9112. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  9113. // C++ [over.over]p3:
  9114. // Non-member functions and static member functions match
  9115. // targets of type "pointer-to-function" or "reference-to-function."
  9116. // Nonstatic member functions match targets of
  9117. // type "pointer-to-member-function."
  9118. // Note that according to DR 247, the containing class does not matter.
  9119. if (FunctionTemplateDecl *FunctionTemplate
  9120. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  9121. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  9122. Ret = true;
  9123. }
  9124. // If we have explicit template arguments supplied, skip non-templates.
  9125. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  9126. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  9127. Ret = true;
  9128. }
  9129. assert(Ret || Matches.empty());
  9130. return Ret;
  9131. }
  9132. void EliminateAllExceptMostSpecializedTemplate() {
  9133. // [...] and any given function template specialization F1 is
  9134. // eliminated if the set contains a second function template
  9135. // specialization whose function template is more specialized
  9136. // than the function template of F1 according to the partial
  9137. // ordering rules of 14.5.5.2.
  9138. // The algorithm specified above is quadratic. We instead use a
  9139. // two-pass algorithm (similar to the one used to identify the
  9140. // best viable function in an overload set) that identifies the
  9141. // best function template (if it exists).
  9142. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  9143. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  9144. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  9145. // TODO: It looks like FailedCandidates does not serve much purpose
  9146. // here, since the no_viable diagnostic has index 0.
  9147. UnresolvedSetIterator Result = S.getMostSpecialized(
  9148. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  9149. SourceExpr->getLocStart(), S.PDiag(),
  9150. S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
  9151. .second->getDeclName(),
  9152. S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
  9153. Complain, TargetFunctionType);
  9154. if (Result != MatchesCopy.end()) {
  9155. // Make it the first and only element
  9156. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  9157. Matches[0].second = cast<FunctionDecl>(*Result);
  9158. Matches.resize(1);
  9159. }
  9160. }
  9161. void EliminateAllTemplateMatches() {
  9162. // [...] any function template specializations in the set are
  9163. // eliminated if the set also contains a non-template function, [...]
  9164. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  9165. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  9166. ++I;
  9167. else {
  9168. Matches[I] = Matches[--N];
  9169. Matches.set_size(N);
  9170. }
  9171. }
  9172. }
  9173. public:
  9174. void ComplainNoMatchesFound() const {
  9175. assert(Matches.empty());
  9176. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
  9177. << OvlExpr->getName() << TargetFunctionType
  9178. << OvlExpr->getSourceRange();
  9179. if (FailedCandidates.empty())
  9180. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9181. else {
  9182. // We have some deduction failure messages. Use them to diagnose
  9183. // the function templates, and diagnose the non-template candidates
  9184. // normally.
  9185. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9186. IEnd = OvlExpr->decls_end();
  9187. I != IEnd; ++I)
  9188. if (FunctionDecl *Fun =
  9189. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  9190. S.NoteOverloadCandidate(Fun, TargetFunctionType);
  9191. FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
  9192. }
  9193. }
  9194. bool IsInvalidFormOfPointerToMemberFunction() const {
  9195. return TargetTypeIsNonStaticMemberFunction &&
  9196. !OvlExprInfo.HasFormOfMemberPointer;
  9197. }
  9198. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  9199. // TODO: Should we condition this on whether any functions might
  9200. // have matched, or is it more appropriate to do that in callers?
  9201. // TODO: a fixit wouldn't hurt.
  9202. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  9203. << TargetType << OvlExpr->getSourceRange();
  9204. }
  9205. bool IsStaticMemberFunctionFromBoundPointer() const {
  9206. return StaticMemberFunctionFromBoundPointer;
  9207. }
  9208. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  9209. S.Diag(OvlExpr->getLocStart(),
  9210. diag::err_invalid_form_pointer_member_function)
  9211. << OvlExpr->getSourceRange();
  9212. }
  9213. void ComplainOfInvalidConversion() const {
  9214. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
  9215. << OvlExpr->getName() << TargetType;
  9216. }
  9217. void ComplainMultipleMatchesFound() const {
  9218. assert(Matches.size() > 1);
  9219. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
  9220. << OvlExpr->getName()
  9221. << OvlExpr->getSourceRange();
  9222. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9223. }
  9224. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  9225. int getNumMatches() const { return Matches.size(); }
  9226. FunctionDecl* getMatchingFunctionDecl() const {
  9227. if (Matches.size() != 1) return nullptr;
  9228. return Matches[0].second;
  9229. }
  9230. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  9231. if (Matches.size() != 1) return nullptr;
  9232. return &Matches[0].first;
  9233. }
  9234. };
  9235. }
  9236. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  9237. /// an overloaded function (C++ [over.over]), where @p From is an
  9238. /// expression with overloaded function type and @p ToType is the type
  9239. /// we're trying to resolve to. For example:
  9240. ///
  9241. /// @code
  9242. /// int f(double);
  9243. /// int f(int);
  9244. ///
  9245. /// int (*pfd)(double) = f; // selects f(double)
  9246. /// @endcode
  9247. ///
  9248. /// This routine returns the resulting FunctionDecl if it could be
  9249. /// resolved, and NULL otherwise. When @p Complain is true, this
  9250. /// routine will emit diagnostics if there is an error.
  9251. FunctionDecl *
  9252. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  9253. QualType TargetType,
  9254. bool Complain,
  9255. DeclAccessPair &FoundResult,
  9256. bool *pHadMultipleCandidates) {
  9257. assert(AddressOfExpr->getType() == Context.OverloadTy);
  9258. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  9259. Complain);
  9260. int NumMatches = Resolver.getNumMatches();
  9261. FunctionDecl *Fn = nullptr;
  9262. if (NumMatches == 0 && Complain) {
  9263. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  9264. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  9265. else
  9266. Resolver.ComplainNoMatchesFound();
  9267. }
  9268. else if (NumMatches > 1 && Complain)
  9269. Resolver.ComplainMultipleMatchesFound();
  9270. else if (NumMatches == 1) {
  9271. Fn = Resolver.getMatchingFunctionDecl();
  9272. assert(Fn);
  9273. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  9274. if (Complain) {
  9275. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  9276. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  9277. else
  9278. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  9279. }
  9280. }
  9281. if (pHadMultipleCandidates)
  9282. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  9283. return Fn;
  9284. }
  9285. /// \brief Given an expression that refers to an overloaded function, try to
  9286. /// resolve that overloaded function expression down to a single function.
  9287. ///
  9288. /// This routine can only resolve template-ids that refer to a single function
  9289. /// template, where that template-id refers to a single template whose template
  9290. /// arguments are either provided by the template-id or have defaults,
  9291. /// as described in C++0x [temp.arg.explicit]p3.
  9292. ///
  9293. /// If no template-ids are found, no diagnostics are emitted and NULL is
  9294. /// returned.
  9295. FunctionDecl *
  9296. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  9297. bool Complain,
  9298. DeclAccessPair *FoundResult) {
  9299. // C++ [over.over]p1:
  9300. // [...] [Note: any redundant set of parentheses surrounding the
  9301. // overloaded function name is ignored (5.1). ]
  9302. // C++ [over.over]p1:
  9303. // [...] The overloaded function name can be preceded by the &
  9304. // operator.
  9305. // If we didn't actually find any template-ids, we're done.
  9306. if (!ovl->hasExplicitTemplateArgs())
  9307. return nullptr;
  9308. TemplateArgumentListInfo ExplicitTemplateArgs;
  9309. ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
  9310. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  9311. // Look through all of the overloaded functions, searching for one
  9312. // whose type matches exactly.
  9313. FunctionDecl *Matched = nullptr;
  9314. for (UnresolvedSetIterator I = ovl->decls_begin(),
  9315. E = ovl->decls_end(); I != E; ++I) {
  9316. // C++0x [temp.arg.explicit]p3:
  9317. // [...] In contexts where deduction is done and fails, or in contexts
  9318. // where deduction is not done, if a template argument list is
  9319. // specified and it, along with any default template arguments,
  9320. // identifies a single function template specialization, then the
  9321. // template-id is an lvalue for the function template specialization.
  9322. FunctionTemplateDecl *FunctionTemplate
  9323. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  9324. // C++ [over.over]p2:
  9325. // If the name is a function template, template argument deduction is
  9326. // done (14.8.2.2), and if the argument deduction succeeds, the
  9327. // resulting template argument list is used to generate a single
  9328. // function template specialization, which is added to the set of
  9329. // overloaded functions considered.
  9330. FunctionDecl *Specialization = nullptr;
  9331. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9332. if (TemplateDeductionResult Result
  9333. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  9334. Specialization, Info,
  9335. /*InOverloadResolution=*/true)) {
  9336. // Make a note of the failed deduction for diagnostics.
  9337. // TODO: Actually use the failed-deduction info?
  9338. FailedCandidates.addCandidate()
  9339. .set(FunctionTemplate->getTemplatedDecl(),
  9340. MakeDeductionFailureInfo(Context, Result, Info));
  9341. continue;
  9342. }
  9343. assert(Specialization && "no specialization and no error?");
  9344. // Multiple matches; we can't resolve to a single declaration.
  9345. if (Matched) {
  9346. if (Complain) {
  9347. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  9348. << ovl->getName();
  9349. NoteAllOverloadCandidates(ovl);
  9350. }
  9351. return nullptr;
  9352. }
  9353. Matched = Specialization;
  9354. if (FoundResult) *FoundResult = I.getPair();
  9355. }
  9356. if (Matched && getLangOpts().CPlusPlus14 &&
  9357. Matched->getReturnType()->isUndeducedType() &&
  9358. DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
  9359. return nullptr;
  9360. return Matched;
  9361. }
  9362. // Resolve and fix an overloaded expression that can be resolved
  9363. // because it identifies a single function template specialization.
  9364. //
  9365. // Last three arguments should only be supplied if Complain = true
  9366. //
  9367. // Return true if it was logically possible to so resolve the
  9368. // expression, regardless of whether or not it succeeded. Always
  9369. // returns true if 'complain' is set.
  9370. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  9371. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  9372. bool complain, const SourceRange& OpRangeForComplaining,
  9373. QualType DestTypeForComplaining,
  9374. unsigned DiagIDForComplaining) {
  9375. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  9376. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  9377. DeclAccessPair found;
  9378. ExprResult SingleFunctionExpression;
  9379. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  9380. ovl.Expression, /*complain*/ false, &found)) {
  9381. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
  9382. SrcExpr = ExprError();
  9383. return true;
  9384. }
  9385. // It is only correct to resolve to an instance method if we're
  9386. // resolving a form that's permitted to be a pointer to member.
  9387. // Otherwise we'll end up making a bound member expression, which
  9388. // is illegal in all the contexts we resolve like this.
  9389. if (!ovl.HasFormOfMemberPointer &&
  9390. isa<CXXMethodDecl>(fn) &&
  9391. cast<CXXMethodDecl>(fn)->isInstance()) {
  9392. if (!complain) return false;
  9393. Diag(ovl.Expression->getExprLoc(),
  9394. diag::err_bound_member_function)
  9395. << 0 << ovl.Expression->getSourceRange();
  9396. // TODO: I believe we only end up here if there's a mix of
  9397. // static and non-static candidates (otherwise the expression
  9398. // would have 'bound member' type, not 'overload' type).
  9399. // Ideally we would note which candidate was chosen and why
  9400. // the static candidates were rejected.
  9401. SrcExpr = ExprError();
  9402. return true;
  9403. }
  9404. // Fix the expression to refer to 'fn'.
  9405. SingleFunctionExpression =
  9406. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  9407. // If desired, do function-to-pointer decay.
  9408. if (doFunctionPointerConverion) {
  9409. SingleFunctionExpression =
  9410. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  9411. if (SingleFunctionExpression.isInvalid()) {
  9412. SrcExpr = ExprError();
  9413. return true;
  9414. }
  9415. }
  9416. }
  9417. if (!SingleFunctionExpression.isUsable()) {
  9418. if (complain) {
  9419. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  9420. << ovl.Expression->getName()
  9421. << DestTypeForComplaining
  9422. << OpRangeForComplaining
  9423. << ovl.Expression->getQualifierLoc().getSourceRange();
  9424. NoteAllOverloadCandidates(SrcExpr.get());
  9425. SrcExpr = ExprError();
  9426. return true;
  9427. }
  9428. return false;
  9429. }
  9430. SrcExpr = SingleFunctionExpression;
  9431. return true;
  9432. }
  9433. /// \brief Add a single candidate to the overload set.
  9434. static void AddOverloadedCallCandidate(Sema &S,
  9435. DeclAccessPair FoundDecl,
  9436. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9437. ArrayRef<Expr *> Args,
  9438. OverloadCandidateSet &CandidateSet,
  9439. bool PartialOverloading,
  9440. bool KnownValid) {
  9441. NamedDecl *Callee = FoundDecl.getDecl();
  9442. if (isa<UsingShadowDecl>(Callee))
  9443. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  9444. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  9445. if (ExplicitTemplateArgs) {
  9446. assert(!KnownValid && "Explicit template arguments?");
  9447. return;
  9448. }
  9449. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  9450. /*SuppressUsedConversions=*/false,
  9451. PartialOverloading);
  9452. return;
  9453. }
  9454. if (FunctionTemplateDecl *FuncTemplate
  9455. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  9456. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  9457. ExplicitTemplateArgs, Args, CandidateSet,
  9458. /*SuppressUsedConversions=*/false,
  9459. PartialOverloading);
  9460. return;
  9461. }
  9462. assert(!KnownValid && "unhandled case in overloaded call candidate");
  9463. }
  9464. /// \brief Add the overload candidates named by callee and/or found by argument
  9465. /// dependent lookup to the given overload set.
  9466. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  9467. ArrayRef<Expr *> Args,
  9468. OverloadCandidateSet &CandidateSet,
  9469. bool PartialOverloading) {
  9470. #ifndef NDEBUG
  9471. // Verify that ArgumentDependentLookup is consistent with the rules
  9472. // in C++0x [basic.lookup.argdep]p3:
  9473. //
  9474. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9475. // and let Y be the lookup set produced by argument dependent
  9476. // lookup (defined as follows). If X contains
  9477. //
  9478. // -- a declaration of a class member, or
  9479. //
  9480. // -- a block-scope function declaration that is not a
  9481. // using-declaration, or
  9482. //
  9483. // -- a declaration that is neither a function or a function
  9484. // template
  9485. //
  9486. // then Y is empty.
  9487. if (ULE->requiresADL()) {
  9488. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9489. E = ULE->decls_end(); I != E; ++I) {
  9490. assert(!(*I)->getDeclContext()->isRecord());
  9491. assert(isa<UsingShadowDecl>(*I) ||
  9492. !(*I)->getDeclContext()->isFunctionOrMethod());
  9493. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  9494. }
  9495. }
  9496. #endif
  9497. // HLSL Change - allow ExternalSource the ability to add the overloads for a call.
  9498. if (ExternalSource &&
  9499. ExternalSource->AddOverloadedCallCandidates(ULE, Args, CandidateSet, PartialOverloading)) {
  9500. return;
  9501. }
  9502. // It would be nice to avoid this copy.
  9503. TemplateArgumentListInfo TABuffer;
  9504. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9505. if (ULE->hasExplicitTemplateArgs()) {
  9506. ULE->copyTemplateArgumentsInto(TABuffer);
  9507. ExplicitTemplateArgs = &TABuffer;
  9508. }
  9509. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9510. E = ULE->decls_end(); I != E; ++I)
  9511. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  9512. CandidateSet, PartialOverloading,
  9513. /*KnownValid*/ true);
  9514. if (ULE->requiresADL())
  9515. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  9516. Args, ExplicitTemplateArgs,
  9517. CandidateSet, PartialOverloading);
  9518. }
  9519. /// Determine whether a declaration with the specified name could be moved into
  9520. /// a different namespace.
  9521. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  9522. switch (Name.getCXXOverloadedOperator()) {
  9523. case OO_New: case OO_Array_New:
  9524. case OO_Delete: case OO_Array_Delete:
  9525. return false;
  9526. default:
  9527. return true;
  9528. }
  9529. }
  9530. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  9531. /// template, where the non-dependent name was declared after the template
  9532. /// was defined. This is common in code written for a compilers which do not
  9533. /// correctly implement two-stage name lookup.
  9534. ///
  9535. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9536. static bool
  9537. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  9538. const CXXScopeSpec &SS, LookupResult &R,
  9539. OverloadCandidateSet::CandidateSetKind CSK,
  9540. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9541. ArrayRef<Expr *> Args,
  9542. bool *DoDiagnoseEmptyLookup = nullptr) {
  9543. if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
  9544. return false;
  9545. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  9546. if (DC->isTransparentContext())
  9547. continue;
  9548. SemaRef.LookupQualifiedName(R, DC);
  9549. if (!R.empty()) {
  9550. R.suppressDiagnostics();
  9551. if (isa<CXXRecordDecl>(DC)) {
  9552. // Don't diagnose names we find in classes; we get much better
  9553. // diagnostics for these from DiagnoseEmptyLookup.
  9554. R.clear();
  9555. if (DoDiagnoseEmptyLookup)
  9556. *DoDiagnoseEmptyLookup = true;
  9557. return false;
  9558. }
  9559. OverloadCandidateSet Candidates(FnLoc, CSK);
  9560. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  9561. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  9562. ExplicitTemplateArgs, Args,
  9563. Candidates, false, /*KnownValid*/ false);
  9564. OverloadCandidateSet::iterator Best;
  9565. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  9566. // No viable functions. Don't bother the user with notes for functions
  9567. // which don't work and shouldn't be found anyway.
  9568. R.clear();
  9569. return false;
  9570. }
  9571. // Find the namespaces where ADL would have looked, and suggest
  9572. // declaring the function there instead.
  9573. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9574. Sema::AssociatedClassSet AssociatedClasses;
  9575. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  9576. AssociatedNamespaces,
  9577. AssociatedClasses);
  9578. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  9579. if (canBeDeclaredInNamespace(R.getLookupName())) {
  9580. DeclContext *Std = SemaRef.getStdNamespace();
  9581. for (Sema::AssociatedNamespaceSet::iterator
  9582. it = AssociatedNamespaces.begin(),
  9583. end = AssociatedNamespaces.end(); it != end; ++it) {
  9584. // Never suggest declaring a function within namespace 'std'.
  9585. if (Std && Std->Encloses(*it))
  9586. continue;
  9587. // Never suggest declaring a function within a namespace with a
  9588. // reserved name, like __gnu_cxx.
  9589. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  9590. if (NS &&
  9591. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  9592. continue;
  9593. SuggestedNamespaces.insert(*it);
  9594. }
  9595. }
  9596. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  9597. << R.getLookupName();
  9598. if (SuggestedNamespaces.empty()) {
  9599. SemaRef.Diag(Best->Function->getLocation(),
  9600. diag::note_not_found_by_two_phase_lookup)
  9601. << R.getLookupName() << 0;
  9602. } else if (SuggestedNamespaces.size() == 1) {
  9603. SemaRef.Diag(Best->Function->getLocation(),
  9604. diag::note_not_found_by_two_phase_lookup)
  9605. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  9606. } else {
  9607. // FIXME: It would be useful to list the associated namespaces here,
  9608. // but the diagnostics infrastructure doesn't provide a way to produce
  9609. // a localized representation of a list of items.
  9610. SemaRef.Diag(Best->Function->getLocation(),
  9611. diag::note_not_found_by_two_phase_lookup)
  9612. << R.getLookupName() << 2;
  9613. }
  9614. // Try to recover by calling this function.
  9615. return true;
  9616. }
  9617. R.clear();
  9618. }
  9619. return false;
  9620. }
  9621. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  9622. /// template, where the non-dependent operator was declared after the template
  9623. /// was defined.
  9624. ///
  9625. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9626. static bool
  9627. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  9628. SourceLocation OpLoc,
  9629. ArrayRef<Expr *> Args) {
  9630. DeclarationName OpName =
  9631. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  9632. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  9633. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  9634. OverloadCandidateSet::CSK_Operator,
  9635. /*ExplicitTemplateArgs=*/nullptr, Args);
  9636. }
  9637. namespace {
  9638. class BuildRecoveryCallExprRAII {
  9639. Sema &SemaRef;
  9640. public:
  9641. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  9642. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  9643. SemaRef.IsBuildingRecoveryCallExpr = true;
  9644. }
  9645. ~BuildRecoveryCallExprRAII() {
  9646. SemaRef.IsBuildingRecoveryCallExpr = false;
  9647. }
  9648. };
  9649. }
  9650. static std::unique_ptr<CorrectionCandidateCallback>
  9651. MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
  9652. bool HasTemplateArgs, bool AllowTypoCorrection) {
  9653. if (!AllowTypoCorrection)
  9654. return llvm::make_unique<NoTypoCorrectionCCC>();
  9655. return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
  9656. HasTemplateArgs, ME);
  9657. }
  9658. /// Attempts to recover from a call where no functions were found.
  9659. ///
  9660. /// Returns true if new candidates were found.
  9661. static ExprResult
  9662. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9663. UnresolvedLookupExpr *ULE,
  9664. SourceLocation LParenLoc,
  9665. MutableArrayRef<Expr *> Args,
  9666. SourceLocation RParenLoc,
  9667. bool EmptyLookup, bool AllowTypoCorrection) {
  9668. // Do not try to recover if it is already building a recovery call.
  9669. // This stops infinite loops for template instantiations like
  9670. //
  9671. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  9672. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  9673. //
  9674. if (SemaRef.IsBuildingRecoveryCallExpr)
  9675. return ExprError();
  9676. BuildRecoveryCallExprRAII RCE(SemaRef);
  9677. CXXScopeSpec SS;
  9678. SS.Adopt(ULE->getQualifierLoc());
  9679. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  9680. TemplateArgumentListInfo TABuffer;
  9681. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9682. if (ULE->hasExplicitTemplateArgs()) {
  9683. ULE->copyTemplateArgumentsInto(TABuffer);
  9684. ExplicitTemplateArgs = &TABuffer;
  9685. }
  9686. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  9687. Sema::LookupOrdinaryName);
  9688. bool DoDiagnoseEmptyLookup = EmptyLookup;
  9689. if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
  9690. OverloadCandidateSet::CSK_Normal,
  9691. ExplicitTemplateArgs, Args,
  9692. &DoDiagnoseEmptyLookup) &&
  9693. (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
  9694. S, SS, R,
  9695. MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
  9696. ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
  9697. ExplicitTemplateArgs, Args)))
  9698. return ExprError();
  9699. assert(!R.empty() && "lookup results empty despite recovery");
  9700. // Build an implicit member call if appropriate. Just drop the
  9701. // casts and such from the call, we don't really care.
  9702. ExprResult NewFn = ExprError();
  9703. if ((*R.begin())->isCXXClassMember())
  9704. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  9705. R, ExplicitTemplateArgs);
  9706. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  9707. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  9708. ExplicitTemplateArgs);
  9709. else
  9710. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  9711. if (NewFn.isInvalid())
  9712. return ExprError();
  9713. // This shouldn't cause an infinite loop because we're giving it
  9714. // an expression with viable lookup results, which should never
  9715. // end up here.
  9716. return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  9717. MultiExprArg(Args.data(), Args.size()),
  9718. RParenLoc);
  9719. }
  9720. /// \brief Constructs and populates an OverloadedCandidateSet from
  9721. /// the given function.
  9722. /// \returns true when an the ExprResult output parameter has been set.
  9723. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  9724. UnresolvedLookupExpr *ULE,
  9725. MultiExprArg Args,
  9726. SourceLocation RParenLoc,
  9727. OverloadCandidateSet *CandidateSet,
  9728. ExprResult *Result) {
  9729. #ifndef NDEBUG
  9730. if (ULE->requiresADL()) {
  9731. // To do ADL, we must have found an unqualified name.
  9732. assert(!ULE->getQualifier() && "qualified name with ADL");
  9733. // We don't perform ADL for implicit declarations of builtins.
  9734. // Verify that this was correctly set up.
  9735. FunctionDecl *F;
  9736. if (ULE->decls_begin() + 1 == ULE->decls_end() &&
  9737. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  9738. F->getBuiltinID() && F->isImplicit())
  9739. llvm_unreachable("performing ADL for builtin");
  9740. // We don't perform ADL in C.
  9741. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  9742. }
  9743. #endif
  9744. UnbridgedCastsSet UnbridgedCasts;
  9745. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  9746. *Result = ExprError();
  9747. return true;
  9748. }
  9749. // Add the functions denoted by the callee to the set of candidate
  9750. // functions, including those from argument-dependent lookup.
  9751. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  9752. if (getLangOpts().MSVCCompat &&
  9753. CurContext->isDependentContext() && !isSFINAEContext() &&
  9754. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  9755. OverloadCandidateSet::iterator Best;
  9756. if (CandidateSet->empty() ||
  9757. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
  9758. OR_No_Viable_Function) {
  9759. // In Microsoft mode, if we are inside a template class member function then
  9760. // create a type dependent CallExpr. The goal is to postpone name lookup
  9761. // to instantiation time to be able to search into type dependent base
  9762. // classes.
  9763. CallExpr *CE = new (Context) CallExpr(
  9764. Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
  9765. CE->setTypeDependent(true);
  9766. *Result = CE;
  9767. return true;
  9768. }
  9769. }
  9770. if (CandidateSet->empty())
  9771. return false;
  9772. UnbridgedCasts.restore();
  9773. return false;
  9774. }
  9775. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  9776. /// the completed call expression. If overload resolution fails, emits
  9777. /// diagnostics and returns ExprError()
  9778. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9779. UnresolvedLookupExpr *ULE,
  9780. SourceLocation LParenLoc,
  9781. MultiExprArg Args,
  9782. SourceLocation RParenLoc,
  9783. Expr *ExecConfig,
  9784. OverloadCandidateSet *CandidateSet,
  9785. OverloadCandidateSet::iterator *Best,
  9786. OverloadingResult OverloadResult,
  9787. bool AllowTypoCorrection) {
  9788. if (CandidateSet->empty())
  9789. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  9790. RParenLoc, /*EmptyLookup=*/true,
  9791. AllowTypoCorrection);
  9792. switch (OverloadResult) {
  9793. case OR_Success: {
  9794. FunctionDecl *FDecl = (*Best)->Function;
  9795. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  9796. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  9797. return ExprError();
  9798. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9799. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9800. ExecConfig);
  9801. }
  9802. case OR_No_Viable_Function: {
  9803. // Try to recover by looking for viable functions which the user might
  9804. // have meant to call.
  9805. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  9806. Args, RParenLoc,
  9807. /*EmptyLookup=*/false,
  9808. AllowTypoCorrection);
  9809. if (!Recovery.isInvalid())
  9810. return Recovery;
  9811. SemaRef.Diag(Fn->getLocStart(),
  9812. diag::err_ovl_no_viable_function_in_call)
  9813. << ULE->getName() << Fn->getSourceRange();
  9814. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9815. break;
  9816. }
  9817. case OR_Ambiguous:
  9818. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
  9819. << ULE->getName() << Fn->getSourceRange();
  9820. CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
  9821. break;
  9822. case OR_Deleted: {
  9823. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
  9824. << (*Best)->Function->isDeleted()
  9825. << ULE->getName()
  9826. << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
  9827. << Fn->getSourceRange();
  9828. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9829. // We emitted an error for the unvailable/deleted function call but keep
  9830. // the call in the AST.
  9831. FunctionDecl *FDecl = (*Best)->Function;
  9832. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9833. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9834. ExecConfig);
  9835. }
  9836. }
  9837. // Overload resolution failed.
  9838. return ExprError();
  9839. }
  9840. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  9841. /// (which eventually refers to the declaration Func) and the call
  9842. /// arguments Args/NumArgs, attempt to resolve the function call down
  9843. /// to a specific function. If overload resolution succeeds, returns
  9844. /// the call expression produced by overload resolution.
  9845. /// Otherwise, emits diagnostics and returns ExprError.
  9846. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  9847. UnresolvedLookupExpr *ULE,
  9848. SourceLocation LParenLoc,
  9849. MultiExprArg Args,
  9850. SourceLocation RParenLoc,
  9851. Expr *ExecConfig,
  9852. bool AllowTypoCorrection) {
  9853. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  9854. OverloadCandidateSet::CSK_Normal);
  9855. ExprResult result;
  9856. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  9857. &result))
  9858. return result;
  9859. OverloadCandidateSet::iterator Best;
  9860. OverloadingResult OverloadResult =
  9861. CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
  9862. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
  9863. RParenLoc, ExecConfig, &CandidateSet,
  9864. &Best, OverloadResult,
  9865. AllowTypoCorrection);
  9866. }
  9867. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  9868. return Functions.size() > 1 ||
  9869. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  9870. }
  9871. /// \brief Create a unary operation that may resolve to an overloaded
  9872. /// operator.
  9873. ///
  9874. /// \param OpLoc The location of the operator itself (e.g., '*').
  9875. ///
  9876. /// \param OpcIn The UnaryOperator::Opcode that describes this
  9877. /// operator.
  9878. ///
  9879. /// \param Fns The set of non-member functions that will be
  9880. /// considered by overload resolution. The caller needs to build this
  9881. /// set based on the context using, e.g.,
  9882. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  9883. /// set should not contain any member functions; those will be added
  9884. /// by CreateOverloadedUnaryOp().
  9885. ///
  9886. /// \param Input The input argument.
  9887. ExprResult
  9888. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
  9889. const UnresolvedSetImpl &Fns,
  9890. Expr *Input) {
  9891. UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
  9892. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  9893. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  9894. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  9895. // TODO: provide better source location info.
  9896. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  9897. if (checkPlaceholderForOverload(*this, Input))
  9898. return ExprError();
  9899. Expr *Args[2] = { Input, nullptr };
  9900. unsigned NumArgs = 1;
  9901. // For post-increment and post-decrement, add the implicit '0' as
  9902. // the second argument, so that we know this is a post-increment or
  9903. // post-decrement.
  9904. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  9905. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  9906. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  9907. SourceLocation());
  9908. NumArgs = 2;
  9909. }
  9910. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  9911. if (Input->isTypeDependent()) {
  9912. if (Fns.empty())
  9913. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  9914. VK_RValue, OK_Ordinary, OpLoc);
  9915. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  9916. UnresolvedLookupExpr *Fn
  9917. = UnresolvedLookupExpr::Create(Context, NamingClass,
  9918. NestedNameSpecifierLoc(), OpNameInfo,
  9919. /*ADL*/ true, IsOverloaded(Fns),
  9920. Fns.begin(), Fns.end());
  9921. return new (Context)
  9922. CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
  9923. VK_RValue, OpLoc, false);
  9924. }
  9925. // Build an empty overload set.
  9926. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  9927. // Add the candidates from the given function set.
  9928. AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
  9929. // Add operator candidates that are member functions.
  9930. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9931. // Add candidates from ADL.
  9932. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  9933. /*ExplicitTemplateArgs*/nullptr,
  9934. CandidateSet);
  9935. // Add builtin operator candidates.
  9936. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9937. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9938. // Perform overload resolution.
  9939. OverloadCandidateSet::iterator Best;
  9940. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  9941. case OR_Success: {
  9942. // We found a built-in operator or an overloaded operator.
  9943. FunctionDecl *FnDecl = Best->Function;
  9944. if (FnDecl) {
  9945. // We matched an overloaded operator. Build a call to that
  9946. // operator.
  9947. // Convert the arguments.
  9948. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  9949. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  9950. ExprResult InputRes =
  9951. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  9952. Best->FoundDecl, Method);
  9953. if (InputRes.isInvalid())
  9954. return ExprError();
  9955. Input = InputRes.get();
  9956. } else {
  9957. // Convert the arguments.
  9958. ExprResult InputInit
  9959. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  9960. Context,
  9961. FnDecl->getParamDecl(0)),
  9962. SourceLocation(),
  9963. Input);
  9964. if (InputInit.isInvalid())
  9965. return ExprError();
  9966. Input = InputInit.get();
  9967. }
  9968. // Build the actual expression node.
  9969. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  9970. HadMultipleCandidates, OpLoc);
  9971. if (FnExpr.isInvalid())
  9972. return ExprError();
  9973. // Determine the result type.
  9974. QualType ResultTy = FnDecl->getReturnType();
  9975. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9976. ResultTy = ResultTy.getNonLValueExprType(Context);
  9977. Args[0] = Input;
  9978. CallExpr *TheCall =
  9979. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
  9980. ResultTy, VK, OpLoc, false);
  9981. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  9982. return ExprError();
  9983. return MaybeBindToTemporary(TheCall);
  9984. } else {
  9985. // We matched a built-in operator. Convert the arguments, then
  9986. // break out so that we will build the appropriate built-in
  9987. // operator node.
  9988. ExprResult InputRes =
  9989. PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
  9990. Best->Conversions[0], AA_Passing);
  9991. if (InputRes.isInvalid())
  9992. return ExprError();
  9993. Input = InputRes.get();
  9994. break;
  9995. }
  9996. }
  9997. case OR_No_Viable_Function:
  9998. // This is an erroneous use of an operator which can be overloaded by
  9999. // a non-member function. Check for non-member operators which were
  10000. // defined too late to be candidates.
  10001. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  10002. // FIXME: Recover by calling the found function.
  10003. return ExprError();
  10004. // No viable function; fall through to handling this as a
  10005. // built-in operator, which will produce an error message for us.
  10006. break;
  10007. case OR_Ambiguous:
  10008. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10009. << UnaryOperator::getOpcodeStr(Opc)
  10010. << Input->getType()
  10011. << Input->getSourceRange();
  10012. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
  10013. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10014. return ExprError();
  10015. case OR_Deleted:
  10016. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10017. << Best->Function->isDeleted()
  10018. << UnaryOperator::getOpcodeStr(Opc)
  10019. << getDeletedOrUnavailableSuffix(Best->Function)
  10020. << Input->getSourceRange();
  10021. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
  10022. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10023. return ExprError();
  10024. }
  10025. // Either we found no viable overloaded operator or we matched a
  10026. // built-in operator. In either case, fall through to trying to
  10027. // build a built-in operation.
  10028. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10029. }
  10030. /// \brief Create a binary operation that may resolve to an overloaded
  10031. /// operator.
  10032. ///
  10033. /// \param OpLoc The location of the operator itself (e.g., '+').
  10034. ///
  10035. /// \param OpcIn The BinaryOperator::Opcode that describes this
  10036. /// operator.
  10037. ///
  10038. /// \param Fns The set of non-member functions that will be
  10039. /// considered by overload resolution. The caller needs to build this
  10040. /// set based on the context using, e.g.,
  10041. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  10042. /// set should not contain any member functions; those will be added
  10043. /// by CreateOverloadedBinOp().
  10044. ///
  10045. /// \param LHS Left-hand argument.
  10046. /// \param RHS Right-hand argument.
  10047. ExprResult
  10048. Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  10049. unsigned OpcIn,
  10050. const UnresolvedSetImpl &Fns,
  10051. Expr *LHS, Expr *RHS) {
  10052. Expr *Args[2] = { LHS, RHS };
  10053. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  10054. BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
  10055. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  10056. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  10057. // If either side is type-dependent, create an appropriate dependent
  10058. // expression.
  10059. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10060. if (Fns.empty()) {
  10061. // If there are no functions to store, just build a dependent
  10062. // BinaryOperator or CompoundAssignment.
  10063. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  10064. return new (Context) BinaryOperator(
  10065. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  10066. OpLoc, FPFeatures.fp_contract);
  10067. return new (Context) CompoundAssignOperator(
  10068. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  10069. Context.DependentTy, Context.DependentTy, OpLoc,
  10070. FPFeatures.fp_contract);
  10071. }
  10072. // FIXME: save results of ADL from here?
  10073. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10074. // TODO: provide better source location info in DNLoc component.
  10075. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  10076. UnresolvedLookupExpr *Fn
  10077. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10078. NestedNameSpecifierLoc(), OpNameInfo,
  10079. /*ADL*/ true, IsOverloaded(Fns),
  10080. Fns.begin(), Fns.end());
  10081. return new (Context)
  10082. CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
  10083. VK_RValue, OpLoc, FPFeatures.fp_contract);
  10084. }
  10085. // Always do placeholder-like conversions on the RHS.
  10086. if (checkPlaceholderForOverload(*this, Args[1]))
  10087. return ExprError();
  10088. // Do placeholder-like conversion on the LHS; note that we should
  10089. // not get here with a PseudoObject LHS.
  10090. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  10091. if (checkPlaceholderForOverload(*this, Args[0]))
  10092. return ExprError();
  10093. // If this is the assignment operator, we only perform overload resolution
  10094. // if the left-hand side is a class or enumeration type. This is actually
  10095. // a hack. The standard requires that we do overload resolution between the
  10096. // various built-in candidates, but as DR507 points out, this can lead to
  10097. // problems. So we do it this way, which pretty much follows what GCC does.
  10098. // Note that we go the traditional code path for compound assignment forms.
  10099. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  10100. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10101. // If this is the .* operator, which is not overloadable, just
  10102. // create a built-in binary operator.
  10103. if (Opc == BO_PtrMemD)
  10104. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10105. // Build an empty overload set.
  10106. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  10107. // Add the candidates from the given function set.
  10108. AddFunctionCandidates(Fns, Args, CandidateSet);
  10109. // Add operator candidates that are member functions.
  10110. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10111. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  10112. // performed for an assignment operator (nor for operator[] nor operator->,
  10113. // which don't get here).
  10114. if (Opc != BO_Assign)
  10115. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  10116. /*ExplicitTemplateArgs*/ nullptr,
  10117. CandidateSet);
  10118. // Add builtin operator candidates.
  10119. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10120. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10121. // Perform overload resolution.
  10122. OverloadCandidateSet::iterator Best;
  10123. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10124. case OR_Success: {
  10125. // We found a built-in operator or an overloaded operator.
  10126. FunctionDecl *FnDecl = Best->Function;
  10127. if (FnDecl) {
  10128. // We matched an overloaded operator. Build a call to that
  10129. // operator.
  10130. // Convert the arguments.
  10131. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  10132. // Best->Access is only meaningful for class members.
  10133. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  10134. ExprResult Arg1 =
  10135. PerformCopyInitialization(
  10136. InitializedEntity::InitializeParameter(Context,
  10137. FnDecl->getParamDecl(0)),
  10138. SourceLocation(), Args[1]);
  10139. if (Arg1.isInvalid())
  10140. return ExprError();
  10141. ExprResult Arg0 =
  10142. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10143. Best->FoundDecl, Method);
  10144. if (Arg0.isInvalid())
  10145. return ExprError();
  10146. Args[0] = Arg0.getAs<Expr>();
  10147. Args[1] = RHS = Arg1.getAs<Expr>();
  10148. } else {
  10149. // Convert the arguments.
  10150. ExprResult Arg0 = PerformCopyInitialization(
  10151. InitializedEntity::InitializeParameter(Context,
  10152. FnDecl->getParamDecl(0)),
  10153. SourceLocation(), Args[0]);
  10154. if (Arg0.isInvalid())
  10155. return ExprError();
  10156. ExprResult Arg1 =
  10157. PerformCopyInitialization(
  10158. InitializedEntity::InitializeParameter(Context,
  10159. FnDecl->getParamDecl(1)),
  10160. SourceLocation(), Args[1]);
  10161. if (Arg1.isInvalid())
  10162. return ExprError();
  10163. Args[0] = LHS = Arg0.getAs<Expr>();
  10164. Args[1] = RHS = Arg1.getAs<Expr>();
  10165. }
  10166. // Build the actual expression node.
  10167. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10168. Best->FoundDecl,
  10169. HadMultipleCandidates, OpLoc);
  10170. if (FnExpr.isInvalid())
  10171. return ExprError();
  10172. // Determine the result type.
  10173. QualType ResultTy = FnDecl->getReturnType();
  10174. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10175. ResultTy = ResultTy.getNonLValueExprType(Context);
  10176. CXXOperatorCallExpr *TheCall =
  10177. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
  10178. Args, ResultTy, VK, OpLoc,
  10179. FPFeatures.fp_contract);
  10180. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  10181. FnDecl))
  10182. return ExprError();
  10183. ArrayRef<const Expr *> ArgsArray(Args, 2);
  10184. // Cut off the implicit 'this'.
  10185. if (isa<CXXMethodDecl>(FnDecl))
  10186. ArgsArray = ArgsArray.slice(1);
  10187. // Check for a self move.
  10188. if (Op == OO_Equal)
  10189. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  10190. checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
  10191. TheCall->getSourceRange(), VariadicDoesNotApply);
  10192. return MaybeBindToTemporary(TheCall);
  10193. } else {
  10194. // We matched a built-in operator. Convert the arguments, then
  10195. // break out so that we will build the appropriate built-in
  10196. // operator node.
  10197. ExprResult ArgsRes0 =
  10198. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10199. Best->Conversions[0], AA_Passing);
  10200. if (ArgsRes0.isInvalid())
  10201. return ExprError();
  10202. Args[0] = ArgsRes0.get();
  10203. ExprResult ArgsRes1 =
  10204. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10205. Best->Conversions[1], AA_Passing);
  10206. if (ArgsRes1.isInvalid())
  10207. return ExprError();
  10208. Args[1] = ArgsRes1.get();
  10209. break;
  10210. }
  10211. }
  10212. case OR_No_Viable_Function: {
  10213. // C++ [over.match.oper]p9:
  10214. // If the operator is the operator , [...] and there are no
  10215. // viable functions, then the operator is assumed to be the
  10216. // built-in operator and interpreted according to clause 5.
  10217. if (Opc == BO_Comma)
  10218. break;
  10219. // For class as left operand for assignment or compound assigment
  10220. // operator do not fall through to handling in built-in, but report that
  10221. // no overloaded assignment operator found
  10222. ExprResult Result = ExprError();
  10223. if (Args[0]->getType()->isRecordType() &&
  10224. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  10225. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10226. << BinaryOperator::getOpcodeStr(Opc)
  10227. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10228. if (Args[0]->getType()->isIncompleteType()) {
  10229. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  10230. << Args[0]->getType()
  10231. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10232. }
  10233. } else {
  10234. // This is an erroneous use of an operator which can be overloaded by
  10235. // a non-member function. Check for non-member operators which were
  10236. // defined too late to be candidates.
  10237. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  10238. // FIXME: Recover by calling the found function.
  10239. return ExprError();
  10240. // No viable function; try to create a built-in operation, which will
  10241. // produce an error. Then, show the non-viable candidates.
  10242. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10243. }
  10244. assert(Result.isInvalid() &&
  10245. "C++ binary operator overloading is missing candidates!");
  10246. if (Result.isInvalid())
  10247. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10248. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10249. return Result;
  10250. }
  10251. case OR_Ambiguous:
  10252. Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
  10253. << BinaryOperator::getOpcodeStr(Opc)
  10254. << Args[0]->getType() << Args[1]->getType()
  10255. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10256. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10257. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10258. return ExprError();
  10259. case OR_Deleted:
  10260. if (isImplicitlyDeleted(Best->Function)) {
  10261. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10262. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  10263. << Context.getRecordType(Method->getParent())
  10264. << getSpecialMember(Method);
  10265. // The user probably meant to call this special member. Just
  10266. // explain why it's deleted.
  10267. NoteDeletedFunction(Method);
  10268. return ExprError();
  10269. } else {
  10270. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10271. << Best->Function->isDeleted()
  10272. << BinaryOperator::getOpcodeStr(Opc)
  10273. << getDeletedOrUnavailableSuffix(Best->Function)
  10274. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10275. }
  10276. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10277. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10278. return ExprError();
  10279. }
  10280. // We matched a built-in operator; build it.
  10281. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10282. }
  10283. ExprResult
  10284. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  10285. SourceLocation RLoc,
  10286. Expr *Base, Expr *Idx) {
  10287. Expr *Args[2] = { Base, Idx };
  10288. DeclarationName OpName =
  10289. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  10290. // If either side is type-dependent, create an appropriate dependent
  10291. // expression.
  10292. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10293. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10294. // CHECKME: no 'operator' keyword?
  10295. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  10296. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10297. UnresolvedLookupExpr *Fn
  10298. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10299. NestedNameSpecifierLoc(), OpNameInfo,
  10300. /*ADL*/ true, /*Overloaded*/ false,
  10301. UnresolvedSetIterator(),
  10302. UnresolvedSetIterator());
  10303. // Can't add any actual overloads yet
  10304. return new (Context)
  10305. CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
  10306. Context.DependentTy, VK_RValue, RLoc, false);
  10307. }
  10308. // Handle placeholders on both operands.
  10309. if (checkPlaceholderForOverload(*this, Args[0]))
  10310. return ExprError();
  10311. if (checkPlaceholderForOverload(*this, Args[1]))
  10312. return ExprError();
  10313. // Build an empty overload set.
  10314. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  10315. // Subscript can only be overloaded as a member function.
  10316. // Add operator candidates that are member functions.
  10317. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10318. // Add builtin operator candidates.
  10319. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10320. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10321. // Perform overload resolution.
  10322. OverloadCandidateSet::iterator Best;
  10323. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  10324. case OR_Success: {
  10325. // We found a built-in operator or an overloaded operator.
  10326. FunctionDecl *FnDecl = Best->Function;
  10327. if (FnDecl) {
  10328. // We matched an overloaded operator. Build a call to that
  10329. // operator.
  10330. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  10331. // Convert the arguments.
  10332. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  10333. ExprResult Arg0 =
  10334. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10335. Best->FoundDecl, Method);
  10336. if (Arg0.isInvalid())
  10337. return ExprError();
  10338. Args[0] = Arg0.get();
  10339. // Convert the arguments.
  10340. ExprResult InputInit
  10341. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10342. Context,
  10343. FnDecl->getParamDecl(0)),
  10344. SourceLocation(),
  10345. Args[1]);
  10346. if (InputInit.isInvalid())
  10347. return ExprError();
  10348. Args[1] = InputInit.getAs<Expr>();
  10349. // Build the actual expression node.
  10350. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  10351. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10352. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10353. Best->FoundDecl,
  10354. HadMultipleCandidates,
  10355. OpLocInfo.getLoc(),
  10356. OpLocInfo.getInfo());
  10357. if (FnExpr.isInvalid())
  10358. return ExprError();
  10359. // Determine the result type
  10360. QualType ResultTy = FnDecl->getReturnType();
  10361. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10362. ResultTy = ResultTy.getNonLValueExprType(Context);
  10363. CXXOperatorCallExpr *TheCall =
  10364. new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
  10365. FnExpr.get(), Args,
  10366. ResultTy, VK, RLoc,
  10367. false);
  10368. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  10369. return ExprError();
  10370. return MaybeBindToTemporary(TheCall);
  10371. } else {
  10372. // We matched a built-in operator. Convert the arguments, then
  10373. // break out so that we will build the appropriate built-in
  10374. // operator node.
  10375. ExprResult ArgsRes0 =
  10376. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10377. Best->Conversions[0], AA_Passing);
  10378. if (ArgsRes0.isInvalid())
  10379. return ExprError();
  10380. Args[0] = ArgsRes0.get();
  10381. ExprResult ArgsRes1 =
  10382. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10383. Best->Conversions[1], AA_Passing);
  10384. if (ArgsRes1.isInvalid())
  10385. return ExprError();
  10386. Args[1] = ArgsRes1.get();
  10387. break;
  10388. }
  10389. }
  10390. case OR_No_Viable_Function: {
  10391. if (CandidateSet.empty())
  10392. Diag(LLoc, diag::err_ovl_no_oper)
  10393. << Args[0]->getType() << /*subscript*/ 0
  10394. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10395. else
  10396. Diag(LLoc, diag::err_ovl_no_viable_subscript)
  10397. << Args[0]->getType()
  10398. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10399. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10400. "[]", LLoc);
  10401. return ExprError();
  10402. }
  10403. case OR_Ambiguous:
  10404. Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
  10405. << "[]"
  10406. << Args[0]->getType() << Args[1]->getType()
  10407. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10408. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10409. "[]", LLoc);
  10410. return ExprError();
  10411. case OR_Deleted:
  10412. Diag(LLoc, diag::err_ovl_deleted_oper)
  10413. << Best->Function->isDeleted() << "[]"
  10414. << getDeletedOrUnavailableSuffix(Best->Function)
  10415. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10416. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10417. "[]", LLoc);
  10418. return ExprError();
  10419. }
  10420. // We matched a built-in operator; build it.
  10421. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  10422. }
  10423. /// BuildCallToMemberFunction - Build a call to a member
  10424. /// function. MemExpr is the expression that refers to the member
  10425. /// function (and includes the object parameter), Args/NumArgs are the
  10426. /// arguments to the function call (not including the object
  10427. /// parameter). The caller needs to validate that the member
  10428. /// expression refers to a non-static member function or an overloaded
  10429. /// member function.
  10430. ExprResult
  10431. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  10432. SourceLocation LParenLoc,
  10433. MultiExprArg Args,
  10434. SourceLocation RParenLoc) {
  10435. assert(MemExprE->getType() == Context.BoundMemberTy ||
  10436. MemExprE->getType() == Context.OverloadTy);
  10437. // Dig out the member expression. This holds both the object
  10438. // argument and the member function we're referring to.
  10439. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  10440. // Determine whether this is a call to a pointer-to-member function.
  10441. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  10442. assert(op->getType() == Context.BoundMemberTy);
  10443. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  10444. QualType fnType =
  10445. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  10446. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  10447. QualType resultType = proto->getCallResultType(Context);
  10448. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  10449. // Check that the object type isn't more qualified than the
  10450. // member function we're calling.
  10451. Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
  10452. QualType objectType = op->getLHS()->getType();
  10453. if (op->getOpcode() == BO_PtrMemI)
  10454. objectType = objectType->castAs<PointerType>()->getPointeeType();
  10455. Qualifiers objectQuals = objectType.getQualifiers();
  10456. Qualifiers difference = objectQuals - funcQuals;
  10457. difference.removeObjCGCAttr();
  10458. difference.removeAddressSpace();
  10459. if (difference) {
  10460. std::string qualsString = difference.getAsString();
  10461. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  10462. << fnType.getUnqualifiedType()
  10463. << qualsString
  10464. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  10465. }
  10466. if (resultType->isMemberPointerType())
  10467. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10468. RequireCompleteType(LParenLoc, resultType, 0);
  10469. CXXMemberCallExpr *call
  10470. = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10471. resultType, valueKind, RParenLoc);
  10472. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
  10473. call, nullptr))
  10474. return ExprError();
  10475. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  10476. return ExprError();
  10477. if (CheckOtherCall(call, proto))
  10478. return ExprError();
  10479. return MaybeBindToTemporary(call);
  10480. }
  10481. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  10482. return new (Context)
  10483. CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
  10484. UnbridgedCastsSet UnbridgedCasts;
  10485. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10486. return ExprError();
  10487. MemberExpr *MemExpr;
  10488. CXXMethodDecl *Method = nullptr;
  10489. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  10490. NestedNameSpecifier *Qualifier = nullptr;
  10491. if (isa<MemberExpr>(NakedMemExpr)) {
  10492. MemExpr = cast<MemberExpr>(NakedMemExpr);
  10493. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  10494. FoundDecl = MemExpr->getFoundDecl();
  10495. Qualifier = MemExpr->getQualifier();
  10496. UnbridgedCasts.restore();
  10497. } else {
  10498. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  10499. Qualifier = UnresExpr->getQualifier();
  10500. QualType ObjectType = UnresExpr->getBaseType();
  10501. Expr::Classification ObjectClassification
  10502. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  10503. : UnresExpr->getBase()->Classify(Context);
  10504. // Add overload candidates
  10505. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  10506. OverloadCandidateSet::CSK_Normal);
  10507. // FIXME: avoid copy.
  10508. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  10509. if (UnresExpr->hasExplicitTemplateArgs()) {
  10510. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  10511. TemplateArgs = &TemplateArgsBuffer;
  10512. }
  10513. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  10514. E = UnresExpr->decls_end(); I != E; ++I) {
  10515. NamedDecl *Func = *I;
  10516. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  10517. if (isa<UsingShadowDecl>(Func))
  10518. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  10519. // Microsoft supports direct constructor calls.
  10520. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  10521. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
  10522. Args, CandidateSet);
  10523. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  10524. // If explicit template arguments were provided, we can't call a
  10525. // non-template member function.
  10526. if (TemplateArgs)
  10527. continue;
  10528. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  10529. ObjectClassification, Args, CandidateSet,
  10530. /*SuppressUserConversions=*/false);
  10531. } else {
  10532. AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
  10533. I.getPair(), ActingDC, TemplateArgs,
  10534. ObjectType, ObjectClassification,
  10535. Args, CandidateSet,
  10536. /*SuppressUsedConversions=*/false);
  10537. }
  10538. }
  10539. DeclarationName DeclName = UnresExpr->getMemberName();
  10540. UnbridgedCasts.restore();
  10541. OverloadCandidateSet::iterator Best;
  10542. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
  10543. Best)) {
  10544. case OR_Success:
  10545. Method = cast<CXXMethodDecl>(Best->Function);
  10546. FoundDecl = Best->FoundDecl;
  10547. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  10548. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  10549. return ExprError();
  10550. // If FoundDecl is different from Method (such as if one is a template
  10551. // and the other a specialization), make sure DiagnoseUseOfDecl is
  10552. // called on both.
  10553. // FIXME: This would be more comprehensively addressed by modifying
  10554. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  10555. // being used.
  10556. if (Method != FoundDecl.getDecl() &&
  10557. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  10558. return ExprError();
  10559. break;
  10560. case OR_No_Viable_Function:
  10561. Diag(UnresExpr->getMemberLoc(),
  10562. diag::err_ovl_no_viable_member_function_in_call)
  10563. << DeclName << MemExprE->getSourceRange();
  10564. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, StringRef(), UnresExpr->getMemberLoc()); // HLSL Change - add member loc
  10565. // FIXME: Leaking incoming expressions!
  10566. return ExprError();
  10567. case OR_Ambiguous:
  10568. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
  10569. << DeclName << MemExprE->getSourceRange();
  10570. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10571. // FIXME: Leaking incoming expressions!
  10572. return ExprError();
  10573. case OR_Deleted:
  10574. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
  10575. << Best->Function->isDeleted()
  10576. << DeclName
  10577. << getDeletedOrUnavailableSuffix(Best->Function)
  10578. << MemExprE->getSourceRange();
  10579. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10580. // FIXME: Leaking incoming expressions!
  10581. return ExprError();
  10582. }
  10583. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  10584. // If overload resolution picked a static member, build a
  10585. // non-member call based on that function.
  10586. if (Method->isStatic()) {
  10587. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  10588. RParenLoc);
  10589. }
  10590. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  10591. }
  10592. QualType ResultType = Method->getReturnType();
  10593. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  10594. ResultType = ResultType.getNonLValueExprType(Context);
  10595. assert(Method && "Member call to something that isn't a method?");
  10596. CXXMemberCallExpr *TheCall =
  10597. new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10598. ResultType, VK, RParenLoc);
  10599. // (CUDA B.1): Check for invalid calls between targets.
  10600. if (getLangOpts().CUDA) {
  10601. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
  10602. if (CheckCUDATarget(Caller, Method)) {
  10603. Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
  10604. << IdentifyCUDATarget(Method) << Method->getIdentifier()
  10605. << IdentifyCUDATarget(Caller);
  10606. return ExprError();
  10607. }
  10608. }
  10609. }
  10610. // Check for a valid return type.
  10611. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  10612. TheCall, Method))
  10613. return ExprError();
  10614. // Convert the object argument (for a non-static member function call).
  10615. // We only need to do this if there was actually an overload; otherwise
  10616. // it was done at lookup.
  10617. if (!Method->isStatic()) {
  10618. ExprResult ObjectArg =
  10619. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  10620. FoundDecl, Method);
  10621. if (ObjectArg.isInvalid())
  10622. return ExprError();
  10623. MemExpr->setBase(ObjectArg.get());
  10624. }
  10625. // Convert the rest of the arguments
  10626. const FunctionProtoType *Proto =
  10627. Method->getType()->getAs<FunctionProtoType>();
  10628. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  10629. RParenLoc))
  10630. return ExprError();
  10631. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10632. if (CheckFunctionCall(Method, TheCall, Proto))
  10633. return ExprError();
  10634. if ((isa<CXXConstructorDecl>(CurContext) ||
  10635. isa<CXXDestructorDecl>(CurContext)) &&
  10636. TheCall->getMethodDecl()->isPure()) {
  10637. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  10638. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
  10639. Diag(MemExpr->getLocStart(),
  10640. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  10641. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  10642. << MD->getParent()->getDeclName();
  10643. Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
  10644. }
  10645. }
  10646. return MaybeBindToTemporary(TheCall);
  10647. }
  10648. /// BuildCallToObjectOfClassType - Build a call to an object of class
  10649. /// type (C++ [over.call.object]), which can end up invoking an
  10650. /// overloaded function call operator (@c operator()) or performing a
  10651. /// user-defined conversion on the object argument.
  10652. ExprResult
  10653. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  10654. SourceLocation LParenLoc,
  10655. MultiExprArg Args,
  10656. SourceLocation RParenLoc) {
  10657. if (checkPlaceholderForOverload(*this, Obj))
  10658. return ExprError();
  10659. ExprResult Object = Obj;
  10660. UnbridgedCastsSet UnbridgedCasts;
  10661. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10662. return ExprError();
  10663. assert(Object.get()->getType()->isRecordType() &&
  10664. "Requires object type argument");
  10665. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  10666. // C++ [over.call.object]p1:
  10667. // If the primary-expression E in the function call syntax
  10668. // evaluates to a class object of type "cv T", then the set of
  10669. // candidate functions includes at least the function call
  10670. // operators of T. The function call operators of T are obtained by
  10671. // ordinary lookup of the name operator() in the context of
  10672. // (E).operator().
  10673. OverloadCandidateSet CandidateSet(LParenLoc,
  10674. OverloadCandidateSet::CSK_Operator);
  10675. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  10676. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  10677. diag::err_incomplete_object_call, Object.get()))
  10678. return true;
  10679. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  10680. LookupQualifiedName(R, Record->getDecl());
  10681. R.suppressDiagnostics();
  10682. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10683. Oper != OperEnd; ++Oper) {
  10684. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  10685. Object.get()->Classify(Context),
  10686. Args, CandidateSet,
  10687. /*SuppressUserConversions=*/ false);
  10688. }
  10689. // C++ [over.call.object]p2:
  10690. // In addition, for each (non-explicit in C++0x) conversion function
  10691. // declared in T of the form
  10692. //
  10693. // operator conversion-type-id () cv-qualifier;
  10694. //
  10695. // where cv-qualifier is the same cv-qualification as, or a
  10696. // greater cv-qualification than, cv, and where conversion-type-id
  10697. // denotes the type "pointer to function of (P1,...,Pn) returning
  10698. // R", or the type "reference to pointer to function of
  10699. // (P1,...,Pn) returning R", or the type "reference to function
  10700. // of (P1,...,Pn) returning R", a surrogate call function [...]
  10701. // is also considered as a candidate function. Similarly,
  10702. // surrogate call functions are added to the set of candidate
  10703. // functions for each conversion function declared in an
  10704. // accessible base class provided the function is not hidden
  10705. // within T by another intervening declaration.
  10706. const auto &Conversions =
  10707. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  10708. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  10709. NamedDecl *D = *I;
  10710. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  10711. if (isa<UsingShadowDecl>(D))
  10712. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  10713. // Skip over templated conversion functions; they aren't
  10714. // surrogates.
  10715. if (isa<FunctionTemplateDecl>(D))
  10716. continue;
  10717. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  10718. if (!Conv->isExplicit()) {
  10719. // Strip the reference type (if any) and then the pointer type (if
  10720. // any) to get down to what might be a function type.
  10721. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  10722. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  10723. ConvType = ConvPtrType->getPointeeType();
  10724. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  10725. {
  10726. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  10727. Object.get(), Args, CandidateSet);
  10728. }
  10729. }
  10730. }
  10731. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10732. // Perform overload resolution.
  10733. OverloadCandidateSet::iterator Best;
  10734. switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
  10735. Best)) {
  10736. case OR_Success:
  10737. // Overload resolution succeeded; we'll build the appropriate call
  10738. // below.
  10739. break;
  10740. case OR_No_Viable_Function:
  10741. if (CandidateSet.empty())
  10742. Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
  10743. << Object.get()->getType() << /*call*/ 1
  10744. << Object.get()->getSourceRange();
  10745. else
  10746. Diag(Object.get()->getLocStart(),
  10747. diag::err_ovl_no_viable_object_call)
  10748. << Object.get()->getType() << Object.get()->getSourceRange();
  10749. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10750. break;
  10751. case OR_Ambiguous:
  10752. Diag(Object.get()->getLocStart(),
  10753. diag::err_ovl_ambiguous_object_call)
  10754. << Object.get()->getType() << Object.get()->getSourceRange();
  10755. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  10756. break;
  10757. case OR_Deleted:
  10758. Diag(Object.get()->getLocStart(),
  10759. diag::err_ovl_deleted_object_call)
  10760. << Best->Function->isDeleted()
  10761. << Object.get()->getType()
  10762. << getDeletedOrUnavailableSuffix(Best->Function)
  10763. << Object.get()->getSourceRange();
  10764. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10765. break;
  10766. }
  10767. if (Best == CandidateSet.end())
  10768. return true;
  10769. UnbridgedCasts.restore();
  10770. if (Best->Function == nullptr) {
  10771. // Since there is no function declaration, this is one of the
  10772. // surrogate candidates. Dig out the conversion function.
  10773. CXXConversionDecl *Conv
  10774. = cast<CXXConversionDecl>(
  10775. Best->Conversions[0].UserDefined.ConversionFunction);
  10776. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  10777. Best->FoundDecl);
  10778. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  10779. return ExprError();
  10780. assert(Conv == Best->FoundDecl.getDecl() &&
  10781. "Found Decl & conversion-to-functionptr should be same, right?!");
  10782. // We selected one of the surrogate functions that converts the
  10783. // object parameter to a function pointer. Perform the conversion
  10784. // on the object argument, then let ActOnCallExpr finish the job.
  10785. // Create an implicit member expr to refer to the conversion operator.
  10786. // and then call it.
  10787. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  10788. Conv, HadMultipleCandidates);
  10789. if (Call.isInvalid())
  10790. return ExprError();
  10791. // Record usage of conversion in an implicit cast.
  10792. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  10793. CK_UserDefinedConversion, Call.get(),
  10794. nullptr, VK_RValue);
  10795. return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  10796. }
  10797. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  10798. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  10799. // that calls this method, using Object for the implicit object
  10800. // parameter and passing along the remaining arguments.
  10801. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10802. // An error diagnostic has already been printed when parsing the declaration.
  10803. if (Method->isInvalidDecl())
  10804. return ExprError();
  10805. const FunctionProtoType *Proto =
  10806. Method->getType()->getAs<FunctionProtoType>();
  10807. unsigned NumParams = Proto->getNumParams();
  10808. DeclarationNameInfo OpLocInfo(
  10809. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  10810. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  10811. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10812. HadMultipleCandidates,
  10813. OpLocInfo.getLoc(),
  10814. OpLocInfo.getInfo());
  10815. if (NewFn.isInvalid())
  10816. return true;
  10817. // Build the full argument list for the method call (the implicit object
  10818. // parameter is placed at the beginning of the list).
  10819. std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
  10820. MethodArgs[0] = Object.get();
  10821. std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
  10822. // Once we've built TheCall, all of the expressions are properly
  10823. // owned.
  10824. QualType ResultTy = Method->getReturnType();
  10825. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10826. ResultTy = ResultTy.getNonLValueExprType(Context);
  10827. CXXOperatorCallExpr *TheCall = new (Context)
  10828. CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
  10829. llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
  10830. ResultTy, VK, RParenLoc, false);
  10831. MethodArgs.reset();
  10832. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  10833. return true;
  10834. // We may have default arguments. If so, we need to allocate more
  10835. // slots in the call for them.
  10836. if (Args.size() < NumParams)
  10837. TheCall->setNumArgs(Context, NumParams + 1);
  10838. bool IsError = false;
  10839. // Initialize the implicit object parameter.
  10840. ExprResult ObjRes =
  10841. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  10842. Best->FoundDecl, Method);
  10843. if (ObjRes.isInvalid())
  10844. IsError = true;
  10845. else
  10846. Object = ObjRes;
  10847. TheCall->setArg(0, Object.get());
  10848. // Check the argument types.
  10849. for (unsigned i = 0; i != NumParams; i++) {
  10850. Expr *Arg;
  10851. if (i < Args.size()) {
  10852. Arg = Args[i];
  10853. // Pass the argument.
  10854. ExprResult InputInit
  10855. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10856. Context,
  10857. Method->getParamDecl(i)),
  10858. SourceLocation(), Arg);
  10859. IsError |= InputInit.isInvalid();
  10860. Arg = InputInit.getAs<Expr>();
  10861. } else {
  10862. ExprResult DefArg
  10863. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  10864. if (DefArg.isInvalid()) {
  10865. IsError = true;
  10866. break;
  10867. }
  10868. Arg = DefArg.getAs<Expr>();
  10869. }
  10870. TheCall->setArg(i + 1, Arg);
  10871. }
  10872. // If this is a variadic call, handle args passed through "...".
  10873. if (Proto->isVariadic()) {
  10874. // Promote the arguments (C99 6.5.2.2p7).
  10875. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  10876. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  10877. nullptr);
  10878. IsError |= Arg.isInvalid();
  10879. TheCall->setArg(i + 1, Arg.get());
  10880. }
  10881. }
  10882. if (IsError) return true;
  10883. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10884. if (CheckFunctionCall(Method, TheCall, Proto))
  10885. return true;
  10886. return MaybeBindToTemporary(TheCall);
  10887. }
  10888. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  10889. /// (if one exists), where @c Base is an expression of class type and
  10890. /// @c Member is the name of the member we're trying to find.
  10891. ExprResult
  10892. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  10893. bool *NoArrowOperatorFound) {
  10894. assert(Base->getType()->isRecordType() &&
  10895. "left-hand side must have class type");
  10896. if (checkPlaceholderForOverload(*this, Base))
  10897. return ExprError();
  10898. SourceLocation Loc = Base->getExprLoc();
  10899. // C++ [over.ref]p1:
  10900. //
  10901. // [...] An expression x->m is interpreted as (x.operator->())->m
  10902. // for a class object x of type T if T::operator->() exists and if
  10903. // the operator is selected as the best match function by the
  10904. // overload resolution mechanism (13.3).
  10905. DeclarationName OpName =
  10906. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  10907. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  10908. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  10909. if (RequireCompleteType(Loc, Base->getType(),
  10910. diag::err_typecheck_incomplete_tag, Base))
  10911. return ExprError();
  10912. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  10913. LookupQualifiedName(R, BaseRecord->getDecl());
  10914. R.suppressDiagnostics();
  10915. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10916. Oper != OperEnd; ++Oper) {
  10917. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  10918. None, CandidateSet, /*SuppressUserConversions=*/false);
  10919. }
  10920. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10921. // Perform overload resolution.
  10922. OverloadCandidateSet::iterator Best;
  10923. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10924. case OR_Success:
  10925. // Overload resolution succeeded; we'll build the call below.
  10926. break;
  10927. case OR_No_Viable_Function:
  10928. if (CandidateSet.empty()) {
  10929. QualType BaseType = Base->getType();
  10930. if (NoArrowOperatorFound) {
  10931. // Report this specific error to the caller instead of emitting a
  10932. // diagnostic, as requested.
  10933. *NoArrowOperatorFound = true;
  10934. return ExprError();
  10935. }
  10936. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  10937. << BaseType << Base->getSourceRange();
  10938. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  10939. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  10940. << FixItHint::CreateReplacement(OpLoc, ".");
  10941. }
  10942. } else
  10943. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10944. << "operator->" << Base->getSourceRange();
  10945. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10946. return ExprError();
  10947. case OR_Ambiguous:
  10948. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10949. << "->" << Base->getType() << Base->getSourceRange();
  10950. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
  10951. return ExprError();
  10952. case OR_Deleted:
  10953. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10954. << Best->Function->isDeleted()
  10955. << "->"
  10956. << getDeletedOrUnavailableSuffix(Best->Function)
  10957. << Base->getSourceRange();
  10958. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10959. return ExprError();
  10960. }
  10961. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  10962. // Convert the object parameter.
  10963. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10964. ExprResult BaseResult =
  10965. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  10966. Best->FoundDecl, Method);
  10967. if (BaseResult.isInvalid())
  10968. return ExprError();
  10969. Base = BaseResult.get();
  10970. // Build the operator call.
  10971. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10972. HadMultipleCandidates, OpLoc);
  10973. if (FnExpr.isInvalid())
  10974. return ExprError();
  10975. QualType ResultTy = Method->getReturnType();
  10976. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10977. ResultTy = ResultTy.getNonLValueExprType(Context);
  10978. CXXOperatorCallExpr *TheCall =
  10979. new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
  10980. Base, ResultTy, VK, OpLoc, false);
  10981. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  10982. return ExprError();
  10983. return MaybeBindToTemporary(TheCall);
  10984. }
  10985. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  10986. /// a literal operator described by the provided lookup results.
  10987. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  10988. DeclarationNameInfo &SuffixInfo,
  10989. ArrayRef<Expr*> Args,
  10990. SourceLocation LitEndLoc,
  10991. TemplateArgumentListInfo *TemplateArgs) {
  10992. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  10993. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  10994. OverloadCandidateSet::CSK_Normal);
  10995. AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
  10996. /*SuppressUserConversions=*/true);
  10997. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10998. // Perform overload resolution. This will usually be trivial, but might need
  10999. // to perform substitutions for a literal operator template.
  11000. OverloadCandidateSet::iterator Best;
  11001. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  11002. case OR_Success:
  11003. case OR_Deleted:
  11004. break;
  11005. case OR_No_Viable_Function:
  11006. Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
  11007. << R.getLookupName();
  11008. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  11009. return ExprError();
  11010. case OR_Ambiguous:
  11011. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  11012. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  11013. return ExprError();
  11014. }
  11015. FunctionDecl *FD = Best->Function;
  11016. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  11017. HadMultipleCandidates,
  11018. SuffixInfo.getLoc(),
  11019. SuffixInfo.getInfo());
  11020. if (Fn.isInvalid())
  11021. return true;
  11022. // Check the argument types. This should almost always be a no-op, except
  11023. // that array-to-pointer decay is applied to string literals.
  11024. Expr *ConvArgs[2];
  11025. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  11026. ExprResult InputInit = PerformCopyInitialization(
  11027. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  11028. SourceLocation(), Args[ArgIdx]);
  11029. if (InputInit.isInvalid())
  11030. return true;
  11031. ConvArgs[ArgIdx] = InputInit.get();
  11032. }
  11033. QualType ResultTy = FD->getReturnType();
  11034. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11035. ResultTy = ResultTy.getNonLValueExprType(Context);
  11036. UserDefinedLiteral *UDL =
  11037. new (Context) UserDefinedLiteral(Context, Fn.get(),
  11038. llvm::makeArrayRef(ConvArgs, Args.size()),
  11039. ResultTy, VK, LitEndLoc, UDSuffixLoc);
  11040. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  11041. return ExprError();
  11042. if (CheckFunctionCall(FD, UDL, nullptr))
  11043. return ExprError();
  11044. return MaybeBindToTemporary(UDL);
  11045. }
  11046. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  11047. /// given LookupResult is non-empty, it is assumed to describe a member which
  11048. /// will be invoked. Otherwise, the function will be found via argument
  11049. /// dependent lookup.
  11050. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  11051. /// otherwise CallExpr is set to ExprError() and some non-success value
  11052. /// is returned.
  11053. Sema::ForRangeStatus
  11054. Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
  11055. SourceLocation RangeLoc, VarDecl *Decl,
  11056. BeginEndFunction BEF,
  11057. const DeclarationNameInfo &NameInfo,
  11058. LookupResult &MemberLookup,
  11059. OverloadCandidateSet *CandidateSet,
  11060. Expr *Range, ExprResult *CallExpr) {
  11061. CandidateSet->clear();
  11062. if (!MemberLookup.empty()) {
  11063. ExprResult MemberRef =
  11064. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  11065. /*IsPtr=*/false, CXXScopeSpec(),
  11066. /*TemplateKWLoc=*/SourceLocation(),
  11067. /*FirstQualifierInScope=*/nullptr,
  11068. MemberLookup,
  11069. /*TemplateArgs=*/nullptr);
  11070. if (MemberRef.isInvalid()) {
  11071. *CallExpr = ExprError();
  11072. Diag(Range->getLocStart(), diag::note_in_for_range)
  11073. << RangeLoc << BEF << Range->getType();
  11074. return FRS_DiagnosticIssued;
  11075. }
  11076. *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  11077. if (CallExpr->isInvalid()) {
  11078. *CallExpr = ExprError();
  11079. Diag(Range->getLocStart(), diag::note_in_for_range)
  11080. << RangeLoc << BEF << Range->getType();
  11081. return FRS_DiagnosticIssued;
  11082. }
  11083. } else {
  11084. UnresolvedSet<0> FoundNames;
  11085. UnresolvedLookupExpr *Fn =
  11086. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  11087. NestedNameSpecifierLoc(), NameInfo,
  11088. /*NeedsADL=*/true, /*Overloaded=*/false,
  11089. FoundNames.begin(), FoundNames.end());
  11090. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  11091. CandidateSet, CallExpr);
  11092. if (CandidateSet->empty() || CandidateSetError) {
  11093. *CallExpr = ExprError();
  11094. return FRS_NoViableFunction;
  11095. }
  11096. OverloadCandidateSet::iterator Best;
  11097. OverloadingResult OverloadResult =
  11098. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
  11099. if (OverloadResult == OR_No_Viable_Function) {
  11100. *CallExpr = ExprError();
  11101. return FRS_NoViableFunction;
  11102. }
  11103. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  11104. Loc, nullptr, CandidateSet, &Best,
  11105. OverloadResult,
  11106. /*AllowTypoCorrection=*/false);
  11107. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  11108. *CallExpr = ExprError();
  11109. Diag(Range->getLocStart(), diag::note_in_for_range)
  11110. << RangeLoc << BEF << Range->getType();
  11111. return FRS_DiagnosticIssued;
  11112. }
  11113. }
  11114. return FRS_Success;
  11115. }
  11116. /// FixOverloadedFunctionReference - E is an expression that refers to
  11117. /// a C++ overloaded function (possibly with some parentheses and
  11118. /// perhaps a '&' around it). We have resolved the overloaded function
  11119. /// to the function declaration Fn, so patch up the expression E to
  11120. /// refer (possibly indirectly) to Fn. Returns the new expr.
  11121. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  11122. FunctionDecl *Fn) {
  11123. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  11124. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  11125. Found, Fn);
  11126. if (SubExpr == PE->getSubExpr())
  11127. return PE;
  11128. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  11129. }
  11130. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  11131. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  11132. Found, Fn);
  11133. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  11134. SubExpr->getType()) &&
  11135. "Implicit cast type cannot be determined from overload");
  11136. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  11137. if (SubExpr == ICE->getSubExpr())
  11138. return ICE;
  11139. return ImplicitCastExpr::Create(Context, ICE->getType(),
  11140. ICE->getCastKind(),
  11141. SubExpr, nullptr,
  11142. ICE->getValueKind());
  11143. }
  11144. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  11145. assert(UnOp->getOpcode() == UO_AddrOf &&
  11146. "Can only take the address of an overloaded function");
  11147. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  11148. if (Method->isStatic()) {
  11149. // Do nothing: static member functions aren't any different
  11150. // from non-member functions.
  11151. } else {
  11152. // Fix the subexpression, which really has to be an
  11153. // UnresolvedLookupExpr holding an overloaded member function
  11154. // or template.
  11155. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11156. Found, Fn);
  11157. if (SubExpr == UnOp->getSubExpr())
  11158. return UnOp;
  11159. assert(isa<DeclRefExpr>(SubExpr)
  11160. && "fixed to something other than a decl ref");
  11161. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  11162. && "fixed to a member ref with no nested name qualifier");
  11163. // We have taken the address of a pointer to member
  11164. // function. Perform the computation here so that we get the
  11165. // appropriate pointer to member type.
  11166. QualType ClassType
  11167. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  11168. QualType MemPtrType
  11169. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  11170. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  11171. VK_RValue, OK_Ordinary,
  11172. UnOp->getOperatorLoc());
  11173. }
  11174. }
  11175. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11176. Found, Fn);
  11177. if (SubExpr == UnOp->getSubExpr())
  11178. return UnOp;
  11179. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  11180. Context.getPointerType(SubExpr->getType()),
  11181. VK_RValue, OK_Ordinary,
  11182. UnOp->getOperatorLoc());
  11183. }
  11184. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11185. // FIXME: avoid copy.
  11186. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11187. if (ULE->hasExplicitTemplateArgs()) {
  11188. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11189. TemplateArgs = &TemplateArgsBuffer;
  11190. }
  11191. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11192. ULE->getQualifierLoc(),
  11193. ULE->getTemplateKeywordLoc(),
  11194. Fn,
  11195. /*enclosing*/ false, // FIXME?
  11196. ULE->getNameLoc(),
  11197. Fn->getType(),
  11198. VK_LValue,
  11199. Found.getDecl(),
  11200. TemplateArgs);
  11201. MarkDeclRefReferenced(DRE);
  11202. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  11203. return DRE;
  11204. }
  11205. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  11206. // FIXME: avoid copy.
  11207. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11208. if (MemExpr->hasExplicitTemplateArgs()) {
  11209. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11210. TemplateArgs = &TemplateArgsBuffer;
  11211. }
  11212. Expr *Base;
  11213. // If we're filling in a static method where we used to have an
  11214. // implicit member access, rewrite to a simple decl ref.
  11215. if (MemExpr->isImplicitAccess()) {
  11216. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11217. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11218. MemExpr->getQualifierLoc(),
  11219. MemExpr->getTemplateKeywordLoc(),
  11220. Fn,
  11221. /*enclosing*/ false,
  11222. MemExpr->getMemberLoc(),
  11223. Fn->getType(),
  11224. VK_LValue,
  11225. Found.getDecl(),
  11226. TemplateArgs);
  11227. MarkDeclRefReferenced(DRE);
  11228. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  11229. return DRE;
  11230. } else {
  11231. SourceLocation Loc = MemExpr->getMemberLoc();
  11232. if (MemExpr->getQualifier())
  11233. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  11234. CheckCXXThisCapture(Loc);
  11235. Base = new (Context) CXXThisExpr(Loc,
  11236. MemExpr->getBaseType(),
  11237. /*isImplicit=*/true);
  11238. }
  11239. } else
  11240. Base = MemExpr->getBase();
  11241. ExprValueKind valueKind;
  11242. QualType type;
  11243. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11244. valueKind = VK_LValue;
  11245. type = Fn->getType();
  11246. } else {
  11247. valueKind = VK_RValue;
  11248. type = Context.BoundMemberTy;
  11249. }
  11250. MemberExpr *ME = MemberExpr::Create(
  11251. Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  11252. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  11253. MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
  11254. OK_Ordinary);
  11255. ME->setHadMultipleCandidates(true);
  11256. MarkMemberReferenced(ME);
  11257. return ME;
  11258. }
  11259. llvm_unreachable("Invalid reference to overloaded function");
  11260. }
  11261. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  11262. DeclAccessPair Found,
  11263. FunctionDecl *Fn) {
  11264. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  11265. }