SemaOverload.cpp 508 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728
  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 "clang/AST/HlslTypes.h" // HLSL Change
  32. #include "llvm/ADT/DenseSet.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/SmallPtrSet.h"
  35. #include "llvm/ADT/SmallString.h"
  36. #include <algorithm>
  37. #include <cstdlib>
  38. using namespace clang;
  39. using namespace sema;
  40. /// A convenience routine for creating a decayed reference to a function.
  41. static ExprResult
  42. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
  43. bool HadMultipleCandidates,
  44. SourceLocation Loc = SourceLocation(),
  45. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  46. if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
  47. return ExprError();
  48. // If FoundDecl is different from Fn (such as if one is a template
  49. // and the other a specialization), make sure DiagnoseUseOfDecl is
  50. // called on both.
  51. // FIXME: This would be more comprehensively addressed by modifying
  52. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  53. // being used.
  54. if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
  55. return ExprError();
  56. DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
  57. VK_LValue, Loc, LocInfo);
  58. if (HadMultipleCandidates)
  59. DRE->setHadMultipleCandidates(true);
  60. S.MarkDeclRefReferenced(DRE);
  61. ExprResult E = DRE;
  62. E = S.DefaultFunctionArrayConversion(E.get());
  63. if (E.isInvalid())
  64. return ExprError();
  65. return E;
  66. }
  67. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  68. bool InOverloadResolution,
  69. StandardConversionSequence &SCS,
  70. bool CStyle,
  71. bool AllowObjCWritebackConversion);
  72. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  73. QualType &ToType,
  74. bool InOverloadResolution,
  75. StandardConversionSequence &SCS,
  76. bool CStyle);
  77. static OverloadingResult
  78. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  79. UserDefinedConversionSequence& User,
  80. OverloadCandidateSet& Conversions,
  81. bool AllowExplicit,
  82. bool AllowObjCConversionOnExplicit);
  83. static ImplicitConversionSequence::CompareKind
  84. CompareStandardConversionSequences(Sema &S,
  85. const StandardConversionSequence& SCS1,
  86. const StandardConversionSequence& SCS2);
  87. static ImplicitConversionSequence::CompareKind
  88. CompareQualificationConversions(Sema &S,
  89. const StandardConversionSequence& SCS1,
  90. const StandardConversionSequence& SCS2);
  91. static ImplicitConversionSequence::CompareKind
  92. CompareDerivedToBaseConversions(Sema &S,
  93. const StandardConversionSequence& SCS1,
  94. const StandardConversionSequence& SCS2);
  95. /// GetConversionRank - Retrieve the implicit conversion rank
  96. /// corresponding to the given implicit conversion kind.
  97. ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
  98. static const ImplicitConversionRank
  99. Rank[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  100. ICR_Exact_Match,
  101. ICR_Exact_Match,
  102. ICR_Exact_Match,
  103. ICR_Exact_Match,
  104. ICR_Exact_Match,
  105. ICR_Exact_Match,
  106. ICR_Promotion,
  107. ICR_Promotion,
  108. ICR_Promotion,
  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_Conversion,
  120. ICR_Complex_Real_Conversion,
  121. ICR_Conversion,
  122. ICR_Conversion,
  123. ICR_Writeback_Conversion
  124. // HLSL Change Starts: missing from original
  125. ,ICR_Conversion,
  126. // HLSL Change: new entries
  127. ICR_Conversion,
  128. ICR_Conversion,
  129. ICR_Conversion,
  130. ICR_Conversion,
  131. ICR_Conversion,
  132. ICR_Conversion,
  133. // HLSL Change Ends
  134. };
  135. static_assert(_countof(Rank) == ICK_Num_Conversion_Kinds,
  136. "Otherwise, GetConversionRank is out of sync with ImplicitConversionKind"); // HLSL Change
  137. assert((int)Kind < (int)ICK_Num_Conversion_Kinds); // HLSL Change
  138. return Rank[(int)Kind];
  139. }
  140. /// GetImplicitConversionName - Return the name of this kind of
  141. /// implicit conversion.
  142. static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  143. static const char* const Name[] = { // HLSL Change (remove explicit size to verify alignment with enum)
  144. "No conversion",
  145. "Lvalue-to-rvalue",
  146. "Array-to-pointer",
  147. "Function-to-pointer",
  148. "Noreturn adjustment",
  149. "Qualification",
  150. "Integral promotion",
  151. "Floating point promotion",
  152. "Complex promotion",
  153. "Integral conversion",
  154. "Floating conversion",
  155. "Complex conversion",
  156. "Floating-integral conversion",
  157. "Pointer conversion",
  158. "Pointer-to-member conversion",
  159. "Boolean conversion",
  160. "Compatible-types conversion",
  161. "Derived-to-base conversion",
  162. "Vector conversion",
  163. "Vector splat",
  164. "Complex-real conversion",
  165. "Block Pointer conversion",
  166. "Transparent Union Conversion",
  167. "Writeback conversion"
  168. // HLSL Change Starts
  169. ,"Zero constant to event conversion", // HLSL Change: missing value
  170. // HLSL Change: new values
  171. "HLSLVector/Matrix to scalar",
  172. "HLSLVector/Matrix conversion",
  173. "Flat assignment conversion",
  174. "HLSLVector/Matrix splat",
  175. "HLSLVector/Matrix truncation",
  176. "HLSL derived to base",
  177. // HLSL Change Ends
  178. };
  179. static_assert(_countof(Name) == ICK_Num_Conversion_Kinds,
  180. "Otherwise, GetImplicitConversionName is out of sync with ImplicitConversionKind"); // HLSL Change
  181. return Name[Kind];
  182. }
  183. /// StandardConversionSequence - Set the standard conversion
  184. /// sequence to the identity conversion.
  185. void StandardConversionSequence::setAsIdentityConversion() {
  186. First = ICK_Identity;
  187. Second = ICK_Identity;
  188. Third = ICK_Identity;
  189. DeprecatedStringLiteralToCharPtr = false;
  190. QualificationIncludesObjCLifetime = false;
  191. ReferenceBinding = false;
  192. DirectBinding = false;
  193. IsLvalueReference = true;
  194. BindsToFunctionLvalue = false;
  195. BindsToRvalue = false;
  196. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  197. ObjCLifetimeConversionBinding = false;
  198. CopyConstructor = nullptr;
  199. }
  200. /// getRank - Retrieve the rank of this standard conversion sequence
  201. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  202. /// implicit conversions.
  203. ImplicitConversionRank StandardConversionSequence::getRank() const {
  204. ImplicitConversionRank Rank = ICR_Exact_Match;
  205. if (GetConversionRank(First) > Rank)
  206. Rank = GetConversionRank(First);
  207. if (GetConversionRank(Second) > Rank)
  208. Rank = GetConversionRank(Second);
  209. if (GetConversionRank(ComponentConversion) > Rank) // HLSL Change
  210. Rank = GetConversionRank(ComponentConversion);
  211. if (GetConversionRank(Third) > Rank)
  212. Rank = GetConversionRank(Third);
  213. return Rank;
  214. }
  215. /// isPointerConversionToBool - Determines whether this conversion is
  216. /// a conversion of a pointer or pointer-to-member to bool. This is
  217. /// used as part of the ranking of standard conversion sequences
  218. /// (C++ 13.3.3.2p4).
  219. bool StandardConversionSequence::isPointerConversionToBool() const {
  220. // Note that FromType has not necessarily been transformed by the
  221. // array-to-pointer or function-to-pointer implicit conversions, so
  222. // check for their presence as well as checking whether FromType is
  223. // a pointer.
  224. if (getToType(1)->isBooleanType() &&
  225. (getFromType()->isPointerType() ||
  226. getFromType()->isObjCObjectPointerType() ||
  227. getFromType()->isBlockPointerType() ||
  228. getFromType()->isNullPtrType() ||
  229. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  230. return true;
  231. return false;
  232. }
  233. /// isPointerConversionToVoidPointer - Determines whether this
  234. /// conversion is a conversion of a pointer to a void pointer. This is
  235. /// used as part of the ranking of standard conversion sequences (C++
  236. /// 13.3.3.2p4).
  237. bool
  238. StandardConversionSequence::
  239. isPointerConversionToVoidPointer(ASTContext& Context) const {
  240. QualType FromType = getFromType();
  241. QualType ToType = getToType(1);
  242. // Note that FromType has not necessarily been transformed by the
  243. // array-to-pointer implicit conversion, so check for its presence
  244. // and redo the conversion to get a pointer.
  245. if (First == ICK_Array_To_Pointer)
  246. FromType = Context.getArrayDecayedType(FromType);
  247. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  248. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  249. return ToPtrType->getPointeeType()->isVoidType();
  250. return false;
  251. }
  252. /// Skip any implicit casts which could be either part of a narrowing conversion
  253. /// or after one in an implicit conversion.
  254. static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
  255. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  256. switch (ICE->getCastKind()) {
  257. case CK_NoOp:
  258. case CK_IntegralCast:
  259. case CK_IntegralToBoolean:
  260. case CK_IntegralToFloating:
  261. case CK_FloatingToIntegral:
  262. case CK_FloatingToBoolean:
  263. case CK_FloatingCast:
  264. Converted = ICE->getSubExpr();
  265. continue;
  266. default:
  267. return Converted;
  268. }
  269. }
  270. return Converted;
  271. }
  272. /// Check if this standard conversion sequence represents a narrowing
  273. /// conversion, according to C++11 [dcl.init.list]p7.
  274. ///
  275. /// \param Ctx The AST context.
  276. /// \param Converted The result of applying this standard conversion sequence.
  277. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  278. /// value of the expression prior to the narrowing conversion.
  279. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  280. /// type of the expression prior to the narrowing conversion.
  281. NarrowingKind
  282. StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
  283. const Expr *Converted,
  284. APValue &ConstantValue,
  285. QualType &ConstantType) const {
  286. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  287. // C++11 [dcl.init.list]p7:
  288. // A narrowing conversion is an implicit conversion ...
  289. QualType FromType = getToType(0);
  290. QualType ToType = getToType(1);
  291. switch (Second) {
  292. // 'bool' is an integral type; dispatch to the right place to handle it.
  293. case ICK_Boolean_Conversion:
  294. if (FromType->isRealFloatingType())
  295. goto FloatingIntegralConversion;
  296. if (FromType->isIntegralOrUnscopedEnumerationType())
  297. goto IntegralConversion;
  298. // Boolean conversions can be from pointers and pointers to members
  299. // [conv.bool], and those aren't considered narrowing conversions.
  300. return NK_Not_Narrowing;
  301. // -- from a floating-point type to an integer type, or
  302. //
  303. // -- from an integer type or unscoped enumeration type to a floating-point
  304. // type, except where the source is a constant expression and the actual
  305. // value after conversion will fit into the target type and will produce
  306. // the original value when converted back to the original type, or
  307. case ICK_Floating_Integral:
  308. FloatingIntegralConversion:
  309. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  310. return NK_Type_Narrowing;
  311. } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
  312. llvm::APSInt IntConstantValue;
  313. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  314. if (Initializer &&
  315. Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  316. // Convert the integer to the floating type.
  317. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  318. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  319. llvm::APFloat::rmNearestTiesToEven);
  320. // And back.
  321. llvm::APSInt ConvertedValue = IntConstantValue;
  322. bool ignored;
  323. Result.convertToInteger(ConvertedValue,
  324. llvm::APFloat::rmTowardZero, &ignored);
  325. // If the resulting value is different, this was a narrowing conversion.
  326. if (IntConstantValue != ConvertedValue) {
  327. ConstantValue = APValue(IntConstantValue);
  328. ConstantType = Initializer->getType();
  329. return NK_Constant_Narrowing;
  330. }
  331. } else {
  332. // Variables are always narrowings.
  333. return NK_Variable_Narrowing;
  334. }
  335. }
  336. return NK_Not_Narrowing;
  337. // -- from long double to double or float, or from double to float, except
  338. // where the source is a constant expression and the actual value after
  339. // conversion is within the range of values that can be represented (even
  340. // if it cannot be represented exactly), or
  341. case ICK_Floating_Conversion:
  342. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  343. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  344. // FromType is larger than ToType.
  345. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  346. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  347. // Constant!
  348. assert(ConstantValue.isFloat());
  349. llvm::APFloat FloatVal = ConstantValue.getFloat();
  350. // Convert the source value into the target type.
  351. bool ignored;
  352. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  353. Ctx.getFloatTypeSemantics(ToType),
  354. llvm::APFloat::rmNearestTiesToEven, &ignored);
  355. // If there was no overflow, the source value is within the range of
  356. // values that can be represented.
  357. if (ConvertStatus & llvm::APFloat::opOverflow) {
  358. ConstantType = Initializer->getType();
  359. return NK_Constant_Narrowing;
  360. }
  361. } else {
  362. return NK_Variable_Narrowing;
  363. }
  364. }
  365. return NK_Not_Narrowing;
  366. // -- from an integer type or unscoped enumeration type to an integer type
  367. // that cannot represent all the values of the original type, except where
  368. // the source is a constant expression and the actual value after
  369. // conversion will fit into the target type and will produce the original
  370. // value when converted back to the original type.
  371. case ICK_Integral_Conversion:
  372. IntegralConversion: {
  373. assert(FromType->isIntegralOrUnscopedEnumerationType());
  374. assert(ToType->isIntegralOrUnscopedEnumerationType());
  375. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  376. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  377. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  378. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  379. if (FromWidth > ToWidth ||
  380. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  381. (FromSigned && !ToSigned)) {
  382. // Not all values of FromType can be represented in ToType.
  383. llvm::APSInt InitializerValue;
  384. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  385. if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  386. // Such conversions on variables are always narrowing.
  387. return NK_Variable_Narrowing;
  388. }
  389. bool Narrowing = false;
  390. if (FromWidth < ToWidth) {
  391. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  392. // narrowing.
  393. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  394. Narrowing = true;
  395. } else {
  396. // Add a bit to the InitializerValue so we don't have to worry about
  397. // signed vs. unsigned comparisons.
  398. InitializerValue = InitializerValue.extend(
  399. InitializerValue.getBitWidth() + 1);
  400. // Convert the initializer to and from the target width and signed-ness.
  401. llvm::APSInt ConvertedValue = InitializerValue;
  402. ConvertedValue = ConvertedValue.trunc(ToWidth);
  403. ConvertedValue.setIsSigned(ToSigned);
  404. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  405. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  406. // If the result is different, this was a narrowing conversion.
  407. if (ConvertedValue != InitializerValue)
  408. Narrowing = true;
  409. }
  410. if (Narrowing) {
  411. ConstantType = Initializer->getType();
  412. ConstantValue = APValue(InitializerValue);
  413. return NK_Constant_Narrowing;
  414. }
  415. }
  416. return NK_Not_Narrowing;
  417. }
  418. default:
  419. // Other kinds of conversions are not narrowings.
  420. return NK_Not_Narrowing;
  421. }
  422. }
  423. /// dump - Print this standard conversion sequence to standard
  424. /// error. Useful for debugging overloading issues.
  425. void StandardConversionSequence::dump() const {
  426. raw_ostream &OS = llvm::errs();
  427. bool PrintedSomething = false;
  428. if (First != ICK_Identity) {
  429. OS << GetImplicitConversionName(First);
  430. PrintedSomething = true;
  431. }
  432. if (Second != ICK_Identity) {
  433. if (PrintedSomething) {
  434. OS << " -> ";
  435. }
  436. OS << GetImplicitConversionName(Second);
  437. if (CopyConstructor) {
  438. OS << " (by copy constructor)";
  439. } else if (DirectBinding) {
  440. OS << " (direct reference binding)";
  441. } else if (ReferenceBinding) {
  442. OS << " (reference binding)";
  443. }
  444. PrintedSomething = true;
  445. }
  446. // HLSL Change Starts
  447. if (ComponentConversion != ICK_Identity) {
  448. if (PrintedSomething) {
  449. OS << " -> ";
  450. }
  451. OS << GetImplicitConversionName(ComponentConversion);
  452. PrintedSomething = true;
  453. }
  454. // HLSL Change Ends
  455. if (Third != ICK_Identity) {
  456. if (PrintedSomething) {
  457. OS << " -> ";
  458. }
  459. OS << GetImplicitConversionName(Third);
  460. PrintedSomething = true;
  461. }
  462. if (!PrintedSomething) {
  463. OS << "No conversions required";
  464. }
  465. }
  466. /// dump - Print this user-defined conversion sequence to standard
  467. /// error. Useful for debugging overloading issues.
  468. void UserDefinedConversionSequence::dump() const {
  469. raw_ostream &OS = llvm::errs();
  470. if (Before.First || Before.Second || Before.Third) {
  471. Before.dump();
  472. OS << " -> ";
  473. }
  474. if (ConversionFunction)
  475. OS << '\'' << *ConversionFunction << '\'';
  476. else
  477. OS << "aggregate initialization";
  478. if (After.First || After.Second || After.Third) {
  479. OS << " -> ";
  480. After.dump();
  481. }
  482. }
  483. /// dump - Print this implicit conversion sequence to standard
  484. /// error. Useful for debugging overloading issues.
  485. void ImplicitConversionSequence::dump() const {
  486. raw_ostream &OS = llvm::errs();
  487. if (isStdInitializerListElement())
  488. OS << "Worst std::initializer_list element conversion: ";
  489. switch (ConversionKind) {
  490. case StandardConversion:
  491. OS << "Standard conversion: ";
  492. Standard.dump();
  493. break;
  494. case UserDefinedConversion:
  495. OS << "User-defined conversion: ";
  496. UserDefined.dump();
  497. break;
  498. case EllipsisConversion:
  499. OS << "Ellipsis conversion";
  500. break;
  501. case AmbiguousConversion:
  502. OS << "Ambiguous conversion";
  503. break;
  504. case BadConversion:
  505. OS << "Bad conversion";
  506. break;
  507. }
  508. OS << "\n";
  509. }
  510. void AmbiguousConversionSequence::construct() {
  511. new (&conversions()) ConversionSet();
  512. }
  513. void AmbiguousConversionSequence::destruct() {
  514. conversions().~ConversionSet();
  515. }
  516. void
  517. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  518. FromTypePtr = O.FromTypePtr;
  519. ToTypePtr = O.ToTypePtr;
  520. new (&conversions()) ConversionSet(O.conversions());
  521. }
  522. namespace {
  523. // Structure used by DeductionFailureInfo to store
  524. // template argument information.
  525. struct DFIArguments {
  526. TemplateArgument FirstArg;
  527. TemplateArgument SecondArg;
  528. };
  529. // Structure used by DeductionFailureInfo to store
  530. // template parameter and template argument information.
  531. struct DFIParamWithArguments : DFIArguments {
  532. TemplateParameter Param;
  533. };
  534. }
  535. /// \brief Convert from Sema's representation of template deduction information
  536. /// to the form used in overload-candidate information.
  537. DeductionFailureInfo
  538. clang::MakeDeductionFailureInfo(ASTContext &Context,
  539. Sema::TemplateDeductionResult TDK,
  540. TemplateDeductionInfo &Info) {
  541. DeductionFailureInfo Result;
  542. Result.Result = static_cast<unsigned>(TDK);
  543. Result.HasDiagnostic = false;
  544. Result.Data = nullptr;
  545. switch (TDK) {
  546. case Sema::TDK_Success:
  547. case Sema::TDK_Invalid:
  548. case Sema::TDK_InstantiationDepth:
  549. case Sema::TDK_TooManyArguments:
  550. case Sema::TDK_TooFewArguments:
  551. break;
  552. case Sema::TDK_Incomplete:
  553. case Sema::TDK_InvalidExplicitArguments:
  554. Result.Data = Info.Param.getOpaqueValue();
  555. break;
  556. case Sema::TDK_NonDeducedMismatch: {
  557. // FIXME: Should allocate from normal heap so that we can free this later.
  558. DFIArguments *Saved = new (Context) DFIArguments;
  559. Saved->FirstArg = Info.FirstArg;
  560. Saved->SecondArg = Info.SecondArg;
  561. Result.Data = Saved;
  562. break;
  563. }
  564. case Sema::TDK_Inconsistent:
  565. case Sema::TDK_Underqualified: {
  566. // FIXME: Should allocate from normal heap so that we can free this later.
  567. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  568. Saved->Param = Info.Param;
  569. Saved->FirstArg = Info.FirstArg;
  570. Saved->SecondArg = Info.SecondArg;
  571. Result.Data = Saved;
  572. break;
  573. }
  574. case Sema::TDK_SubstitutionFailure:
  575. Result.Data = Info.take();
  576. if (Info.hasSFINAEDiagnostic()) {
  577. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  578. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  579. Info.takeSFINAEDiagnostic(*Diag);
  580. Result.HasDiagnostic = true;
  581. }
  582. break;
  583. case Sema::TDK_FailedOverloadResolution:
  584. Result.Data = Info.Expression;
  585. break;
  586. case Sema::TDK_MiscellaneousDeductionFailure:
  587. break;
  588. }
  589. return Result;
  590. }
  591. void DeductionFailureInfo::Destroy() {
  592. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  593. case Sema::TDK_Success:
  594. case Sema::TDK_Invalid:
  595. case Sema::TDK_InstantiationDepth:
  596. case Sema::TDK_Incomplete:
  597. case Sema::TDK_TooManyArguments:
  598. case Sema::TDK_TooFewArguments:
  599. case Sema::TDK_InvalidExplicitArguments:
  600. case Sema::TDK_FailedOverloadResolution:
  601. break;
  602. case Sema::TDK_Inconsistent:
  603. case Sema::TDK_Underqualified:
  604. case Sema::TDK_NonDeducedMismatch:
  605. // FIXME: Destroy the data?
  606. Data = nullptr;
  607. break;
  608. case Sema::TDK_SubstitutionFailure:
  609. // FIXME: Destroy the template argument list?
  610. Data = nullptr;
  611. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  612. Diag->~PartialDiagnosticAt();
  613. HasDiagnostic = false;
  614. }
  615. break;
  616. // Unhandled
  617. case Sema::TDK_MiscellaneousDeductionFailure:
  618. break;
  619. }
  620. }
  621. PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
  622. if (HasDiagnostic)
  623. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  624. return nullptr;
  625. }
  626. TemplateParameter DeductionFailureInfo::getTemplateParameter() {
  627. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  628. case Sema::TDK_Success:
  629. case Sema::TDK_Invalid:
  630. case Sema::TDK_InstantiationDepth:
  631. case Sema::TDK_TooManyArguments:
  632. case Sema::TDK_TooFewArguments:
  633. case Sema::TDK_SubstitutionFailure:
  634. case Sema::TDK_NonDeducedMismatch:
  635. case Sema::TDK_FailedOverloadResolution:
  636. return TemplateParameter();
  637. case Sema::TDK_Incomplete:
  638. case Sema::TDK_InvalidExplicitArguments:
  639. return TemplateParameter::getFromOpaqueValue(Data);
  640. case Sema::TDK_Inconsistent:
  641. case Sema::TDK_Underqualified:
  642. return static_cast<DFIParamWithArguments*>(Data)->Param;
  643. // Unhandled
  644. case Sema::TDK_MiscellaneousDeductionFailure:
  645. break;
  646. }
  647. return TemplateParameter();
  648. }
  649. TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
  650. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  651. case Sema::TDK_Success:
  652. case Sema::TDK_Invalid:
  653. case Sema::TDK_InstantiationDepth:
  654. case Sema::TDK_TooManyArguments:
  655. case Sema::TDK_TooFewArguments:
  656. case Sema::TDK_Incomplete:
  657. case Sema::TDK_InvalidExplicitArguments:
  658. case Sema::TDK_Inconsistent:
  659. case Sema::TDK_Underqualified:
  660. case Sema::TDK_NonDeducedMismatch:
  661. case Sema::TDK_FailedOverloadResolution:
  662. return nullptr;
  663. case Sema::TDK_SubstitutionFailure:
  664. return static_cast<TemplateArgumentList*>(Data);
  665. // Unhandled
  666. case Sema::TDK_MiscellaneousDeductionFailure:
  667. break;
  668. }
  669. return nullptr;
  670. }
  671. const TemplateArgument *DeductionFailureInfo::getFirstArg() {
  672. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  673. case Sema::TDK_Success:
  674. case Sema::TDK_Invalid:
  675. case Sema::TDK_InstantiationDepth:
  676. case Sema::TDK_Incomplete:
  677. case Sema::TDK_TooManyArguments:
  678. case Sema::TDK_TooFewArguments:
  679. case Sema::TDK_InvalidExplicitArguments:
  680. case Sema::TDK_SubstitutionFailure:
  681. case Sema::TDK_FailedOverloadResolution:
  682. return nullptr;
  683. case Sema::TDK_Inconsistent:
  684. case Sema::TDK_Underqualified:
  685. case Sema::TDK_NonDeducedMismatch:
  686. return &static_cast<DFIArguments*>(Data)->FirstArg;
  687. // Unhandled
  688. case Sema::TDK_MiscellaneousDeductionFailure:
  689. break;
  690. }
  691. return nullptr;
  692. }
  693. const TemplateArgument *DeductionFailureInfo::getSecondArg() {
  694. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  695. case Sema::TDK_Success:
  696. case Sema::TDK_Invalid:
  697. case Sema::TDK_InstantiationDepth:
  698. case Sema::TDK_Incomplete:
  699. case Sema::TDK_TooManyArguments:
  700. case Sema::TDK_TooFewArguments:
  701. case Sema::TDK_InvalidExplicitArguments:
  702. case Sema::TDK_SubstitutionFailure:
  703. case Sema::TDK_FailedOverloadResolution:
  704. return nullptr;
  705. case Sema::TDK_Inconsistent:
  706. case Sema::TDK_Underqualified:
  707. case Sema::TDK_NonDeducedMismatch:
  708. return &static_cast<DFIArguments*>(Data)->SecondArg;
  709. // Unhandled
  710. case Sema::TDK_MiscellaneousDeductionFailure:
  711. break;
  712. }
  713. return nullptr;
  714. }
  715. Expr *DeductionFailureInfo::getExpr() {
  716. if (static_cast<Sema::TemplateDeductionResult>(Result) ==
  717. Sema::TDK_FailedOverloadResolution)
  718. return static_cast<Expr*>(Data);
  719. return nullptr;
  720. }
  721. void OverloadCandidateSet::destroyCandidates() {
  722. for (iterator i = begin(), e = end(); i != e; ++i) {
  723. for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
  724. i->Conversions[ii].~ImplicitConversionSequence();
  725. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  726. i->DeductionFailure.Destroy();
  727. }
  728. }
  729. void OverloadCandidateSet::clear() {
  730. destroyCandidates();
  731. NumInlineSequences = 0;
  732. Candidates.clear();
  733. Functions.clear();
  734. }
  735. namespace {
  736. class UnbridgedCastsSet {
  737. struct Entry {
  738. Expr **Addr;
  739. Expr *Saved;
  740. };
  741. SmallVector<Entry, 2> Entries;
  742. public:
  743. void save(Sema &S, Expr *&E) {
  744. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  745. Entry entry = { &E, E };
  746. Entries.push_back(entry);
  747. E = S.stripARCUnbridgedCast(E);
  748. }
  749. void restore() {
  750. for (SmallVectorImpl<Entry>::iterator
  751. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  752. *i->Addr = i->Saved;
  753. }
  754. };
  755. }
  756. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  757. /// preprocessing on the given expression.
  758. ///
  759. /// \param unbridgedCasts a collection to which to add unbridged casts;
  760. /// without this, they will be immediately diagnosed as errors
  761. ///
  762. /// Return true on unrecoverable error.
  763. static bool
  764. checkPlaceholderForOverload(Sema &S, Expr *&E,
  765. UnbridgedCastsSet *unbridgedCasts = nullptr) {
  766. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  767. // We can't handle overloaded expressions here because overload
  768. // resolution might reasonably tweak them.
  769. if (placeholder->getKind() == BuiltinType::Overload) return false;
  770. // If the context potentially accepts unbridged ARC casts, strip
  771. // the unbridged cast and add it to the collection for later restoration.
  772. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  773. unbridgedCasts) {
  774. unbridgedCasts->save(S, E);
  775. return false;
  776. }
  777. // Go ahead and check everything else.
  778. ExprResult result = S.CheckPlaceholderExpr(E);
  779. if (result.isInvalid())
  780. return true;
  781. E = result.get();
  782. return false;
  783. }
  784. // Nothing to do.
  785. return false;
  786. }
  787. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  788. /// placeholders.
  789. static bool checkArgPlaceholdersForOverload(Sema &S,
  790. MultiExprArg Args,
  791. UnbridgedCastsSet &unbridged) {
  792. for (unsigned i = 0, e = Args.size(); i != e; ++i)
  793. if (checkPlaceholderForOverload(S, Args[i], &unbridged))
  794. return true;
  795. return false;
  796. }
  797. // IsOverload - Determine whether the given New declaration is an
  798. // overload of the declarations in Old. This routine returns false if
  799. // New and Old cannot be overloaded, e.g., if New has the same
  800. // signature as some function in Old (C++ 1.3.10) or if the Old
  801. // declarations aren't functions (or function templates) at all. When
  802. // it does return false, MatchedDecl will point to the decl that New
  803. // cannot be overloaded with. This decl may be a UsingShadowDecl on
  804. // top of the underlying declaration.
  805. //
  806. // Example: Given the following input:
  807. //
  808. // void f(int, float); // #1
  809. // void f(int, int); // #2
  810. // int f(int, int); // #3
  811. //
  812. // When we process #1, there is no previous declaration of "f",
  813. // so IsOverload will not be used.
  814. //
  815. // When we process #2, Old contains only the FunctionDecl for #1. By
  816. // comparing the parameter types, we see that #1 and #2 are overloaded
  817. // (since they have different signatures), so this routine returns
  818. // false; MatchedDecl is unchanged.
  819. //
  820. // When we process #3, Old is an overload set containing #1 and #2. We
  821. // compare the signatures of #3 to #1 (they're overloaded, so we do
  822. // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
  823. // identical (return types of functions are not part of the
  824. // signature), IsOverload returns false and MatchedDecl will be set to
  825. // point to the FunctionDecl for #2.
  826. //
  827. // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
  828. // into a class by a using declaration. The rules for whether to hide
  829. // shadow declarations ignore some properties which otherwise figure
  830. // into a function template's signature.
  831. Sema::OverloadKind
  832. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  833. NamedDecl *&Match, bool NewIsUsingDecl) {
  834. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  835. I != E; ++I) {
  836. NamedDecl *OldD = *I;
  837. bool OldIsUsingDecl = false;
  838. if (isa<UsingShadowDecl>(OldD)) {
  839. OldIsUsingDecl = true;
  840. // We can always introduce two using declarations into the same
  841. // context, even if they have identical signatures.
  842. if (NewIsUsingDecl) continue;
  843. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  844. }
  845. // If either declaration was introduced by a using declaration,
  846. // we'll need to use slightly different rules for matching.
  847. // Essentially, these rules are the normal rules, except that
  848. // function templates hide function templates with different
  849. // return types or template parameter lists.
  850. bool UseMemberUsingDeclRules =
  851. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
  852. !New->getFriendObjectKind();
  853. if (FunctionDecl *OldF = OldD->getAsFunction()) {
  854. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  855. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  856. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  857. continue;
  858. }
  859. if (!isa<FunctionTemplateDecl>(OldD) &&
  860. !shouldLinkPossiblyHiddenDecl(*I, New))
  861. continue;
  862. Match = *I;
  863. return Ovl_Match;
  864. }
  865. } else if (isa<UsingDecl>(OldD)) {
  866. // We can overload with these, which can show up when doing
  867. // redeclaration checks for UsingDecls.
  868. assert(Old.getLookupKind() == LookupUsingDeclName);
  869. } else if (isa<TagDecl>(OldD)) {
  870. // We can always overload with tags by hiding them.
  871. } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
  872. // Optimistically assume that an unresolved using decl will
  873. // overload; if it doesn't, we'll have to diagnose during
  874. // template instantiation.
  875. } else {
  876. // (C++ 13p1):
  877. // Only function declarations can be overloaded; object and type
  878. // declarations cannot be overloaded.
  879. Match = *I;
  880. return Ovl_NonFunction;
  881. }
  882. }
  883. return Ovl_Overload;
  884. }
  885. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  886. bool UseUsingDeclRules) {
  887. // C++ [basic.start.main]p2: This function shall not be overloaded.
  888. if (New->isMain())
  889. return false;
  890. // MSVCRT user defined entry points cannot be overloaded.
  891. if (New->isMSVCRTEntryPoint())
  892. return false;
  893. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  894. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  895. // C++ [temp.fct]p2:
  896. // A function template can be overloaded with other function templates
  897. // and with normal (non-template) functions.
  898. if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
  899. return true;
  900. // Is the function New an overload of the function Old?
  901. QualType OldQType = Context.getCanonicalType(Old->getType());
  902. QualType NewQType = Context.getCanonicalType(New->getType());
  903. // Compare the signatures (C++ 1.3.10) of the two functions to
  904. // determine whether they are overloads. If we find any mismatch
  905. // in the signature, they are overloads.
  906. // If either of these functions is a K&R-style function (no
  907. // prototype), then we consider them to have matching signatures.
  908. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  909. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  910. return false;
  911. const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
  912. const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
  913. // The signature of a function includes the types of its
  914. // parameters (C++ 1.3.10), which includes the presence or absence
  915. // of the ellipsis; see C++ DR 357).
  916. if (OldQType != NewQType &&
  917. (OldType->getNumParams() != NewType->getNumParams() ||
  918. OldType->isVariadic() != NewType->isVariadic() ||
  919. !FunctionParamTypesAreEqual(OldType, NewType)))
  920. return true;
  921. // C++ [temp.over.link]p4:
  922. // The signature of a function template consists of its function
  923. // signature, its return type and its template parameter list. The names
  924. // of the template parameters are significant only for establishing the
  925. // relationship between the template parameters and the rest of the
  926. // signature.
  927. //
  928. // We check the return type and template parameter lists for function
  929. // templates first; the remaining checks follow.
  930. //
  931. // However, we don't consider either of these when deciding whether
  932. // a member introduced by a shadow declaration is hidden.
  933. if (!UseUsingDeclRules && NewTemplate &&
  934. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  935. OldTemplate->getTemplateParameters(),
  936. false, TPL_TemplateMatch) ||
  937. OldType->getReturnType() != NewType->getReturnType()))
  938. return true;
  939. // If the function is a class member, its signature includes the
  940. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  941. //
  942. // As part of this, also check whether one of the member functions
  943. // is static, in which case they are not overloads (C++
  944. // 13.1p2). While not part of the definition of the signature,
  945. // this check is important to determine whether these functions
  946. // can be overloaded.
  947. CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  948. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  949. if (OldMethod && NewMethod &&
  950. !OldMethod->isStatic() && !NewMethod->isStatic()) {
  951. if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
  952. if (!UseUsingDeclRules &&
  953. (OldMethod->getRefQualifier() == RQ_None ||
  954. NewMethod->getRefQualifier() == RQ_None)) {
  955. // C++0x [over.load]p2:
  956. // - Member function declarations with the same name and the same
  957. // parameter-type-list as well as member function template
  958. // declarations with the same name, the same parameter-type-list, and
  959. // the same template parameter lists cannot be overloaded if any of
  960. // them, but not all, have a ref-qualifier (8.3.5).
  961. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  962. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  963. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  964. }
  965. return true;
  966. }
  967. // We may not have applied the implicit const for a constexpr member
  968. // function yet (because we haven't yet resolved whether this is a static
  969. // or non-static member function). Add it now, on the assumption that this
  970. // is a redeclaration of OldMethod.
  971. unsigned OldQuals = OldMethod->getTypeQualifiers();
  972. unsigned NewQuals = NewMethod->getTypeQualifiers();
  973. if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
  974. !isa<CXXConstructorDecl>(NewMethod))
  975. NewQuals |= Qualifiers::Const;
  976. // We do not allow overloading based off of '__restrict'.
  977. OldQuals &= ~Qualifiers::Restrict;
  978. NewQuals &= ~Qualifiers::Restrict;
  979. if (OldQuals != NewQuals)
  980. return true;
  981. }
  982. // enable_if attributes are an order-sensitive part of the signature.
  983. for (specific_attr_iterator<EnableIfAttr>
  984. NewI = New->specific_attr_begin<EnableIfAttr>(),
  985. NewE = New->specific_attr_end<EnableIfAttr>(),
  986. OldI = Old->specific_attr_begin<EnableIfAttr>(),
  987. OldE = Old->specific_attr_end<EnableIfAttr>();
  988. NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
  989. if (NewI == NewE || OldI == OldE)
  990. return true;
  991. llvm::FoldingSetNodeID NewID, OldID;
  992. NewI->getCond()->Profile(NewID, Context, true);
  993. OldI->getCond()->Profile(OldID, Context, true);
  994. if (NewID != OldID)
  995. return true;
  996. }
  997. // The signatures match; this is not an overload.
  998. return false;
  999. }
  1000. /// \brief Checks availability of the function depending on the current
  1001. /// function context. Inside an unavailable function, unavailability is ignored.
  1002. ///
  1003. /// \returns true if \arg FD is unavailable and current context is inside
  1004. /// an available function, false otherwise.
  1005. bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
  1006. return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
  1007. }
  1008. /// \brief Tries a user-defined conversion from From to ToType.
  1009. ///
  1010. /// Produces an implicit conversion sequence for when a standard conversion
  1011. /// is not an option. See TryImplicitConversion for more information.
  1012. static ImplicitConversionSequence
  1013. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  1014. bool SuppressUserConversions,
  1015. bool AllowExplicit,
  1016. bool InOverloadResolution,
  1017. bool CStyle,
  1018. bool AllowObjCWritebackConversion,
  1019. bool AllowObjCConversionOnExplicit) {
  1020. ImplicitConversionSequence ICS;
  1021. if (SuppressUserConversions || S.getLangOpts().HLSL) { // HLSL Change - no user conversions
  1022. // We're not in the case above, so there is no conversion that
  1023. // we can perform.
  1024. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1025. return ICS;
  1026. }
  1027. // Attempt user-defined conversion.
  1028. OverloadCandidateSet Conversions(From->getExprLoc(),
  1029. OverloadCandidateSet::CSK_Normal);
  1030. switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
  1031. Conversions, AllowExplicit,
  1032. AllowObjCConversionOnExplicit)) {
  1033. case OR_Success:
  1034. case OR_Deleted:
  1035. ICS.setUserDefined();
  1036. ICS.UserDefined.Before.setAsIdentityConversion();
  1037. // C++ [over.ics.user]p4:
  1038. // A conversion of an expression of class type to the same class
  1039. // type is given Exact Match rank, and a conversion of an
  1040. // expression of class type to a base class of that type is
  1041. // given Conversion rank, in spite of the fact that a copy
  1042. // constructor (i.e., a user-defined conversion function) is
  1043. // called for those cases.
  1044. if (CXXConstructorDecl *Constructor
  1045. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  1046. QualType FromCanon
  1047. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  1048. QualType ToCanon
  1049. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  1050. if (Constructor->isCopyConstructor() &&
  1051. (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
  1052. // Turn this into a "standard" conversion sequence, so that it
  1053. // gets ranked with standard conversion sequences.
  1054. ICS.setStandard();
  1055. ICS.Standard.setAsIdentityConversion();
  1056. ICS.Standard.setFromType(From->getType());
  1057. ICS.Standard.setAllToTypes(ToType);
  1058. ICS.Standard.CopyConstructor = Constructor;
  1059. if (ToCanon != FromCanon)
  1060. ICS.Standard.Second = ICK_Derived_To_Base;
  1061. }
  1062. }
  1063. break;
  1064. case OR_Ambiguous:
  1065. ICS.setAmbiguous();
  1066. ICS.Ambiguous.setFromType(From->getType());
  1067. ICS.Ambiguous.setToType(ToType);
  1068. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  1069. Cand != Conversions.end(); ++Cand)
  1070. if (Cand->Viable)
  1071. ICS.Ambiguous.addConversion(Cand->Function);
  1072. break;
  1073. // Fall through.
  1074. case OR_No_Viable_Function:
  1075. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1076. break;
  1077. }
  1078. return ICS;
  1079. }
  1080. /// TryImplicitConversion - Attempt to perform an implicit conversion
  1081. /// from the given expression (Expr) to the given type (ToType). This
  1082. /// function returns an implicit conversion sequence that can be used
  1083. /// to perform the initialization. Given
  1084. ///
  1085. /// void f(float f);
  1086. /// void g(int i) { f(i); }
  1087. ///
  1088. /// this routine would produce an implicit conversion sequence to
  1089. /// describe the initialization of f from i, which will be a standard
  1090. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1091. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1092. //
  1093. /// Note that this routine only determines how the conversion can be
  1094. /// performed; it does not actually perform the conversion. As such,
  1095. /// it will not produce any diagnostics if no conversion is available,
  1096. /// but will instead return an implicit conversion sequence of kind
  1097. /// "BadConversion".
  1098. ///
  1099. /// If @p SuppressUserConversions, then user-defined conversions are
  1100. /// not permitted.
  1101. /// If @p AllowExplicit, then explicit user-defined conversions are
  1102. /// permitted.
  1103. ///
  1104. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1105. /// writeback conversion, which allows __autoreleasing id* parameters to
  1106. /// be initialized with __strong id* or __weak id* arguments.
  1107. static ImplicitConversionSequence
  1108. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1109. bool SuppressUserConversions,
  1110. bool AllowExplicit,
  1111. bool InOverloadResolution,
  1112. bool CStyle,
  1113. bool AllowObjCWritebackConversion,
  1114. bool AllowObjCConversionOnExplicit) {
  1115. ImplicitConversionSequence ICS;
  1116. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1117. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1118. ICS.setStandard();
  1119. return ICS;
  1120. }
  1121. if (!S.getLangOpts().CPlusPlus) {
  1122. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1123. return ICS;
  1124. }
  1125. // C++ [over.ics.user]p4:
  1126. // A conversion of an expression of class type to the same class
  1127. // type is given Exact Match rank, and a conversion of an
  1128. // expression of class type to a base class of that type is
  1129. // given Conversion rank, in spite of the fact that a copy/move
  1130. // constructor (i.e., a user-defined conversion function) is
  1131. // called for those cases.
  1132. QualType FromType = From->getType();
  1133. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1134. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1135. S.IsDerivedFrom(FromType, ToType))) {
  1136. ICS.setStandard();
  1137. ICS.Standard.setAsIdentityConversion();
  1138. ICS.Standard.setFromType(FromType);
  1139. ICS.Standard.setAllToTypes(ToType);
  1140. // We don't actually check at this point whether there is a valid
  1141. // copy/move constructor, since overloading just assumes that it
  1142. // exists. When we actually perform initialization, we'll find the
  1143. // appropriate constructor to copy the returned object, if needed.
  1144. ICS.Standard.CopyConstructor = nullptr;
  1145. // Determine whether this is considered a derived-to-base conversion.
  1146. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1147. ICS.Standard.Second = ICK_Derived_To_Base;
  1148. return ICS;
  1149. }
  1150. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1151. AllowExplicit, InOverloadResolution, CStyle,
  1152. AllowObjCWritebackConversion,
  1153. AllowObjCConversionOnExplicit);
  1154. }
  1155. ImplicitConversionSequence
  1156. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1157. bool SuppressUserConversions,
  1158. bool AllowExplicit,
  1159. bool InOverloadResolution,
  1160. bool CStyle,
  1161. bool AllowObjCWritebackConversion) {
  1162. return ::TryImplicitConversion(*this, From, ToType,
  1163. SuppressUserConversions, AllowExplicit,
  1164. InOverloadResolution, CStyle,
  1165. AllowObjCWritebackConversion,
  1166. /*AllowObjCConversionOnExplicit=*/false);
  1167. }
  1168. /// PerformImplicitConversion - Perform an implicit conversion of the
  1169. /// expression From to the type ToType. Returns the
  1170. /// converted expression. Flavor is the kind of conversion we're
  1171. /// performing, used in the error message. If @p AllowExplicit,
  1172. /// explicit user-defined conversions are permitted.
  1173. ExprResult
  1174. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1175. AssignmentAction Action, bool AllowExplicit) {
  1176. ImplicitConversionSequence ICS;
  1177. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1178. }
  1179. ExprResult
  1180. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1181. AssignmentAction Action, bool AllowExplicit,
  1182. ImplicitConversionSequence& ICS) {
  1183. if (checkPlaceholderForOverload(*this, From))
  1184. return ExprError();
  1185. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1186. bool AllowObjCWritebackConversion
  1187. = getLangOpts().ObjCAutoRefCount &&
  1188. (Action == AA_Passing || Action == AA_Sending);
  1189. if (getLangOpts().ObjC1)
  1190. CheckObjCBridgeRelatedConversions(From->getLocStart(),
  1191. ToType, From->getType(), From);
  1192. ICS = ::TryImplicitConversion(*this, From, ToType,
  1193. /*SuppressUserConversions=*/false,
  1194. AllowExplicit,
  1195. /*InOverloadResolution=*/false,
  1196. /*CStyle=*/false,
  1197. AllowObjCWritebackConversion,
  1198. /*AllowObjCConversionOnExplicit=*/false);
  1199. return PerformImplicitConversion(From, ToType, ICS, Action);
  1200. }
  1201. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1202. /// conversion that strips "noreturn" off the nested function type.
  1203. bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
  1204. QualType &ResultTy) {
  1205. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1206. return false;
  1207. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1208. // where F adds one of the following at most once:
  1209. // - a pointer
  1210. // - a member pointer
  1211. // - a block pointer
  1212. CanQualType CanTo = Context.getCanonicalType(ToType);
  1213. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1214. Type::TypeClass TyClass = CanTo->getTypeClass();
  1215. if (TyClass != CanFrom->getTypeClass()) return false;
  1216. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1217. if (TyClass == Type::Pointer) {
  1218. CanTo = CanTo.getAs<PointerType>()->getPointeeType();
  1219. CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
  1220. } else if (TyClass == Type::BlockPointer) {
  1221. CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
  1222. CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
  1223. } else if (TyClass == Type::MemberPointer) {
  1224. CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
  1225. CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
  1226. } else {
  1227. return false;
  1228. }
  1229. TyClass = CanTo->getTypeClass();
  1230. if (TyClass != CanFrom->getTypeClass()) return false;
  1231. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1232. return false;
  1233. }
  1234. const FunctionType *FromFn = cast<FunctionType>(CanFrom);
  1235. FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
  1236. if (!EInfo.getNoReturn()) return false;
  1237. FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
  1238. assert(QualType(FromFn, 0).isCanonical());
  1239. if (QualType(FromFn, 0) != CanTo) return false;
  1240. ResultTy = ToType;
  1241. return true;
  1242. }
  1243. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1244. /// vector conversion.
  1245. ///
  1246. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1247. /// conversion.
  1248. static bool IsVectorConversion(Sema &S, QualType FromType,
  1249. QualType ToType, ImplicitConversionKind &ICK) {
  1250. // We need at least one of these types to be a vector type to have a vector
  1251. // conversion.
  1252. if (!ToType->isVectorType() && !FromType->isVectorType())
  1253. return false;
  1254. // Identical types require no conversions.
  1255. if (S.Context.hasSameUnqualifiedType(FromType, ToType))
  1256. return false;
  1257. // There are no conversions between extended vector types, only identity.
  1258. if (ToType->isExtVectorType()) {
  1259. // There are no conversions between extended vector types other than the
  1260. // identity conversion.
  1261. if (FromType->isExtVectorType())
  1262. return false;
  1263. // Vector splat from any arithmetic type to a vector.
  1264. if (FromType->isArithmeticType()) {
  1265. ICK = ICK_Vector_Splat;
  1266. return true;
  1267. }
  1268. }
  1269. // We can perform the conversion between vector types in the following cases:
  1270. // 1)vector types are equivalent AltiVec and GCC vector types
  1271. // 2)lax vector conversions are permitted and the vector types are of the
  1272. // same size
  1273. if (ToType->isVectorType() && FromType->isVectorType()) {
  1274. if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
  1275. S.isLaxVectorConversion(FromType, ToType)) {
  1276. ICK = ICK_Vector_Conversion;
  1277. return true;
  1278. }
  1279. }
  1280. return false;
  1281. }
  1282. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1283. bool InOverloadResolution,
  1284. StandardConversionSequence &SCS,
  1285. bool CStyle);
  1286. /// IsStandardConversion - Determines whether there is a standard
  1287. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1288. /// expression From to the type ToType. Standard conversion sequences
  1289. /// only consider non-class types; for conversions that involve class
  1290. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1291. /// contain the standard conversion sequence required to perform this
  1292. /// conversion and this routine will return true. Otherwise, this
  1293. /// routine will return false and the value of SCS is unspecified.
  1294. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1295. bool InOverloadResolution,
  1296. StandardConversionSequence &SCS,
  1297. bool CStyle,
  1298. bool AllowObjCWritebackConversion) {
  1299. QualType FromType = From->getType();
  1300. // Standard conversions (C++ [conv])
  1301. SCS.setAsIdentityConversion();
  1302. SCS.IncompatibleObjC = false;
  1303. SCS.setFromType(FromType);
  1304. SCS.CopyConstructor = nullptr;
  1305. // HLSL Change Begins
  1306. if (S.getLangOpts().HLSL) {
  1307. return hlsl::CanConvert(&S, SourceLocation(), From, ToType, /*explicitConversion=*/false, &SCS);
  1308. }
  1309. // HLSL Change Ends
  1310. // There are no standard conversions for class types in C++, so
  1311. // abort early. When overloading in C, however, we do permit
  1312. if (FromType->isRecordType() || ToType->isRecordType()) {
  1313. if (S.getLangOpts().CPlusPlus)
  1314. return false;
  1315. // When we're overloading in C, we allow, as standard conversions,
  1316. }
  1317. // The first conversion can be an lvalue-to-rvalue conversion,
  1318. // array-to-pointer conversion, or function-to-pointer conversion
  1319. // (C++ 4p1).
  1320. if (FromType == S.Context.OverloadTy) {
  1321. DeclAccessPair AccessPair;
  1322. if (FunctionDecl *Fn
  1323. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1324. AccessPair)) {
  1325. // We were able to resolve the address of the overloaded function,
  1326. // so we can convert to the type of that function.
  1327. FromType = Fn->getType();
  1328. SCS.setFromType(FromType);
  1329. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1330. // if the type matches (identity) or we are converting to bool
  1331. if (!S.Context.hasSameUnqualifiedType(
  1332. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1333. QualType resultTy;
  1334. // if the function type matches except for [[noreturn]], it's ok
  1335. if (!S.IsNoReturnConversion(FromType,
  1336. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1337. // otherwise, only a boolean conversion is standard
  1338. if (!ToType->isBooleanType())
  1339. return false;
  1340. }
  1341. // Check if the "from" expression is taking the address of an overloaded
  1342. // function and recompute the FromType accordingly. Take advantage of the
  1343. // fact that non-static member functions *must* have such an address-of
  1344. // expression.
  1345. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1346. if (Method && !Method->isStatic()) {
  1347. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1348. "Non-unary operator on non-static member address");
  1349. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1350. == UO_AddrOf &&
  1351. "Non-address-of operator on non-static member address");
  1352. const Type *ClassType
  1353. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1354. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1355. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1356. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1357. UO_AddrOf &&
  1358. "Non-address-of operator for overloaded function expression");
  1359. FromType = S.Context.getPointerType(FromType);
  1360. }
  1361. // Check that we've computed the proper type after overload resolution.
  1362. assert(S.Context.hasSameType(
  1363. FromType,
  1364. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1365. } else {
  1366. return false;
  1367. }
  1368. }
  1369. // Lvalue-to-rvalue conversion (C++11 4.1):
  1370. // A glvalue (3.10) of a non-function, non-array type T can
  1371. // be converted to a prvalue.
  1372. bool argIsLValue = From->isGLValue();
  1373. if (argIsLValue &&
  1374. !FromType->isFunctionType() && (!FromType->isArrayType() || S.getLangOpts().HLSL) && // HLSL Change - HLSL allows arrays
  1375. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1376. SCS.First = ICK_Lvalue_To_Rvalue;
  1377. // C11 6.3.2.1p2:
  1378. // ... if the lvalue has atomic type, the value has the non-atomic version
  1379. // of the type of the lvalue ...
  1380. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1381. FromType = Atomic->getValueType();
  1382. // If T is a non-class type, the type of the rvalue is the
  1383. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1384. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1385. // just strip the qualifiers because they don't matter.
  1386. FromType = FromType.getUnqualifiedType();
  1387. } else if (FromType->isArrayType()) {
  1388. // Array-to-pointer conversion (C++ 4.2)
  1389. SCS.First = ICK_Array_To_Pointer;
  1390. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1391. // bound of T" can be converted to an rvalue of type "pointer to
  1392. // T" (C++ 4.2p1).
  1393. FromType = S.Context.getArrayDecayedType(FromType);
  1394. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1395. // This conversion is deprecated in C++03 (D.4)
  1396. SCS.DeprecatedStringLiteralToCharPtr = true;
  1397. // For the purpose of ranking in overload resolution
  1398. // (13.3.3.1.1), this conversion is considered an
  1399. // array-to-pointer conversion followed by a qualification
  1400. // conversion (4.4). (C++ 4.2p2)
  1401. SCS.Second = ICK_Identity;
  1402. SCS.Third = ICK_Qualification;
  1403. SCS.QualificationIncludesObjCLifetime = false;
  1404. SCS.setAllToTypes(FromType);
  1405. return true;
  1406. }
  1407. } else if (FromType->isFunctionType() && argIsLValue) {
  1408. // Function-to-pointer conversion (C++ 4.3).
  1409. SCS.First = ICK_Function_To_Pointer;
  1410. // An lvalue of function type T can be converted to an rvalue of
  1411. // type "pointer to T." The result is a pointer to the
  1412. // function. (C++ 4.3p1).
  1413. FromType = S.Context.getPointerType(FromType);
  1414. } else {
  1415. // We don't require any conversions for the first step.
  1416. SCS.First = ICK_Identity;
  1417. }
  1418. SCS.setToType(0, FromType);
  1419. // The second conversion can be an integral promotion, floating
  1420. // point promotion, integral conversion, floating point conversion,
  1421. // floating-integral conversion, pointer conversion,
  1422. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1423. // For overloading in C, this can also be a "compatible-type"
  1424. // conversion.
  1425. bool IncompatibleObjC = false;
  1426. ImplicitConversionKind SecondICK = ICK_Identity;
  1427. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1428. // The unqualified versions of the types are the same: there's no
  1429. // conversion to do.
  1430. SCS.Second = ICK_Identity;
  1431. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1432. // Integral promotion (C++ 4.5).
  1433. SCS.Second = ICK_Integral_Promotion;
  1434. FromType = ToType.getUnqualifiedType();
  1435. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1436. // Floating point promotion (C++ 4.6).
  1437. SCS.Second = ICK_Floating_Promotion;
  1438. FromType = ToType.getUnqualifiedType();
  1439. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1440. // Complex promotion (Clang extension)
  1441. SCS.Second = ICK_Complex_Promotion;
  1442. FromType = ToType.getUnqualifiedType();
  1443. } else if (ToType->isBooleanType() &&
  1444. (FromType->isArithmeticType() ||
  1445. FromType->isAnyPointerType() ||
  1446. FromType->isBlockPointerType() ||
  1447. FromType->isMemberPointerType() ||
  1448. FromType->isNullPtrType())) {
  1449. // Boolean conversions (C++ 4.12).
  1450. SCS.Second = ICK_Boolean_Conversion;
  1451. FromType = S.Context.BoolTy;
  1452. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1453. ToType->isIntegralType(S.Context)) {
  1454. // Integral conversions (C++ 4.7).
  1455. SCS.Second = ICK_Integral_Conversion;
  1456. FromType = ToType.getUnqualifiedType();
  1457. } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
  1458. // Complex conversions (C99 6.3.1.6)
  1459. SCS.Second = ICK_Complex_Conversion;
  1460. FromType = ToType.getUnqualifiedType();
  1461. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1462. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1463. // Complex-real conversions (C99 6.3.1.7)
  1464. SCS.Second = ICK_Complex_Real;
  1465. FromType = ToType.getUnqualifiedType();
  1466. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1467. // Floating point conversions (C++ 4.8).
  1468. SCS.Second = ICK_Floating_Conversion;
  1469. FromType = ToType.getUnqualifiedType();
  1470. } else if ((FromType->isRealFloatingType() &&
  1471. ToType->isIntegralType(S.Context)) ||
  1472. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1473. ToType->isRealFloatingType())) {
  1474. // Floating-integral conversions (C++ 4.9).
  1475. SCS.Second = ICK_Floating_Integral;
  1476. FromType = ToType.getUnqualifiedType();
  1477. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1478. SCS.Second = ICK_Block_Pointer_Conversion;
  1479. } else if (AllowObjCWritebackConversion &&
  1480. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1481. SCS.Second = ICK_Writeback_Conversion;
  1482. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1483. FromType, IncompatibleObjC)) {
  1484. // Pointer conversions (C++ 4.10).
  1485. SCS.Second = ICK_Pointer_Conversion;
  1486. SCS.IncompatibleObjC = IncompatibleObjC;
  1487. FromType = FromType.getUnqualifiedType();
  1488. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1489. InOverloadResolution, FromType)) {
  1490. // Pointer to member conversions (4.11).
  1491. SCS.Second = ICK_Pointer_Member;
  1492. } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
  1493. SCS.Second = SecondICK;
  1494. FromType = ToType.getUnqualifiedType();
  1495. } else if (!S.getLangOpts().CPlusPlus &&
  1496. S.Context.typesAreCompatible(ToType, FromType)) {
  1497. // Compatible conversions (Clang extension for C function overloading)
  1498. SCS.Second = ICK_Compatible_Conversion;
  1499. FromType = ToType.getUnqualifiedType();
  1500. } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
  1501. // Treat a conversion that strips "noreturn" as an identity conversion.
  1502. SCS.Second = ICK_NoReturn_Adjustment;
  1503. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1504. InOverloadResolution,
  1505. SCS, CStyle)) {
  1506. SCS.Second = ICK_TransparentUnionConversion;
  1507. FromType = ToType;
  1508. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1509. CStyle)) {
  1510. // tryAtomicConversion has updated the standard conversion sequence
  1511. // appropriately.
  1512. return true;
  1513. } else if (ToType->isEventT() &&
  1514. From->isIntegerConstantExpr(S.getASTContext()) &&
  1515. (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
  1516. SCS.Second = ICK_Zero_Event_Conversion;
  1517. FromType = ToType;
  1518. } else {
  1519. // No second conversion required.
  1520. SCS.Second = ICK_Identity;
  1521. }
  1522. SCS.setToType(1, FromType);
  1523. QualType CanonFrom;
  1524. QualType CanonTo;
  1525. // The third conversion can be a qualification conversion (C++ 4p1).
  1526. bool ObjCLifetimeConversion;
  1527. if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1528. ObjCLifetimeConversion)) {
  1529. SCS.Third = ICK_Qualification;
  1530. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1531. FromType = ToType;
  1532. CanonFrom = S.Context.getCanonicalType(FromType);
  1533. CanonTo = S.Context.getCanonicalType(ToType);
  1534. } else {
  1535. // No conversion required
  1536. SCS.Third = ICK_Identity;
  1537. // C++ [over.best.ics]p6:
  1538. // [...] Any difference in top-level cv-qualification is
  1539. // subsumed by the initialization itself and does not constitute
  1540. // a conversion. [...]
  1541. CanonFrom = S.Context.getCanonicalType(FromType);
  1542. CanonTo = S.Context.getCanonicalType(ToType);
  1543. if (CanonFrom.getLocalUnqualifiedType()
  1544. == CanonTo.getLocalUnqualifiedType() &&
  1545. CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
  1546. FromType = ToType;
  1547. CanonFrom = CanonTo;
  1548. }
  1549. }
  1550. SCS.setToType(2, FromType);
  1551. // If we have not converted the argument type to the parameter type,
  1552. // this is a bad conversion sequence.
  1553. if (CanonFrom != CanonTo)
  1554. return false;
  1555. return true;
  1556. }
  1557. static bool
  1558. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1559. QualType &ToType,
  1560. bool InOverloadResolution,
  1561. StandardConversionSequence &SCS,
  1562. bool CStyle) {
  1563. const RecordType *UT = ToType->getAsUnionType();
  1564. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1565. return false;
  1566. // The field to initialize within the transparent union.
  1567. RecordDecl *UD = UT->getDecl();
  1568. // It's compatible if the expression matches any of the fields.
  1569. for (const auto *it : UD->fields()) {
  1570. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1571. CStyle, /*ObjCWritebackConversion=*/false)) {
  1572. ToType = it->getType();
  1573. return true;
  1574. }
  1575. }
  1576. return false;
  1577. }
  1578. /// IsIntegralPromotion - Determines whether the conversion from the
  1579. /// expression From (whose potentially-adjusted type is FromType) to
  1580. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1581. /// sets PromotedType to the promoted type.
  1582. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1583. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1584. // All integers are built-in.
  1585. if (!To) {
  1586. return false;
  1587. }
  1588. // An rvalue of type char, signed char, unsigned char, short int, or
  1589. // unsigned short int can be converted to an rvalue of type int if
  1590. // int can represent all the values of the source type; otherwise,
  1591. // the source rvalue can be converted to an rvalue of type unsigned
  1592. // int (C++ 4.5p1).
  1593. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1594. !FromType->isEnumeralType()) {
  1595. if (// We can promote any signed, promotable integer type to an int
  1596. (FromType->isSignedIntegerType() ||
  1597. // We can promote any unsigned integer type whose size is
  1598. // less than int to an int.
  1599. (!FromType->isSignedIntegerType() &&
  1600. Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
  1601. return To->getKind() == BuiltinType::Int;
  1602. }
  1603. return To->getKind() == BuiltinType::UInt;
  1604. }
  1605. // C++11 [conv.prom]p3:
  1606. // A prvalue of an unscoped enumeration type whose underlying type is not
  1607. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1608. // following types that can represent all the values of the enumeration
  1609. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1610. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1611. // long long int. If none of the types in that list can represent all the
  1612. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1613. // type can be converted to an rvalue a prvalue of the extended integer type
  1614. // with lowest integer conversion rank (4.13) greater than the rank of long
  1615. // long in which all the values of the enumeration can be represented. If
  1616. // there are two such extended types, the signed one is chosen.
  1617. // C++11 [conv.prom]p4:
  1618. // A prvalue of an unscoped enumeration type whose underlying type is fixed
  1619. // can be converted to a prvalue of its underlying type. Moreover, if
  1620. // integral promotion can be applied to its underlying type, a prvalue of an
  1621. // unscoped enumeration type whose underlying type is fixed can also be
  1622. // converted to a prvalue of the promoted underlying type.
  1623. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1624. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1625. // provided for a scoped enumeration.
  1626. if (FromEnumType->getDecl()->isScoped())
  1627. return false;
  1628. // We can perform an integral promotion to the underlying type of the enum,
  1629. // even if that's not the promoted type. Note that the check for promoting
  1630. // the underlying type is based on the type alone, and does not consider
  1631. // the bitfield-ness of the actual source expression.
  1632. if (FromEnumType->getDecl()->isFixed()) {
  1633. QualType Underlying = FromEnumType->getDecl()->getIntegerType();
  1634. return Context.hasSameUnqualifiedType(Underlying, ToType) ||
  1635. IsIntegralPromotion(nullptr, Underlying, ToType);
  1636. }
  1637. // We have already pre-calculated the promotion type, so this is trivial.
  1638. if (ToType->isIntegerType() &&
  1639. !RequireCompleteType(From->getLocStart(), FromType, 0))
  1640. return Context.hasSameUnqualifiedType(
  1641. ToType, FromEnumType->getDecl()->getPromotionType());
  1642. }
  1643. // C++0x [conv.prom]p2:
  1644. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1645. // to an rvalue a prvalue of the first of the following types that can
  1646. // represent all the values of its underlying type: int, unsigned int,
  1647. // long int, unsigned long int, long long int, or unsigned long long int.
  1648. // If none of the types in that list can represent all the values of its
  1649. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1650. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1651. // type.
  1652. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1653. ToType->isIntegerType()) {
  1654. // Determine whether the type we're converting from is signed or
  1655. // unsigned.
  1656. bool FromIsSigned = FromType->isSignedIntegerType();
  1657. uint64_t FromSize = Context.getTypeSize(FromType);
  1658. // The types we'll try to promote to, in the appropriate
  1659. // order. Try each of these types.
  1660. QualType PromoteTypes[6] = {
  1661. Context.IntTy, Context.UnsignedIntTy,
  1662. Context.LongTy, Context.UnsignedLongTy ,
  1663. Context.LongLongTy, Context.UnsignedLongLongTy
  1664. };
  1665. for (int Idx = 0; Idx < 6; ++Idx) {
  1666. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1667. if (FromSize < ToSize ||
  1668. (FromSize == ToSize &&
  1669. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1670. // We found the type that we can promote to. If this is the
  1671. // type we wanted, we have a promotion. Otherwise, no
  1672. // promotion.
  1673. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1674. }
  1675. }
  1676. }
  1677. // An rvalue for an integral bit-field (9.6) can be converted to an
  1678. // rvalue of type int if int can represent all the values of the
  1679. // bit-field; otherwise, it can be converted to unsigned int if
  1680. // unsigned int can represent all the values of the bit-field. If
  1681. // the bit-field is larger yet, no integral promotion applies to
  1682. // it. If the bit-field has an enumerated type, it is treated as any
  1683. // other value of that type for promotion purposes (C++ 4.5p3).
  1684. // FIXME: We should delay checking of bit-fields until we actually perform the
  1685. // conversion.
  1686. if (From) {
  1687. if (FieldDecl *MemberDecl = From->getSourceBitField()) {
  1688. llvm::APSInt BitWidth;
  1689. if (FromType->isIntegralType(Context) &&
  1690. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1691. llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1692. ToSize = Context.getTypeSize(ToType);
  1693. // Are we promoting to an int from a bitfield that fits in an int?
  1694. if (BitWidth < ToSize ||
  1695. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1696. return To->getKind() == BuiltinType::Int;
  1697. }
  1698. // Are we promoting to an unsigned int from an unsigned bitfield
  1699. // that fits into an unsigned int?
  1700. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1701. return To->getKind() == BuiltinType::UInt;
  1702. }
  1703. return false;
  1704. }
  1705. }
  1706. }
  1707. // An rvalue of type bool can be converted to an rvalue of type int,
  1708. // with false becoming zero and true becoming one (C++ 4.5p4).
  1709. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1710. return true;
  1711. }
  1712. return false;
  1713. }
  1714. /// IsFloatingPointPromotion - Determines whether the conversion from
  1715. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1716. /// returns true and sets PromotedType to the promoted type.
  1717. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1718. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1719. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1720. /// An rvalue of type float can be converted to an rvalue of type
  1721. /// double. (C++ 4.6p1).
  1722. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1723. ToBuiltin->getKind() == BuiltinType::Double)
  1724. return true;
  1725. // C99 6.3.1.5p1:
  1726. // When a float is promoted to double or long double, or a
  1727. // double is promoted to long double [...].
  1728. if (!getLangOpts().CPlusPlus &&
  1729. (FromBuiltin->getKind() == BuiltinType::Float ||
  1730. FromBuiltin->getKind() == BuiltinType::Double) &&
  1731. (ToBuiltin->getKind() == BuiltinType::LongDouble))
  1732. return true;
  1733. // Half can be promoted to float.
  1734. if (!getLangOpts().NativeHalfType &&
  1735. FromBuiltin->getKind() == BuiltinType::Half &&
  1736. ToBuiltin->getKind() == BuiltinType::Float)
  1737. return true;
  1738. // HLSL Change Starts
  1739. // TODO: Update this for new builtin types min16float, min16int, min16uint.
  1740. if (getLangOpts().HLSL) {
  1741. if (FromBuiltin->getKind() == BuiltinType::LitFloat &&
  1742. (ToBuiltin->getKind() == BuiltinType::Min10Float ||
  1743. ToBuiltin->getKind() == BuiltinType::HalfFloat ||
  1744. ToBuiltin->getKind() == BuiltinType::Float ||
  1745. ToBuiltin->getKind() == BuiltinType::Half ||
  1746. ToBuiltin->getKind() == BuiltinType::Double))
  1747. return true;
  1748. if (FromBuiltin->getKind() == BuiltinType::Min10Float &&
  1749. (ToBuiltin->getKind() == BuiltinType::Float ||
  1750. ToBuiltin->getKind() == BuiltinType::HalfFloat ||
  1751. ToBuiltin->getKind() == BuiltinType::Half ||
  1752. ToBuiltin->getKind() == BuiltinType::Double))
  1753. return true;
  1754. }
  1755. // HLSL Change Ends
  1756. }
  1757. return false;
  1758. }
  1759. /// \brief Determine if a conversion is a complex promotion.
  1760. ///
  1761. /// A complex promotion is defined as a complex -> complex conversion
  1762. /// where the conversion between the underlying real types is a
  1763. /// floating-point or integral promotion.
  1764. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1765. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1766. if (!FromComplex)
  1767. return false;
  1768. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1769. if (!ToComplex)
  1770. return false;
  1771. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1772. ToComplex->getElementType()) ||
  1773. IsIntegralPromotion(nullptr, FromComplex->getElementType(),
  1774. ToComplex->getElementType());
  1775. }
  1776. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1777. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1778. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1779. /// if non-empty, will be a pointer to ToType that may or may not have
  1780. /// the right set of qualifiers on its pointee.
  1781. ///
  1782. static QualType
  1783. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  1784. QualType ToPointee, QualType ToType,
  1785. ASTContext &Context,
  1786. bool StripObjCLifetime = false) {
  1787. assert((FromPtr->getTypeClass() == Type::Pointer ||
  1788. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  1789. "Invalid similarly-qualified pointer type");
  1790. /// Conversions to 'id' subsume cv-qualifier conversions.
  1791. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  1792. return ToType.getUnqualifiedType();
  1793. QualType CanonFromPointee
  1794. = Context.getCanonicalType(FromPtr->getPointeeType());
  1795. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  1796. Qualifiers Quals = CanonFromPointee.getQualifiers();
  1797. if (StripObjCLifetime)
  1798. Quals.removeObjCLifetime();
  1799. // Exact qualifier match -> return the pointer type we're converting to.
  1800. if (CanonToPointee.getLocalQualifiers() == Quals) {
  1801. // ToType is exactly what we need. Return it.
  1802. if (!ToType.isNull())
  1803. return ToType.getUnqualifiedType();
  1804. // Build a pointer to ToPointee. It has the right qualifiers
  1805. // already.
  1806. if (isa<ObjCObjectPointerType>(ToType))
  1807. return Context.getObjCObjectPointerType(ToPointee);
  1808. return Context.getPointerType(ToPointee);
  1809. }
  1810. // Just build a canonical type that has the right qualifiers.
  1811. QualType QualifiedCanonToPointee
  1812. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  1813. if (isa<ObjCObjectPointerType>(ToType))
  1814. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  1815. return Context.getPointerType(QualifiedCanonToPointee);
  1816. }
  1817. static bool isNullPointerConstantForConversion(Expr *Expr,
  1818. bool InOverloadResolution,
  1819. ASTContext &Context) {
  1820. // Handle value-dependent integral null pointer constants correctly.
  1821. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  1822. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  1823. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  1824. return !InOverloadResolution;
  1825. return Expr->isNullPointerConstant(Context,
  1826. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  1827. : Expr::NPC_ValueDependentIsNull);
  1828. }
  1829. /// IsPointerConversion - Determines whether the conversion of the
  1830. /// expression From, which has the (possibly adjusted) type FromType,
  1831. /// can be converted to the type ToType via a pointer conversion (C++
  1832. /// 4.10). If so, returns true and places the converted type (that
  1833. /// might differ from ToType in its cv-qualifiers at some level) into
  1834. /// ConvertedType.
  1835. ///
  1836. /// This routine also supports conversions to and from block pointers
  1837. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  1838. /// pointers to interfaces. FIXME: Once we've determined the
  1839. /// appropriate overloading rules for Objective-C, we may want to
  1840. /// split the Objective-C checks into a different routine; however,
  1841. /// GCC seems to consider all of these conversions to be pointer
  1842. /// conversions, so for now they live here. IncompatibleObjC will be
  1843. /// set if the conversion is an allowed Objective-C conversion that
  1844. /// should result in a warning.
  1845. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  1846. bool InOverloadResolution,
  1847. QualType& ConvertedType,
  1848. bool &IncompatibleObjC) {
  1849. IncompatibleObjC = false;
  1850. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  1851. IncompatibleObjC))
  1852. return true;
  1853. // Conversion from a null pointer constant to any Objective-C pointer type.
  1854. if (ToType->isObjCObjectPointerType() &&
  1855. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1856. ConvertedType = ToType;
  1857. return true;
  1858. }
  1859. // Blocks: Block pointers can be converted to void*.
  1860. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  1861. ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
  1862. ConvertedType = ToType;
  1863. return true;
  1864. }
  1865. // Blocks: A null pointer constant can be converted to a block
  1866. // pointer type.
  1867. if (ToType->isBlockPointerType() &&
  1868. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1869. ConvertedType = ToType;
  1870. return true;
  1871. }
  1872. // If the left-hand-side is nullptr_t, the right side can be a null
  1873. // pointer constant.
  1874. if (ToType->isNullPtrType() &&
  1875. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1876. ConvertedType = ToType;
  1877. return true;
  1878. }
  1879. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  1880. if (!ToTypePtr)
  1881. return false;
  1882. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  1883. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1884. ConvertedType = ToType;
  1885. return true;
  1886. }
  1887. // Beyond this point, both types need to be pointers
  1888. // , including objective-c pointers.
  1889. QualType ToPointeeType = ToTypePtr->getPointeeType();
  1890. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  1891. !getLangOpts().ObjCAutoRefCount) {
  1892. ConvertedType = BuildSimilarlyQualifiedPointerType(
  1893. FromType->getAs<ObjCObjectPointerType>(),
  1894. ToPointeeType,
  1895. ToType, Context);
  1896. return true;
  1897. }
  1898. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  1899. if (!FromTypePtr)
  1900. return false;
  1901. QualType FromPointeeType = FromTypePtr->getPointeeType();
  1902. // If the unqualified pointee types are the same, this can't be a
  1903. // pointer conversion, so don't do all of the work below.
  1904. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  1905. return false;
  1906. // An rvalue of type "pointer to cv T," where T is an object type,
  1907. // can be converted to an rvalue of type "pointer to cv void" (C++
  1908. // 4.10p2).
  1909. if (FromPointeeType->isIncompleteOrObjectType() &&
  1910. ToPointeeType->isVoidType()) {
  1911. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1912. ToPointeeType,
  1913. ToType, Context,
  1914. /*StripObjCLifetime=*/true);
  1915. return true;
  1916. }
  1917. // MSVC allows implicit function to void* type conversion.
  1918. if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
  1919. ToPointeeType->isVoidType()) {
  1920. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1921. ToPointeeType,
  1922. ToType, Context);
  1923. return true;
  1924. }
  1925. // When we're overloading in C, we allow a special kind of pointer
  1926. // conversion for compatible-but-not-identical pointee types.
  1927. if (!getLangOpts().CPlusPlus &&
  1928. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  1929. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1930. ToPointeeType,
  1931. ToType, Context);
  1932. return true;
  1933. }
  1934. // C++ [conv.ptr]p3:
  1935. //
  1936. // An rvalue of type "pointer to cv D," where D is a class type,
  1937. // can be converted to an rvalue of type "pointer to cv B," where
  1938. // B is a base class (clause 10) of D. If B is an inaccessible
  1939. // (clause 11) or ambiguous (10.2) base class of D, a program that
  1940. // necessitates this conversion is ill-formed. The result of the
  1941. // conversion is a pointer to the base class sub-object of the
  1942. // derived class object. The null pointer value is converted to
  1943. // the null pointer value of the destination type.
  1944. //
  1945. // Note that we do not check for ambiguity or inaccessibility
  1946. // here. That is handled by CheckPointerConversion.
  1947. if (getLangOpts().CPlusPlus &&
  1948. FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  1949. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  1950. !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
  1951. IsDerivedFrom(FromPointeeType, ToPointeeType)) {
  1952. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1953. ToPointeeType,
  1954. ToType, Context);
  1955. return true;
  1956. }
  1957. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  1958. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  1959. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1960. ToPointeeType,
  1961. ToType, Context);
  1962. return true;
  1963. }
  1964. return false;
  1965. }
  1966. /// \brief Adopt the given qualifiers for the given type.
  1967. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  1968. Qualifiers TQs = T.getQualifiers();
  1969. // Check whether qualifiers already match.
  1970. if (TQs == Qs)
  1971. return T;
  1972. if (Qs.compatiblyIncludes(TQs))
  1973. return Context.getQualifiedType(T, Qs);
  1974. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  1975. }
  1976. /// isObjCPointerConversion - Determines whether this is an
  1977. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  1978. /// with the same arguments and return values.
  1979. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  1980. QualType& ConvertedType,
  1981. bool &IncompatibleObjC) {
  1982. if (!getLangOpts().ObjC1)
  1983. return false;
  1984. // The set of qualifiers on the type we're converting from.
  1985. Qualifiers FromQualifiers = FromType.getQualifiers();
  1986. // First, we handle all conversions on ObjC object pointer types.
  1987. const ObjCObjectPointerType* ToObjCPtr =
  1988. ToType->getAs<ObjCObjectPointerType>();
  1989. const ObjCObjectPointerType *FromObjCPtr =
  1990. FromType->getAs<ObjCObjectPointerType>();
  1991. if (ToObjCPtr && FromObjCPtr) {
  1992. // If the pointee types are the same (ignoring qualifications),
  1993. // then this is not a pointer conversion.
  1994. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  1995. FromObjCPtr->getPointeeType()))
  1996. return false;
  1997. // Conversion between Objective-C pointers.
  1998. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  1999. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  2000. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  2001. if (getLangOpts().CPlusPlus && LHS && RHS &&
  2002. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  2003. FromObjCPtr->getPointeeType()))
  2004. return false;
  2005. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2006. ToObjCPtr->getPointeeType(),
  2007. ToType, Context);
  2008. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2009. return true;
  2010. }
  2011. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  2012. // Okay: this is some kind of implicit downcast of Objective-C
  2013. // interfaces, which is permitted. However, we're going to
  2014. // complain about it.
  2015. IncompatibleObjC = true;
  2016. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  2017. ToObjCPtr->getPointeeType(),
  2018. ToType, Context);
  2019. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2020. return true;
  2021. }
  2022. }
  2023. // Beyond this point, both types need to be C pointers or block pointers.
  2024. QualType ToPointeeType;
  2025. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  2026. ToPointeeType = ToCPtr->getPointeeType();
  2027. else if (const BlockPointerType *ToBlockPtr =
  2028. ToType->getAs<BlockPointerType>()) {
  2029. // Objective C++: We're able to convert from a pointer to any object
  2030. // to a block pointer type.
  2031. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  2032. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2033. return true;
  2034. }
  2035. ToPointeeType = ToBlockPtr->getPointeeType();
  2036. }
  2037. else if (FromType->getAs<BlockPointerType>() &&
  2038. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  2039. // Objective C++: We're able to convert from a block pointer type to a
  2040. // pointer to any object.
  2041. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2042. return true;
  2043. }
  2044. else
  2045. return false;
  2046. QualType FromPointeeType;
  2047. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  2048. FromPointeeType = FromCPtr->getPointeeType();
  2049. else if (const BlockPointerType *FromBlockPtr =
  2050. FromType->getAs<BlockPointerType>())
  2051. FromPointeeType = FromBlockPtr->getPointeeType();
  2052. else
  2053. return false;
  2054. // If we have pointers to pointers, recursively check whether this
  2055. // is an Objective-C conversion.
  2056. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  2057. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2058. IncompatibleObjC)) {
  2059. // We always complain about this conversion.
  2060. IncompatibleObjC = true;
  2061. ConvertedType = Context.getPointerType(ConvertedType);
  2062. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2063. return true;
  2064. }
  2065. // Allow conversion of pointee being objective-c pointer to another one;
  2066. // as in I* to id.
  2067. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  2068. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  2069. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  2070. IncompatibleObjC)) {
  2071. ConvertedType = Context.getPointerType(ConvertedType);
  2072. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  2073. return true;
  2074. }
  2075. // If we have pointers to functions or blocks, check whether the only
  2076. // differences in the argument and result types are in Objective-C
  2077. // pointer conversions. If so, we permit the conversion (but
  2078. // complain about it).
  2079. const FunctionProtoType *FromFunctionType
  2080. = FromPointeeType->getAs<FunctionProtoType>();
  2081. const FunctionProtoType *ToFunctionType
  2082. = ToPointeeType->getAs<FunctionProtoType>();
  2083. if (FromFunctionType && ToFunctionType) {
  2084. // If the function types are exactly the same, this isn't an
  2085. // Objective-C pointer conversion.
  2086. if (Context.getCanonicalType(FromPointeeType)
  2087. == Context.getCanonicalType(ToPointeeType))
  2088. return false;
  2089. // Perform the quick checks that will tell us whether these
  2090. // function types are obviously different.
  2091. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2092. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  2093. FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
  2094. return false;
  2095. bool HasObjCConversion = false;
  2096. if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
  2097. Context.getCanonicalType(ToFunctionType->getReturnType())) {
  2098. // Okay, the types match exactly. Nothing to do.
  2099. } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
  2100. ToFunctionType->getReturnType(),
  2101. ConvertedType, IncompatibleObjC)) {
  2102. // Okay, we have an Objective-C pointer conversion.
  2103. HasObjCConversion = true;
  2104. } else {
  2105. // Function types are too different. Abort.
  2106. return false;
  2107. }
  2108. // Check argument types.
  2109. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2110. ArgIdx != NumArgs; ++ArgIdx) {
  2111. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2112. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2113. if (Context.getCanonicalType(FromArgType)
  2114. == Context.getCanonicalType(ToArgType)) {
  2115. // Okay, the types match exactly. Nothing to do.
  2116. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2117. ConvertedType, IncompatibleObjC)) {
  2118. // Okay, we have an Objective-C pointer conversion.
  2119. HasObjCConversion = true;
  2120. } else {
  2121. // Argument types are too different. Abort.
  2122. return false;
  2123. }
  2124. }
  2125. if (HasObjCConversion) {
  2126. // We had an Objective-C conversion. Allow this pointer
  2127. // conversion, but complain about it.
  2128. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2129. IncompatibleObjC = true;
  2130. return true;
  2131. }
  2132. }
  2133. return false;
  2134. }
  2135. /// \brief Determine whether this is an Objective-C writeback conversion,
  2136. /// used for parameter passing when performing automatic reference counting.
  2137. ///
  2138. /// \param FromType The type we're converting form.
  2139. ///
  2140. /// \param ToType The type we're converting to.
  2141. ///
  2142. /// \param ConvertedType The type that will be produced after applying
  2143. /// this conversion.
  2144. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2145. QualType &ConvertedType) {
  2146. if (!getLangOpts().ObjCAutoRefCount ||
  2147. Context.hasSameUnqualifiedType(FromType, ToType))
  2148. return false;
  2149. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2150. QualType ToPointee;
  2151. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2152. ToPointee = ToPointer->getPointeeType();
  2153. else
  2154. return false;
  2155. Qualifiers ToQuals = ToPointee.getQualifiers();
  2156. if (!ToPointee->isObjCLifetimeType() ||
  2157. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2158. !ToQuals.withoutObjCLifetime().empty())
  2159. return false;
  2160. // Argument must be a pointer to __strong to __weak.
  2161. QualType FromPointee;
  2162. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2163. FromPointee = FromPointer->getPointeeType();
  2164. else
  2165. return false;
  2166. Qualifiers FromQuals = FromPointee.getQualifiers();
  2167. if (!FromPointee->isObjCLifetimeType() ||
  2168. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2169. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2170. return false;
  2171. // Make sure that we have compatible qualifiers.
  2172. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2173. if (!ToQuals.compatiblyIncludes(FromQuals))
  2174. return false;
  2175. // Remove qualifiers from the pointee type we're converting from; they
  2176. // aren't used in the compatibility check belong, and we'll be adding back
  2177. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2178. FromPointee = FromPointee.getUnqualifiedType();
  2179. // The unqualified form of the pointee types must be compatible.
  2180. ToPointee = ToPointee.getUnqualifiedType();
  2181. bool IncompatibleObjC;
  2182. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2183. FromPointee = ToPointee;
  2184. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2185. IncompatibleObjC))
  2186. return false;
  2187. /// \brief Construct the type we're converting to, which is a pointer to
  2188. /// __autoreleasing pointee.
  2189. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2190. ConvertedType = Context.getPointerType(FromPointee);
  2191. return true;
  2192. }
  2193. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2194. QualType& ConvertedType) {
  2195. QualType ToPointeeType;
  2196. if (const BlockPointerType *ToBlockPtr =
  2197. ToType->getAs<BlockPointerType>())
  2198. ToPointeeType = ToBlockPtr->getPointeeType();
  2199. else
  2200. return false;
  2201. QualType FromPointeeType;
  2202. if (const BlockPointerType *FromBlockPtr =
  2203. FromType->getAs<BlockPointerType>())
  2204. FromPointeeType = FromBlockPtr->getPointeeType();
  2205. else
  2206. return false;
  2207. // We have pointer to blocks, check whether the only
  2208. // differences in the argument and result types are in Objective-C
  2209. // pointer conversions. If so, we permit the conversion.
  2210. const FunctionProtoType *FromFunctionType
  2211. = FromPointeeType->getAs<FunctionProtoType>();
  2212. const FunctionProtoType *ToFunctionType
  2213. = ToPointeeType->getAs<FunctionProtoType>();
  2214. if (!FromFunctionType || !ToFunctionType)
  2215. return false;
  2216. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2217. return true;
  2218. // Perform the quick checks that will tell us whether these
  2219. // function types are obviously different.
  2220. if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
  2221. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2222. return false;
  2223. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2224. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2225. if (FromEInfo != ToEInfo)
  2226. return false;
  2227. bool IncompatibleObjC = false;
  2228. if (Context.hasSameType(FromFunctionType->getReturnType(),
  2229. ToFunctionType->getReturnType())) {
  2230. // Okay, the types match exactly. Nothing to do.
  2231. } else {
  2232. QualType RHS = FromFunctionType->getReturnType();
  2233. QualType LHS = ToFunctionType->getReturnType();
  2234. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2235. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2236. LHS = LHS.getUnqualifiedType();
  2237. if (Context.hasSameType(RHS,LHS)) {
  2238. // OK exact match.
  2239. } else if (isObjCPointerConversion(RHS, LHS,
  2240. ConvertedType, IncompatibleObjC)) {
  2241. if (IncompatibleObjC)
  2242. return false;
  2243. // Okay, we have an Objective-C pointer conversion.
  2244. }
  2245. else
  2246. return false;
  2247. }
  2248. // Check argument types.
  2249. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
  2250. ArgIdx != NumArgs; ++ArgIdx) {
  2251. IncompatibleObjC = false;
  2252. QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
  2253. QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
  2254. if (Context.hasSameType(FromArgType, ToArgType)) {
  2255. // Okay, the types match exactly. Nothing to do.
  2256. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2257. ConvertedType, IncompatibleObjC)) {
  2258. if (IncompatibleObjC)
  2259. return false;
  2260. // Okay, we have an Objective-C pointer conversion.
  2261. } else
  2262. // Argument types are too different. Abort.
  2263. return false;
  2264. }
  2265. if (LangOpts.ObjCAutoRefCount &&
  2266. !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
  2267. ToFunctionType))
  2268. return false;
  2269. ConvertedType = ToType;
  2270. return true;
  2271. }
  2272. enum {
  2273. ft_default,
  2274. ft_different_class,
  2275. ft_parameter_arity,
  2276. ft_parameter_mismatch,
  2277. ft_return_type,
  2278. ft_qualifer_mismatch
  2279. };
  2280. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2281. /// function types. Catches different number of parameter, mismatch in
  2282. /// parameter types, and different return types.
  2283. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2284. QualType FromType, QualType ToType) {
  2285. // If either type is not valid, include no extra info.
  2286. if (FromType.isNull() || ToType.isNull()) {
  2287. PDiag << ft_default;
  2288. return;
  2289. }
  2290. // Get the function type from the pointers.
  2291. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2292. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2293. *ToMember = ToType->getAs<MemberPointerType>();
  2294. if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
  2295. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2296. << QualType(FromMember->getClass(), 0);
  2297. return;
  2298. }
  2299. FromType = FromMember->getPointeeType();
  2300. ToType = ToMember->getPointeeType();
  2301. }
  2302. if (FromType->isPointerType())
  2303. FromType = FromType->getPointeeType();
  2304. if (ToType->isPointerType())
  2305. ToType = ToType->getPointeeType();
  2306. // Remove references.
  2307. FromType = FromType.getNonReferenceType();
  2308. ToType = ToType.getNonReferenceType();
  2309. // Don't print extra info for non-specialized template functions.
  2310. if (FromType->isInstantiationDependentType() &&
  2311. !FromType->getAs<TemplateSpecializationType>()) {
  2312. PDiag << ft_default;
  2313. return;
  2314. }
  2315. // No extra info for same types.
  2316. if (Context.hasSameType(FromType, ToType)) {
  2317. PDiag << ft_default;
  2318. return;
  2319. }
  2320. const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
  2321. *ToFunction = ToType->getAs<FunctionProtoType>();
  2322. // Both types need to be function types.
  2323. if (!FromFunction || !ToFunction) {
  2324. PDiag << ft_default;
  2325. return;
  2326. }
  2327. if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
  2328. PDiag << ft_parameter_arity << ToFunction->getNumParams()
  2329. << FromFunction->getNumParams();
  2330. return;
  2331. }
  2332. // Handle different parameter types.
  2333. unsigned ArgPos;
  2334. if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2335. PDiag << ft_parameter_mismatch << ArgPos + 1
  2336. << ToFunction->getParamType(ArgPos)
  2337. << FromFunction->getParamType(ArgPos);
  2338. return;
  2339. }
  2340. // Handle different return type.
  2341. if (!Context.hasSameType(FromFunction->getReturnType(),
  2342. ToFunction->getReturnType())) {
  2343. PDiag << ft_return_type << ToFunction->getReturnType()
  2344. << FromFunction->getReturnType();
  2345. return;
  2346. }
  2347. unsigned FromQuals = FromFunction->getTypeQuals(),
  2348. ToQuals = ToFunction->getTypeQuals();
  2349. if (FromQuals != ToQuals) {
  2350. PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
  2351. return;
  2352. }
  2353. // Unable to find a difference, so add no extra info.
  2354. PDiag << ft_default;
  2355. }
  2356. /// FunctionParamTypesAreEqual - This routine checks two function proto types
  2357. /// for equality of their argument types. Caller has already checked that
  2358. /// they have same number of arguments. If the parameters are different,
  2359. /// ArgPos will have the parameter index of the first different parameter.
  2360. bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
  2361. const FunctionProtoType *NewType,
  2362. unsigned *ArgPos) {
  2363. int index = 0;
  2364. for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
  2365. N = NewType->param_type_begin(),
  2366. E = OldType->param_type_end();
  2367. O && (O != E); ++O, ++N) {
  2368. if (!Context.hasSameType(O->getUnqualifiedType(),
  2369. N->getUnqualifiedType())
  2370. || OldType->getParamMods()[index] != NewType->getParamMods()[index]) { // HLSL Change - check param mods
  2371. index++;
  2372. if (ArgPos)
  2373. *ArgPos = O - OldType->param_type_begin();
  2374. return false;
  2375. }
  2376. }
  2377. return true;
  2378. }
  2379. /// CheckPointerConversion - Check the pointer conversion from the
  2380. /// expression From to the type ToType. This routine checks for
  2381. /// ambiguous or inaccessible derived-to-base pointer
  2382. /// conversions for which IsPointerConversion has already returned
  2383. /// true. It returns true and produces a diagnostic if there was an
  2384. /// error, or returns false otherwise.
  2385. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2386. CastKind &Kind,
  2387. CXXCastPath& BasePath,
  2388. bool IgnoreBaseAccess) {
  2389. QualType FromType = From->getType();
  2390. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2391. Kind = CK_BitCast;
  2392. if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2393. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2394. Expr::NPCK_ZeroExpression) {
  2395. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2396. DiagRuntimeBehavior(From->getExprLoc(), From,
  2397. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2398. << ToType << From->getSourceRange());
  2399. else if (!isUnevaluatedContext())
  2400. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2401. << ToType << From->getSourceRange();
  2402. }
  2403. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2404. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2405. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2406. ToPointeeType = ToPtrType->getPointeeType();
  2407. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2408. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2409. // We must have a derived-to-base conversion. Check an
  2410. // ambiguous or inaccessible conversion.
  2411. if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
  2412. From->getExprLoc(),
  2413. From->getSourceRange(), &BasePath,
  2414. IgnoreBaseAccess))
  2415. return true;
  2416. // The conversion was successful.
  2417. Kind = CK_DerivedToBase;
  2418. }
  2419. }
  2420. } else if (const ObjCObjectPointerType *ToPtrType =
  2421. ToType->getAs<ObjCObjectPointerType>()) {
  2422. if (const ObjCObjectPointerType *FromPtrType =
  2423. FromType->getAs<ObjCObjectPointerType>()) {
  2424. // Objective-C++ conversions are always okay.
  2425. // FIXME: We should have a different class of conversions for the
  2426. // Objective-C++ implicit conversions.
  2427. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2428. return false;
  2429. } else if (FromType->isBlockPointerType()) {
  2430. Kind = CK_BlockPointerToObjCPointerCast;
  2431. } else {
  2432. Kind = CK_CPointerToObjCPointerCast;
  2433. }
  2434. } else if (ToType->isBlockPointerType()) {
  2435. if (!FromType->isBlockPointerType())
  2436. Kind = CK_AnyPointerToBlockPointerCast;
  2437. }
  2438. // We shouldn't fall into this case unless it's valid for other
  2439. // reasons.
  2440. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2441. Kind = CK_NullToPointer;
  2442. return false;
  2443. }
  2444. /// IsMemberPointerConversion - Determines whether the conversion of the
  2445. /// expression From, which has the (possibly adjusted) type FromType, can be
  2446. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2447. /// If so, returns true and places the converted type (that might differ from
  2448. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2449. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2450. QualType ToType,
  2451. bool InOverloadResolution,
  2452. QualType &ConvertedType) {
  2453. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2454. if (!ToTypePtr)
  2455. return false;
  2456. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2457. if (From->isNullPointerConstant(Context,
  2458. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2459. : Expr::NPC_ValueDependentIsNull)) {
  2460. ConvertedType = ToType;
  2461. return true;
  2462. }
  2463. // Otherwise, both types have to be member pointers.
  2464. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2465. if (!FromTypePtr)
  2466. return false;
  2467. // A pointer to member of B can be converted to a pointer to member of D,
  2468. // where D is derived from B (C++ 4.11p2).
  2469. QualType FromClass(FromTypePtr->getClass(), 0);
  2470. QualType ToClass(ToTypePtr->getClass(), 0);
  2471. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2472. !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
  2473. IsDerivedFrom(ToClass, FromClass)) {
  2474. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2475. ToClass.getTypePtr());
  2476. return true;
  2477. }
  2478. return false;
  2479. }
  2480. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2481. /// expression From to the type ToType. This routine checks for ambiguous or
  2482. /// virtual or inaccessible base-to-derived member pointer conversions
  2483. /// for which IsMemberPointerConversion has already returned true. It returns
  2484. /// true and produces a diagnostic if there was an error, or returns false
  2485. /// otherwise.
  2486. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2487. CastKind &Kind,
  2488. CXXCastPath &BasePath,
  2489. bool IgnoreBaseAccess) {
  2490. QualType FromType = From->getType();
  2491. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2492. if (!FromPtrType) {
  2493. // This must be a null pointer to member pointer conversion
  2494. assert(From->isNullPointerConstant(Context,
  2495. Expr::NPC_ValueDependentIsNull) &&
  2496. "Expr must be null pointer constant!");
  2497. Kind = CK_NullToMemberPointer;
  2498. return false;
  2499. }
  2500. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2501. assert(ToPtrType && "No member pointer cast has a target type "
  2502. "that is not a member pointer.");
  2503. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2504. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2505. // FIXME: What about dependent types?
  2506. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2507. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2508. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2509. /*DetectVirtual=*/true);
  2510. bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
  2511. assert(DerivationOkay &&
  2512. "Should not have been called if derivation isn't OK.");
  2513. (void)DerivationOkay;
  2514. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2515. getUnqualifiedType())) {
  2516. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2517. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2518. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2519. return true;
  2520. }
  2521. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2522. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2523. << FromClass << ToClass << QualType(VBase, 0)
  2524. << From->getSourceRange();
  2525. return true;
  2526. }
  2527. if (!IgnoreBaseAccess)
  2528. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2529. Paths.front(),
  2530. diag::err_downcast_from_inaccessible_base);
  2531. // Must be a base to derived member conversion.
  2532. BuildBasePathArray(Paths, BasePath);
  2533. Kind = CK_BaseToDerivedMemberPointer;
  2534. return false;
  2535. }
  2536. /// Determine whether the lifetime conversion between the two given
  2537. /// qualifiers sets is nontrivial.
  2538. static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
  2539. Qualifiers ToQuals) {
  2540. // Converting anything to const __unsafe_unretained is trivial.
  2541. if (ToQuals.hasConst() &&
  2542. ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  2543. return false;
  2544. return true;
  2545. }
  2546. /// IsQualificationConversion - Determines whether the conversion from
  2547. /// an rvalue of type FromType to ToType is a qualification conversion
  2548. /// (C++ 4.4).
  2549. ///
  2550. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2551. /// when the qualification conversion involves a change in the Objective-C
  2552. /// object lifetime.
  2553. bool
  2554. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2555. bool CStyle, bool &ObjCLifetimeConversion) {
  2556. FromType = Context.getCanonicalType(FromType);
  2557. ToType = Context.getCanonicalType(ToType);
  2558. ObjCLifetimeConversion = false;
  2559. // If FromType and ToType are the same type, this is not a
  2560. // qualification conversion.
  2561. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2562. return false;
  2563. // (C++ 4.4p4):
  2564. // A conversion can add cv-qualifiers at levels other than the first
  2565. // in multi-level pointers, subject to the following rules: [...]
  2566. bool PreviousToQualsIncludeConst = true;
  2567. bool UnwrappedAnyPointer = false;
  2568. while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
  2569. // Within each iteration of the loop, we check the qualifiers to
  2570. // determine if this still looks like a qualification
  2571. // conversion. Then, if all is well, we unwrap one more level of
  2572. // pointers or pointers-to-members and do it all again
  2573. // until there are no more pointers or pointers-to-members left to
  2574. // unwrap.
  2575. UnwrappedAnyPointer = true;
  2576. Qualifiers FromQuals = FromType.getQualifiers();
  2577. Qualifiers ToQuals = ToType.getQualifiers();
  2578. // Objective-C ARC:
  2579. // Check Objective-C lifetime conversions.
  2580. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2581. UnwrappedAnyPointer) {
  2582. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2583. if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
  2584. ObjCLifetimeConversion = true;
  2585. FromQuals.removeObjCLifetime();
  2586. ToQuals.removeObjCLifetime();
  2587. } else {
  2588. // Qualification conversions cannot cast between different
  2589. // Objective-C lifetime qualifiers.
  2590. return false;
  2591. }
  2592. }
  2593. // Allow addition/removal of GC attributes but not changing GC attributes.
  2594. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2595. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2596. FromQuals.removeObjCGCAttr();
  2597. ToQuals.removeObjCGCAttr();
  2598. }
  2599. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2600. // 2,j, and similarly for volatile.
  2601. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2602. return false;
  2603. // -- if the cv 1,j and cv 2,j are different, then const is in
  2604. // every cv for 0 < k < j.
  2605. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2606. && !PreviousToQualsIncludeConst)
  2607. return false;
  2608. // Keep track of whether all prior cv-qualifiers in the "to" type
  2609. // include const.
  2610. PreviousToQualsIncludeConst
  2611. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2612. }
  2613. // We are left with FromType and ToType being the pointee types
  2614. // after unwrapping the original FromType and ToType the same number
  2615. // of types. If we unwrapped any pointers, and if FromType and
  2616. // ToType have the same unqualified type (since we checked
  2617. // qualifiers above), then this is a qualification conversion.
  2618. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2619. }
  2620. /// \brief - Determine whether this is a conversion from a scalar type to an
  2621. /// atomic type.
  2622. ///
  2623. /// If successful, updates \c SCS's second and third steps in the conversion
  2624. /// sequence to finish the conversion.
  2625. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2626. bool InOverloadResolution,
  2627. StandardConversionSequence &SCS,
  2628. bool CStyle) {
  2629. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2630. if (!ToAtomic)
  2631. return false;
  2632. StandardConversionSequence InnerSCS;
  2633. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2634. InOverloadResolution, InnerSCS,
  2635. CStyle, /*AllowObjCWritebackConversion=*/false))
  2636. return false;
  2637. SCS.Second = InnerSCS.Second;
  2638. SCS.setToType(1, InnerSCS.getToType(1));
  2639. SCS.Third = InnerSCS.Third;
  2640. SCS.QualificationIncludesObjCLifetime
  2641. = InnerSCS.QualificationIncludesObjCLifetime;
  2642. SCS.setToType(2, InnerSCS.getToType(2));
  2643. return true;
  2644. }
  2645. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2646. CXXConstructorDecl *Constructor,
  2647. QualType Type) {
  2648. const FunctionProtoType *CtorType =
  2649. Constructor->getType()->getAs<FunctionProtoType>();
  2650. if (CtorType->getNumParams() > 0) {
  2651. QualType FirstArg = CtorType->getParamType(0);
  2652. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2653. return true;
  2654. }
  2655. return false;
  2656. }
  2657. static OverloadingResult
  2658. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2659. CXXRecordDecl *To,
  2660. UserDefinedConversionSequence &User,
  2661. OverloadCandidateSet &CandidateSet,
  2662. bool AllowExplicit) {
  2663. DeclContext::lookup_result R = S.LookupConstructors(To);
  2664. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2665. Con != ConEnd; ++Con) {
  2666. NamedDecl *D = *Con;
  2667. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2668. // Find the constructor (which may be a template).
  2669. CXXConstructorDecl *Constructor = nullptr;
  2670. FunctionTemplateDecl *ConstructorTmpl
  2671. = dyn_cast<FunctionTemplateDecl>(D);
  2672. if (ConstructorTmpl)
  2673. Constructor
  2674. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2675. else
  2676. Constructor = cast<CXXConstructorDecl>(D);
  2677. bool Usable = !Constructor->isInvalidDecl() &&
  2678. S.isInitListConstructor(Constructor) &&
  2679. (AllowExplicit || !Constructor->isExplicit());
  2680. if (Usable) {
  2681. // If the first argument is (a reference to) the target type,
  2682. // suppress conversions.
  2683. bool SuppressUserConversions =
  2684. isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
  2685. if (ConstructorTmpl)
  2686. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2687. /*ExplicitArgs*/ nullptr,
  2688. From, CandidateSet,
  2689. SuppressUserConversions);
  2690. else
  2691. S.AddOverloadCandidate(Constructor, FoundDecl,
  2692. From, CandidateSet,
  2693. SuppressUserConversions);
  2694. }
  2695. }
  2696. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2697. OverloadCandidateSet::iterator Best;
  2698. switch (auto Result =
  2699. CandidateSet.BestViableFunction(S, From->getLocStart(),
  2700. Best, true)) {
  2701. case OR_Deleted:
  2702. case OR_Success: {
  2703. // Record the standard conversion we used and the conversion function.
  2704. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2705. QualType ThisType = Constructor->getThisType(S.Context);
  2706. // Initializer lists don't have conversions as such.
  2707. User.Before.setAsIdentityConversion();
  2708. User.HadMultipleCandidates = HadMultipleCandidates;
  2709. User.ConversionFunction = Constructor;
  2710. User.FoundConversionFunction = Best->FoundDecl;
  2711. User.After.setAsIdentityConversion();
  2712. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2713. User.After.setAllToTypes(ToType);
  2714. return Result;
  2715. }
  2716. case OR_No_Viable_Function:
  2717. return OR_No_Viable_Function;
  2718. case OR_Ambiguous:
  2719. return OR_Ambiguous;
  2720. }
  2721. llvm_unreachable("Invalid OverloadResult!");
  2722. }
  2723. /// Determines whether there is a user-defined conversion sequence
  2724. /// (C++ [over.ics.user]) that converts expression From to the type
  2725. /// ToType. If such a conversion exists, User will contain the
  2726. /// user-defined conversion sequence that performs such a conversion
  2727. /// and this routine will return true. Otherwise, this routine returns
  2728. /// false and User is unspecified.
  2729. ///
  2730. /// \param AllowExplicit true if the conversion should consider C++0x
  2731. /// "explicit" conversion functions as well as non-explicit conversion
  2732. /// functions (C++0x [class.conv.fct]p2).
  2733. ///
  2734. /// \param AllowObjCConversionOnExplicit true if the conversion should
  2735. /// allow an extra Objective-C pointer conversion on uses of explicit
  2736. /// constructors. Requires \c AllowExplicit to also be set.
  2737. static OverloadingResult
  2738. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2739. UserDefinedConversionSequence &User,
  2740. OverloadCandidateSet &CandidateSet,
  2741. bool AllowExplicit,
  2742. bool AllowObjCConversionOnExplicit) {
  2743. assert(AllowExplicit || !AllowObjCConversionOnExplicit);
  2744. // Whether we will only visit constructors.
  2745. bool ConstructorsOnly = false;
  2746. // If the type we are conversion to is a class type, enumerate its
  2747. // constructors.
  2748. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2749. // C++ [over.match.ctor]p1:
  2750. // When objects of class type are direct-initialized (8.5), or
  2751. // copy-initialized from an expression of the same or a
  2752. // derived class type (8.5), overload resolution selects the
  2753. // constructor. [...] For copy-initialization, the candidate
  2754. // functions are all the converting constructors (12.3.1) of
  2755. // that class. The argument list is the expression-list within
  2756. // the parentheses of the initializer.
  2757. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  2758. (From->getType()->getAs<RecordType>() &&
  2759. S.IsDerivedFrom(From->getType(), ToType)))
  2760. ConstructorsOnly = true;
  2761. S.RequireCompleteType(From->getExprLoc(), ToType, 0);
  2762. // RequireCompleteType may have returned true due to some invalid decl
  2763. // during template instantiation, but ToType may be complete enough now
  2764. // to try to recover.
  2765. if (ToType->isIncompleteType()) {
  2766. // We're not going to find any constructors.
  2767. } else if (CXXRecordDecl *ToRecordDecl
  2768. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  2769. Expr **Args = &From;
  2770. unsigned NumArgs = 1;
  2771. bool ListInitializing = false;
  2772. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  2773. // But first, see if there is an init-list-constructor that will work.
  2774. OverloadingResult Result = IsInitializerListConstructorConversion(
  2775. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  2776. if (Result != OR_No_Viable_Function)
  2777. return Result;
  2778. // Never mind.
  2779. CandidateSet.clear();
  2780. // If we're list-initializing, we pass the individual elements as
  2781. // arguments, not the entire list.
  2782. Args = InitList->getInits();
  2783. NumArgs = InitList->getNumInits();
  2784. ListInitializing = true;
  2785. }
  2786. DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
  2787. for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
  2788. Con != ConEnd; ++Con) {
  2789. NamedDecl *D = *Con;
  2790. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2791. // Find the constructor (which may be a template).
  2792. CXXConstructorDecl *Constructor = nullptr;
  2793. FunctionTemplateDecl *ConstructorTmpl
  2794. = dyn_cast<FunctionTemplateDecl>(D);
  2795. if (ConstructorTmpl)
  2796. Constructor
  2797. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2798. else
  2799. Constructor = cast<CXXConstructorDecl>(D);
  2800. bool Usable = !Constructor->isInvalidDecl();
  2801. if (ListInitializing)
  2802. Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
  2803. else
  2804. Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
  2805. if (Usable) {
  2806. bool SuppressUserConversions = !ConstructorsOnly;
  2807. if (SuppressUserConversions && ListInitializing) {
  2808. SuppressUserConversions = false;
  2809. if (NumArgs == 1) {
  2810. // If the first argument is (a reference to) the target type,
  2811. // suppress conversions.
  2812. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2813. S.Context, Constructor, ToType);
  2814. }
  2815. }
  2816. if (ConstructorTmpl)
  2817. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2818. /*ExplicitArgs*/ nullptr,
  2819. llvm::makeArrayRef(Args, NumArgs),
  2820. CandidateSet, SuppressUserConversions);
  2821. else
  2822. // Allow one user-defined conversion when user specifies a
  2823. // From->ToType conversion via an static cast (c-style, etc).
  2824. S.AddOverloadCandidate(Constructor, FoundDecl,
  2825. llvm::makeArrayRef(Args, NumArgs),
  2826. CandidateSet, SuppressUserConversions);
  2827. }
  2828. }
  2829. }
  2830. }
  2831. // Enumerate conversion functions, if we're allowed to.
  2832. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  2833. } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
  2834. // No conversion functions from incomplete types.
  2835. } else if (const RecordType *FromRecordType
  2836. = From->getType()->getAs<RecordType>()) {
  2837. if (CXXRecordDecl *FromRecordDecl
  2838. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  2839. // Add all of the conversion functions as candidates.
  2840. const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
  2841. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  2842. DeclAccessPair FoundDecl = I.getPair();
  2843. NamedDecl *D = FoundDecl.getDecl();
  2844. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  2845. if (isa<UsingShadowDecl>(D))
  2846. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2847. CXXConversionDecl *Conv;
  2848. FunctionTemplateDecl *ConvTemplate;
  2849. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  2850. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  2851. else
  2852. Conv = cast<CXXConversionDecl>(D);
  2853. if (AllowExplicit || !Conv->isExplicit()) {
  2854. if (ConvTemplate)
  2855. S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
  2856. ActingContext, From, ToType,
  2857. CandidateSet,
  2858. AllowObjCConversionOnExplicit);
  2859. else
  2860. S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
  2861. From, ToType, CandidateSet,
  2862. AllowObjCConversionOnExplicit);
  2863. }
  2864. }
  2865. }
  2866. }
  2867. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2868. OverloadCandidateSet::iterator Best;
  2869. switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
  2870. Best, true)) {
  2871. case OR_Success:
  2872. case OR_Deleted:
  2873. // Record the standard conversion we used and the conversion function.
  2874. if (CXXConstructorDecl *Constructor
  2875. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  2876. // C++ [over.ics.user]p1:
  2877. // If the user-defined conversion is specified by a
  2878. // constructor (12.3.1), the initial standard conversion
  2879. // sequence converts the source type to the type required by
  2880. // the argument of the constructor.
  2881. //
  2882. QualType ThisType = Constructor->getThisType(S.Context);
  2883. if (isa<InitListExpr>(From)) {
  2884. // Initializer lists don't have conversions as such.
  2885. User.Before.setAsIdentityConversion();
  2886. } else {
  2887. if (Best->Conversions[0].isEllipsis())
  2888. User.EllipsisConversion = true;
  2889. else {
  2890. User.Before = Best->Conversions[0].Standard;
  2891. User.EllipsisConversion = false;
  2892. }
  2893. }
  2894. User.HadMultipleCandidates = HadMultipleCandidates;
  2895. User.ConversionFunction = Constructor;
  2896. User.FoundConversionFunction = Best->FoundDecl;
  2897. User.After.setAsIdentityConversion();
  2898. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2899. User.After.setAllToTypes(ToType);
  2900. return Result;
  2901. }
  2902. if (CXXConversionDecl *Conversion
  2903. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  2904. // C++ [over.ics.user]p1:
  2905. //
  2906. // [...] If the user-defined conversion is specified by a
  2907. // conversion function (12.3.2), the initial standard
  2908. // conversion sequence converts the source type to the
  2909. // implicit object parameter of the conversion function.
  2910. User.Before = Best->Conversions[0].Standard;
  2911. User.HadMultipleCandidates = HadMultipleCandidates;
  2912. User.ConversionFunction = Conversion;
  2913. User.FoundConversionFunction = Best->FoundDecl;
  2914. User.EllipsisConversion = false;
  2915. // C++ [over.ics.user]p2:
  2916. // The second standard conversion sequence converts the
  2917. // result of the user-defined conversion to the target type
  2918. // for the sequence. Since an implicit conversion sequence
  2919. // is an initialization, the special rules for
  2920. // initialization by user-defined conversion apply when
  2921. // selecting the best user-defined conversion for a
  2922. // user-defined conversion sequence (see 13.3.3 and
  2923. // 13.3.3.1).
  2924. User.After = Best->FinalConversion;
  2925. return Result;
  2926. }
  2927. llvm_unreachable("Not a constructor or conversion function?");
  2928. case OR_No_Viable_Function:
  2929. return OR_No_Viable_Function;
  2930. case OR_Ambiguous:
  2931. return OR_Ambiguous;
  2932. }
  2933. llvm_unreachable("Invalid OverloadResult!");
  2934. }
  2935. bool
  2936. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  2937. ImplicitConversionSequence ICS;
  2938. OverloadCandidateSet CandidateSet(From->getExprLoc(),
  2939. OverloadCandidateSet::CSK_Normal);
  2940. OverloadingResult OvResult =
  2941. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  2942. CandidateSet, false, false);
  2943. if (OvResult == OR_Ambiguous)
  2944. Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
  2945. << From->getType() << ToType << From->getSourceRange();
  2946. else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
  2947. if (!RequireCompleteType(From->getLocStart(), ToType,
  2948. diag::err_typecheck_nonviable_condition_incomplete,
  2949. From->getType(), From->getSourceRange()))
  2950. Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
  2951. << From->getType() << From->getSourceRange() << ToType;
  2952. } else
  2953. return false;
  2954. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
  2955. return true;
  2956. }
  2957. /// \brief Compare the user-defined conversion functions or constructors
  2958. /// of two user-defined conversion sequences to determine whether any ordering
  2959. /// is possible.
  2960. static ImplicitConversionSequence::CompareKind
  2961. compareConversionFunctions(Sema &S, FunctionDecl *Function1,
  2962. FunctionDecl *Function2) {
  2963. if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
  2964. return ImplicitConversionSequence::Indistinguishable;
  2965. // Objective-C++:
  2966. // If both conversion functions are implicitly-declared conversions from
  2967. // a lambda closure type to a function pointer and a block pointer,
  2968. // respectively, always prefer the conversion to a function pointer,
  2969. // because the function pointer is more lightweight and is more likely
  2970. // to keep code working.
  2971. CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
  2972. if (!Conv1)
  2973. return ImplicitConversionSequence::Indistinguishable;
  2974. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  2975. if (!Conv2)
  2976. return ImplicitConversionSequence::Indistinguishable;
  2977. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  2978. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  2979. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  2980. if (Block1 != Block2)
  2981. return Block1 ? ImplicitConversionSequence::Worse
  2982. : ImplicitConversionSequence::Better;
  2983. }
  2984. return ImplicitConversionSequence::Indistinguishable;
  2985. }
  2986. static bool hasDeprecatedStringLiteralToCharPtrConversion(
  2987. const ImplicitConversionSequence &ICS) {
  2988. return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
  2989. (ICS.isUserDefined() &&
  2990. ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
  2991. }
  2992. /// CompareImplicitConversionSequences - Compare two implicit
  2993. /// conversion sequences to determine whether one is better than the
  2994. /// other or if they are indistinguishable (C++ 13.3.3.2).
  2995. static ImplicitConversionSequence::CompareKind
  2996. CompareImplicitConversionSequences(Sema &S,
  2997. const ImplicitConversionSequence& ICS1,
  2998. const ImplicitConversionSequence& ICS2)
  2999. {
  3000. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  3001. // conversion sequences (as defined in 13.3.3.1)
  3002. // -- a standard conversion sequence (13.3.3.1.1) is a better
  3003. // conversion sequence than a user-defined conversion sequence or
  3004. // an ellipsis conversion sequence, and
  3005. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  3006. // conversion sequence than an ellipsis conversion sequence
  3007. // (13.3.3.1.3).
  3008. //
  3009. // C++0x [over.best.ics]p10:
  3010. // For the purpose of ranking implicit conversion sequences as
  3011. // described in 13.3.3.2, the ambiguous conversion sequence is
  3012. // treated as a user-defined sequence that is indistinguishable
  3013. // from any other user-defined conversion sequence.
  3014. // String literal to 'char *' conversion has been deprecated in C++03. It has
  3015. // been removed from C++11. We still accept this conversion, if it happens at
  3016. // the best viable function. Otherwise, this conversion is considered worse
  3017. // than ellipsis conversion. Consider this as an extension; this is not in the
  3018. // standard. For example:
  3019. //
  3020. // int &f(...); // #1
  3021. // void f(char*); // #2
  3022. // void g() { int &r = f("foo"); }
  3023. //
  3024. // In C++03, we pick #2 as the best viable function.
  3025. // In C++11, we pick #1 as the best viable function, because ellipsis
  3026. // conversion is better than string-literal to char* conversion (since there
  3027. // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
  3028. // convert arguments, #2 would be the best viable function in C++11.
  3029. // If the best viable function has this conversion, a warning will be issued
  3030. // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
  3031. if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
  3032. hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
  3033. hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
  3034. return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
  3035. ? ImplicitConversionSequence::Worse
  3036. : ImplicitConversionSequence::Better;
  3037. // HLSL Change Starts
  3038. // This ranking happens in HLSL as part of diagnostics; otherwise the specific ranking is used.
  3039. if (S.getLangOpts().HLSL) {
  3040. if (!ICS1.isInitialized() || !ICS2.isInitialized())
  3041. return ImplicitConversionSequence::Indistinguishable;
  3042. }
  3043. // HLSL Change Ends
  3044. if (ICS1.getKindRank() < ICS2.getKindRank())
  3045. return ImplicitConversionSequence::Better;
  3046. if (ICS2.getKindRank() < ICS1.getKindRank())
  3047. return ImplicitConversionSequence::Worse;
  3048. // The following checks require both conversion sequences to be of
  3049. // the same kind.
  3050. if (ICS1.getKind() != ICS2.getKind())
  3051. return ImplicitConversionSequence::Indistinguishable;
  3052. ImplicitConversionSequence::CompareKind Result =
  3053. ImplicitConversionSequence::Indistinguishable;
  3054. // Two implicit conversion sequences of the same form are
  3055. // indistinguishable conversion sequences unless one of the
  3056. // following rules apply: (C++ 13.3.3.2p3):
  3057. // List-initialization sequence L1 is a better conversion sequence than
  3058. // list-initialization sequence L2 if:
  3059. // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
  3060. // if not that,
  3061. // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
  3062. // and N1 is smaller than N2.,
  3063. // even if one of the other rules in this paragraph would otherwise apply.
  3064. if (!ICS1.isBad()) {
  3065. if (ICS1.isStdInitializerListElement() &&
  3066. !ICS2.isStdInitializerListElement())
  3067. return ImplicitConversionSequence::Better;
  3068. if (!ICS1.isStdInitializerListElement() &&
  3069. ICS2.isStdInitializerListElement())
  3070. return ImplicitConversionSequence::Worse;
  3071. }
  3072. if (ICS1.isStandard())
  3073. // Standard conversion sequence S1 is a better conversion sequence than
  3074. // standard conversion sequence S2 if [...]
  3075. Result = CompareStandardConversionSequences(S,
  3076. ICS1.Standard, ICS2.Standard);
  3077. else if (ICS1.isUserDefined()) {
  3078. // User-defined conversion sequence U1 is a better conversion
  3079. // sequence than another user-defined conversion sequence U2 if
  3080. // they contain the same user-defined conversion function or
  3081. // constructor and if the second standard conversion sequence of
  3082. // U1 is better than the second standard conversion sequence of
  3083. // U2 (C++ 13.3.3.2p3).
  3084. if (ICS1.UserDefined.ConversionFunction ==
  3085. ICS2.UserDefined.ConversionFunction)
  3086. Result = CompareStandardConversionSequences(S,
  3087. ICS1.UserDefined.After,
  3088. ICS2.UserDefined.After);
  3089. else
  3090. Result = compareConversionFunctions(S,
  3091. ICS1.UserDefined.ConversionFunction,
  3092. ICS2.UserDefined.ConversionFunction);
  3093. }
  3094. return Result;
  3095. }
  3096. static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
  3097. while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3098. Qualifiers Quals;
  3099. T1 = Context.getUnqualifiedArrayType(T1, Quals);
  3100. T2 = Context.getUnqualifiedArrayType(T2, Quals);
  3101. }
  3102. return Context.hasSameUnqualifiedType(T1, T2);
  3103. }
  3104. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  3105. // determine if one is a proper subset of the other.
  3106. static ImplicitConversionSequence::CompareKind
  3107. compareStandardConversionSubsets(ASTContext &Context,
  3108. const StandardConversionSequence& SCS1,
  3109. const StandardConversionSequence& SCS2) {
  3110. ImplicitConversionSequence::CompareKind Result
  3111. = ImplicitConversionSequence::Indistinguishable;
  3112. // the identity conversion sequence is considered to be a subsequence of
  3113. // any non-identity conversion sequence
  3114. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  3115. return ImplicitConversionSequence::Better;
  3116. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  3117. return ImplicitConversionSequence::Worse;
  3118. if (SCS1.Second != SCS2.Second) {
  3119. if (SCS1.Second == ICK_Identity)
  3120. Result = ImplicitConversionSequence::Better;
  3121. else if (SCS2.Second == ICK_Identity)
  3122. Result = ImplicitConversionSequence::Worse;
  3123. else
  3124. return ImplicitConversionSequence::Indistinguishable;
  3125. } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
  3126. return ImplicitConversionSequence::Indistinguishable;
  3127. if (SCS1.Third == SCS2.Third) {
  3128. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  3129. : ImplicitConversionSequence::Indistinguishable;
  3130. }
  3131. if (SCS1.Third == ICK_Identity)
  3132. return Result == ImplicitConversionSequence::Worse
  3133. ? ImplicitConversionSequence::Indistinguishable
  3134. : ImplicitConversionSequence::Better;
  3135. if (SCS2.Third == ICK_Identity)
  3136. return Result == ImplicitConversionSequence::Better
  3137. ? ImplicitConversionSequence::Indistinguishable
  3138. : ImplicitConversionSequence::Worse;
  3139. return ImplicitConversionSequence::Indistinguishable;
  3140. }
  3141. /// \brief Determine whether one of the given reference bindings is better
  3142. /// than the other based on what kind of bindings they are.
  3143. static bool
  3144. isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3145. const StandardConversionSequence &SCS2) {
  3146. // C++0x [over.ics.rank]p3b4:
  3147. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3148. // implicit object parameter of a non-static member function declared
  3149. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3150. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3151. // lvalue reference to a function lvalue and S2 binds an rvalue
  3152. // reference*.
  3153. //
  3154. // FIXME: Rvalue references. We're going rogue with the above edits,
  3155. // because the semantics in the current C++0x working paper (N3225 at the
  3156. // time of this writing) break the standard definition of std::forward
  3157. // and std::reference_wrapper when dealing with references to functions.
  3158. // Proposed wording changes submitted to CWG for consideration.
  3159. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3160. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3161. return false;
  3162. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3163. SCS2.IsLvalueReference) ||
  3164. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3165. !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
  3166. }
  3167. /// CompareStandardConversionSequences - Compare two standard
  3168. /// conversion sequences to determine whether one is better than the
  3169. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3170. static ImplicitConversionSequence::CompareKind
  3171. CompareStandardConversionSequences(Sema &S,
  3172. const StandardConversionSequence& SCS1,
  3173. const StandardConversionSequence& SCS2)
  3174. {
  3175. // Standard conversion sequence S1 is a better conversion sequence
  3176. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3177. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3178. // sequences in the canonical form defined by 13.3.3.1.1,
  3179. // excluding any Lvalue Transformation; the identity conversion
  3180. // sequence is considered to be a subsequence of any
  3181. // non-identity conversion sequence) or, if not that,
  3182. if (ImplicitConversionSequence::CompareKind CK
  3183. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3184. return CK;
  3185. // -- the rank of S1 is better than the rank of S2 (by the rules
  3186. // defined below), or, if not that,
  3187. ImplicitConversionRank Rank1 = SCS1.getRank();
  3188. ImplicitConversionRank Rank2 = SCS2.getRank();
  3189. if (Rank1 < Rank2)
  3190. return ImplicitConversionSequence::Better;
  3191. else if (Rank2 < Rank1)
  3192. return ImplicitConversionSequence::Worse;
  3193. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3194. // are indistinguishable unless one of the following rules
  3195. // applies:
  3196. // A conversion that is not a conversion of a pointer, or
  3197. // pointer to member, to bool is better than another conversion
  3198. // that is such a conversion.
  3199. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3200. return SCS2.isPointerConversionToBool()
  3201. ? ImplicitConversionSequence::Better
  3202. : ImplicitConversionSequence::Worse;
  3203. // C++ [over.ics.rank]p4b2:
  3204. //
  3205. // If class B is derived directly or indirectly from class A,
  3206. // conversion of B* to A* is better than conversion of B* to
  3207. // void*, and conversion of A* to void* is better than conversion
  3208. // of B* to void*.
  3209. bool SCS1ConvertsToVoid
  3210. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3211. bool SCS2ConvertsToVoid
  3212. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3213. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3214. // Exactly one of the conversion sequences is a conversion to
  3215. // a void pointer; it's the worse conversion.
  3216. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3217. : ImplicitConversionSequence::Worse;
  3218. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3219. // Neither conversion sequence converts to a void pointer; compare
  3220. // their derived-to-base conversions.
  3221. if (ImplicitConversionSequence::CompareKind DerivedCK
  3222. = CompareDerivedToBaseConversions(S, SCS1, SCS2))
  3223. return DerivedCK;
  3224. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3225. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3226. // Both conversion sequences are conversions to void
  3227. // pointers. Compare the source types to determine if there's an
  3228. // inheritance relationship in their sources.
  3229. QualType FromType1 = SCS1.getFromType();
  3230. QualType FromType2 = SCS2.getFromType();
  3231. // Adjust the types we're converting from via the array-to-pointer
  3232. // conversion, if we need to.
  3233. if (SCS1.First == ICK_Array_To_Pointer)
  3234. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3235. if (SCS2.First == ICK_Array_To_Pointer)
  3236. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3237. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3238. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3239. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3240. return ImplicitConversionSequence::Better;
  3241. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3242. return ImplicitConversionSequence::Worse;
  3243. // Objective-C++: If one interface is more specific than the
  3244. // other, it is the better one.
  3245. const ObjCObjectPointerType* FromObjCPtr1
  3246. = FromType1->getAs<ObjCObjectPointerType>();
  3247. const ObjCObjectPointerType* FromObjCPtr2
  3248. = FromType2->getAs<ObjCObjectPointerType>();
  3249. if (FromObjCPtr1 && FromObjCPtr2) {
  3250. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3251. FromObjCPtr2);
  3252. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3253. FromObjCPtr1);
  3254. if (AssignLeft != AssignRight) {
  3255. return AssignLeft? ImplicitConversionSequence::Better
  3256. : ImplicitConversionSequence::Worse;
  3257. }
  3258. }
  3259. }
  3260. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3261. // bullet 3).
  3262. if (ImplicitConversionSequence::CompareKind QualCK
  3263. = CompareQualificationConversions(S, SCS1, SCS2))
  3264. return QualCK;
  3265. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3266. // Check for a better reference binding based on the kind of bindings.
  3267. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3268. return ImplicitConversionSequence::Better;
  3269. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3270. return ImplicitConversionSequence::Worse;
  3271. // C++ [over.ics.rank]p3b4:
  3272. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3273. // which the references refer are the same type except for
  3274. // top-level cv-qualifiers, and the type to which the reference
  3275. // initialized by S2 refers is more cv-qualified than the type
  3276. // to which the reference initialized by S1 refers.
  3277. QualType T1 = SCS1.getToType(2);
  3278. QualType T2 = SCS2.getToType(2);
  3279. T1 = S.Context.getCanonicalType(T1);
  3280. T2 = S.Context.getCanonicalType(T2);
  3281. Qualifiers T1Quals, T2Quals;
  3282. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3283. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3284. if (UnqualT1 == UnqualT2) {
  3285. // Objective-C++ ARC: If the references refer to objects with different
  3286. // lifetimes, prefer bindings that don't change lifetime.
  3287. if (SCS1.ObjCLifetimeConversionBinding !=
  3288. SCS2.ObjCLifetimeConversionBinding) {
  3289. return SCS1.ObjCLifetimeConversionBinding
  3290. ? ImplicitConversionSequence::Worse
  3291. : ImplicitConversionSequence::Better;
  3292. }
  3293. // If the type is an array type, promote the element qualifiers to the
  3294. // type for comparison.
  3295. if (isa<ArrayType>(T1) && T1Quals)
  3296. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3297. if (isa<ArrayType>(T2) && T2Quals)
  3298. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3299. if (T2.isMoreQualifiedThan(T1))
  3300. return ImplicitConversionSequence::Better;
  3301. else if (T1.isMoreQualifiedThan(T2))
  3302. return ImplicitConversionSequence::Worse;
  3303. }
  3304. }
  3305. // In Microsoft mode, prefer an integral conversion to a
  3306. // floating-to-integral conversion if the integral conversion
  3307. // is between types of the same size.
  3308. // For example:
  3309. // void f(float);
  3310. // void f(int);
  3311. // int main {
  3312. // long a;
  3313. // f(a);
  3314. // }
  3315. // Here, MSVC will call f(int) instead of generating a compile error
  3316. // as clang will do in standard mode.
  3317. if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
  3318. SCS2.Second == ICK_Floating_Integral &&
  3319. S.Context.getTypeSize(SCS1.getFromType()) ==
  3320. S.Context.getTypeSize(SCS1.getToType(2)))
  3321. return ImplicitConversionSequence::Better;
  3322. return ImplicitConversionSequence::Indistinguishable;
  3323. }
  3324. /// CompareQualificationConversions - Compares two standard conversion
  3325. /// sequences to determine whether they can be ranked based on their
  3326. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3327. static ImplicitConversionSequence::CompareKind
  3328. CompareQualificationConversions(Sema &S,
  3329. const StandardConversionSequence& SCS1,
  3330. const StandardConversionSequence& SCS2) {
  3331. // C++ 13.3.3.2p3:
  3332. // -- S1 and S2 differ only in their qualification conversion and
  3333. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3334. // cv-qualification signature of type T1 is a proper subset of
  3335. // the cv-qualification signature of type T2, and S1 is not the
  3336. // deprecated string literal array-to-pointer conversion (4.2).
  3337. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3338. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3339. return ImplicitConversionSequence::Indistinguishable;
  3340. // FIXME: the example in the standard doesn't use a qualification
  3341. // conversion (!)
  3342. QualType T1 = SCS1.getToType(2);
  3343. QualType T2 = SCS2.getToType(2);
  3344. T1 = S.Context.getCanonicalType(T1);
  3345. T2 = S.Context.getCanonicalType(T2);
  3346. Qualifiers T1Quals, T2Quals;
  3347. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3348. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3349. // If the types are the same, we won't learn anything by unwrapped
  3350. // them.
  3351. if (UnqualT1 == UnqualT2)
  3352. return ImplicitConversionSequence::Indistinguishable;
  3353. // If the type is an array type, promote the element qualifiers to the type
  3354. // for comparison.
  3355. if (isa<ArrayType>(T1) && T1Quals)
  3356. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3357. if (isa<ArrayType>(T2) && T2Quals)
  3358. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3359. ImplicitConversionSequence::CompareKind Result
  3360. = ImplicitConversionSequence::Indistinguishable;
  3361. // Objective-C++ ARC:
  3362. // Prefer qualification conversions not involving a change in lifetime
  3363. // to qualification conversions that do not change lifetime.
  3364. if (SCS1.QualificationIncludesObjCLifetime !=
  3365. SCS2.QualificationIncludesObjCLifetime) {
  3366. Result = SCS1.QualificationIncludesObjCLifetime
  3367. ? ImplicitConversionSequence::Worse
  3368. : ImplicitConversionSequence::Better;
  3369. }
  3370. while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3371. // Within each iteration of the loop, we check the qualifiers to
  3372. // determine if this still looks like a qualification
  3373. // conversion. Then, if all is well, we unwrap one more level of
  3374. // pointers or pointers-to-members and do it all again
  3375. // until there are no more pointers or pointers-to-members left
  3376. // to unwrap. This essentially mimics what
  3377. // IsQualificationConversion does, but here we're checking for a
  3378. // strict subset of qualifiers.
  3379. if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
  3380. // The qualifiers are the same, so this doesn't tell us anything
  3381. // about how the sequences rank.
  3382. ;
  3383. else if (T2.isMoreQualifiedThan(T1)) {
  3384. // T1 has fewer qualifiers, so it could be the better sequence.
  3385. if (Result == ImplicitConversionSequence::Worse)
  3386. // Neither has qualifiers that are a subset of the other's
  3387. // qualifiers.
  3388. return ImplicitConversionSequence::Indistinguishable;
  3389. Result = ImplicitConversionSequence::Better;
  3390. } else if (T1.isMoreQualifiedThan(T2)) {
  3391. // T2 has fewer qualifiers, so it could be the better sequence.
  3392. if (Result == ImplicitConversionSequence::Better)
  3393. // Neither has qualifiers that are a subset of the other's
  3394. // qualifiers.
  3395. return ImplicitConversionSequence::Indistinguishable;
  3396. Result = ImplicitConversionSequence::Worse;
  3397. } else {
  3398. // Qualifiers are disjoint.
  3399. return ImplicitConversionSequence::Indistinguishable;
  3400. }
  3401. // If the types after this point are equivalent, we're done.
  3402. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3403. break;
  3404. }
  3405. // Check that the winning standard conversion sequence isn't using
  3406. // the deprecated string literal array to pointer conversion.
  3407. switch (Result) {
  3408. case ImplicitConversionSequence::Better:
  3409. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3410. Result = ImplicitConversionSequence::Indistinguishable;
  3411. break;
  3412. case ImplicitConversionSequence::Indistinguishable:
  3413. break;
  3414. case ImplicitConversionSequence::Worse:
  3415. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3416. Result = ImplicitConversionSequence::Indistinguishable;
  3417. break;
  3418. }
  3419. return Result;
  3420. }
  3421. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3422. /// sequences to determine whether they can be ranked based on their
  3423. /// various kinds of derived-to-base conversions (C++
  3424. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3425. /// conversions between Objective-C interface types.
  3426. static ImplicitConversionSequence::CompareKind
  3427. CompareDerivedToBaseConversions(Sema &S,
  3428. const StandardConversionSequence& SCS1,
  3429. const StandardConversionSequence& SCS2) {
  3430. QualType FromType1 = SCS1.getFromType();
  3431. QualType ToType1 = SCS1.getToType(1);
  3432. QualType FromType2 = SCS2.getFromType();
  3433. QualType ToType2 = SCS2.getToType(1);
  3434. // Adjust the types we're converting from via the array-to-pointer
  3435. // conversion, if we need to.
  3436. if (SCS1.First == ICK_Array_To_Pointer)
  3437. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3438. if (SCS2.First == ICK_Array_To_Pointer)
  3439. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3440. // Canonicalize all of the types.
  3441. FromType1 = S.Context.getCanonicalType(FromType1);
  3442. ToType1 = S.Context.getCanonicalType(ToType1);
  3443. FromType2 = S.Context.getCanonicalType(FromType2);
  3444. ToType2 = S.Context.getCanonicalType(ToType2);
  3445. // C++ [over.ics.rank]p4b3:
  3446. //
  3447. // If class B is derived directly or indirectly from class A and
  3448. // class C is derived directly or indirectly from B,
  3449. //
  3450. // Compare based on pointer conversions.
  3451. if (SCS1.Second == ICK_Pointer_Conversion &&
  3452. SCS2.Second == ICK_Pointer_Conversion &&
  3453. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3454. FromType1->isPointerType() && FromType2->isPointerType() &&
  3455. ToType1->isPointerType() && ToType2->isPointerType()) {
  3456. QualType FromPointee1
  3457. = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3458. QualType ToPointee1
  3459. = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3460. QualType FromPointee2
  3461. = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3462. QualType ToPointee2
  3463. = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3464. // -- conversion of C* to B* is better than conversion of C* to A*,
  3465. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3466. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3467. return ImplicitConversionSequence::Better;
  3468. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3469. return ImplicitConversionSequence::Worse;
  3470. }
  3471. // -- conversion of B* to A* is better than conversion of C* to A*,
  3472. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3473. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3474. return ImplicitConversionSequence::Better;
  3475. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3476. return ImplicitConversionSequence::Worse;
  3477. }
  3478. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3479. SCS2.Second == ICK_Pointer_Conversion) {
  3480. const ObjCObjectPointerType *FromPtr1
  3481. = FromType1->getAs<ObjCObjectPointerType>();
  3482. const ObjCObjectPointerType *FromPtr2
  3483. = FromType2->getAs<ObjCObjectPointerType>();
  3484. const ObjCObjectPointerType *ToPtr1
  3485. = ToType1->getAs<ObjCObjectPointerType>();
  3486. const ObjCObjectPointerType *ToPtr2
  3487. = ToType2->getAs<ObjCObjectPointerType>();
  3488. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3489. // Apply the same conversion ranking rules for Objective-C pointer types
  3490. // that we do for C++ pointers to class types. However, we employ the
  3491. // Objective-C pseudo-subtyping relationship used for assignment of
  3492. // Objective-C pointer types.
  3493. bool FromAssignLeft
  3494. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3495. bool FromAssignRight
  3496. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3497. bool ToAssignLeft
  3498. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3499. bool ToAssignRight
  3500. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3501. // A conversion to an a non-id object pointer type or qualified 'id'
  3502. // type is better than a conversion to 'id'.
  3503. if (ToPtr1->isObjCIdType() &&
  3504. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3505. return ImplicitConversionSequence::Worse;
  3506. if (ToPtr2->isObjCIdType() &&
  3507. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3508. return ImplicitConversionSequence::Better;
  3509. // A conversion to a non-id object pointer type is better than a
  3510. // conversion to a qualified 'id' type
  3511. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3512. return ImplicitConversionSequence::Worse;
  3513. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3514. return ImplicitConversionSequence::Better;
  3515. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3516. // type is better than a conversion to 'Class'.
  3517. if (ToPtr1->isObjCClassType() &&
  3518. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3519. return ImplicitConversionSequence::Worse;
  3520. if (ToPtr2->isObjCClassType() &&
  3521. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3522. return ImplicitConversionSequence::Better;
  3523. // A conversion to a non-Class object pointer type is better than a
  3524. // conversion to a qualified 'Class' type.
  3525. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3526. return ImplicitConversionSequence::Worse;
  3527. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3528. return ImplicitConversionSequence::Better;
  3529. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3530. if (S.Context.hasSameType(FromType1, FromType2) &&
  3531. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3532. (ToAssignLeft != ToAssignRight))
  3533. return ToAssignLeft? ImplicitConversionSequence::Worse
  3534. : ImplicitConversionSequence::Better;
  3535. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3536. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3537. (FromAssignLeft != FromAssignRight))
  3538. return FromAssignLeft? ImplicitConversionSequence::Better
  3539. : ImplicitConversionSequence::Worse;
  3540. }
  3541. }
  3542. // Ranking of member-pointer types.
  3543. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3544. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3545. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3546. const MemberPointerType * FromMemPointer1 =
  3547. FromType1->getAs<MemberPointerType>();
  3548. const MemberPointerType * ToMemPointer1 =
  3549. ToType1->getAs<MemberPointerType>();
  3550. const MemberPointerType * FromMemPointer2 =
  3551. FromType2->getAs<MemberPointerType>();
  3552. const MemberPointerType * ToMemPointer2 =
  3553. ToType2->getAs<MemberPointerType>();
  3554. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3555. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3556. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3557. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3558. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3559. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3560. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3561. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3562. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3563. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3564. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3565. return ImplicitConversionSequence::Worse;
  3566. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3567. return ImplicitConversionSequence::Better;
  3568. }
  3569. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3570. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3571. if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3572. return ImplicitConversionSequence::Better;
  3573. else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3574. return ImplicitConversionSequence::Worse;
  3575. }
  3576. }
  3577. if (SCS1.Second == ICK_Derived_To_Base) {
  3578. // -- conversion of C to B is better than conversion of C to A,
  3579. // -- binding of an expression of type C to a reference of type
  3580. // B& is better than binding an expression of type C to a
  3581. // reference of type A&,
  3582. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3583. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3584. if (S.IsDerivedFrom(ToType1, ToType2))
  3585. return ImplicitConversionSequence::Better;
  3586. else if (S.IsDerivedFrom(ToType2, ToType1))
  3587. return ImplicitConversionSequence::Worse;
  3588. }
  3589. // -- conversion of B to A is better than conversion of C to A.
  3590. // -- binding of an expression of type B to a reference of type
  3591. // A& is better than binding an expression of type C to a
  3592. // reference of type A&,
  3593. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3594. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3595. if (S.IsDerivedFrom(FromType2, FromType1))
  3596. return ImplicitConversionSequence::Better;
  3597. else if (S.IsDerivedFrom(FromType1, FromType2))
  3598. return ImplicitConversionSequence::Worse;
  3599. }
  3600. }
  3601. return ImplicitConversionSequence::Indistinguishable;
  3602. }
  3603. /// \brief Determine whether the given type is valid, e.g., it is not an invalid
  3604. /// C++ class.
  3605. static bool isTypeValid(QualType T) {
  3606. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3607. return !Record->isInvalidDecl();
  3608. return true;
  3609. }
  3610. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3611. /// determine whether they are reference-related,
  3612. /// reference-compatible, reference-compatible with added
  3613. /// qualification, or incompatible, for use in C++ initialization by
  3614. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3615. /// type, and the first type (T1) is the pointee type of the reference
  3616. /// type being initialized.
  3617. Sema::ReferenceCompareResult
  3618. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3619. QualType OrigT1, QualType OrigT2,
  3620. bool &DerivedToBase,
  3621. bool &ObjCConversion,
  3622. bool &ObjCLifetimeConversion) {
  3623. assert(!OrigT1->isReferenceType() &&
  3624. "T1 must be the pointee type of the reference type");
  3625. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3626. QualType T1 = Context.getCanonicalType(OrigT1);
  3627. QualType T2 = Context.getCanonicalType(OrigT2);
  3628. Qualifiers T1Quals, T2Quals;
  3629. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3630. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3631. // C++ [dcl.init.ref]p4:
  3632. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3633. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3634. // T1 is a base class of T2.
  3635. DerivedToBase = false;
  3636. ObjCConversion = false;
  3637. ObjCLifetimeConversion = false;
  3638. if (UnqualT1 == UnqualT2) {
  3639. // Nothing to do.
  3640. } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
  3641. isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
  3642. IsDerivedFrom(UnqualT2, UnqualT1))
  3643. DerivedToBase = true;
  3644. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3645. UnqualT2->isObjCObjectOrInterfaceType() &&
  3646. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3647. ObjCConversion = true;
  3648. else
  3649. return Ref_Incompatible;
  3650. // At this point, we know that T1 and T2 are reference-related (at
  3651. // least).
  3652. // If the type is an array type, promote the element qualifiers to the type
  3653. // for comparison.
  3654. if (isa<ArrayType>(T1) && T1Quals)
  3655. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3656. if (isa<ArrayType>(T2) && T2Quals)
  3657. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3658. // C++ [dcl.init.ref]p4:
  3659. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3660. // reference-related to T2 and cv1 is the same cv-qualification
  3661. // as, or greater cv-qualification than, cv2. For purposes of
  3662. // overload resolution, cases for which cv1 is greater
  3663. // cv-qualification than cv2 are identified as
  3664. // reference-compatible with added qualification (see 13.3.3.2).
  3665. //
  3666. // Note that we also require equivalence of Objective-C GC and address-space
  3667. // qualifiers when performing these computations, so that e.g., an int in
  3668. // address space 1 is not reference-compatible with an int in address
  3669. // space 2.
  3670. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3671. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3672. if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
  3673. ObjCLifetimeConversion = true;
  3674. T1Quals.removeObjCLifetime();
  3675. T2Quals.removeObjCLifetime();
  3676. }
  3677. if (T1Quals == T2Quals)
  3678. return Ref_Compatible;
  3679. else if (T1Quals.compatiblyIncludes(T2Quals))
  3680. return Ref_Compatible_With_Added_Qualification;
  3681. else
  3682. return Ref_Related;
  3683. }
  3684. /// \brief Look for a user-defined conversion to an value reference-compatible
  3685. /// with DeclType. Return true if something definite is found.
  3686. static bool
  3687. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  3688. QualType DeclType, SourceLocation DeclLoc,
  3689. Expr *Init, QualType T2, bool AllowRvalues,
  3690. bool AllowExplicit) {
  3691. assert(T2->isRecordType() && "Can only find conversions of record types.");
  3692. CXXRecordDecl *T2RecordDecl
  3693. = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
  3694. OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
  3695. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3696. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3697. NamedDecl *D = *I;
  3698. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3699. if (isa<UsingShadowDecl>(D))
  3700. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3701. FunctionTemplateDecl *ConvTemplate
  3702. = dyn_cast<FunctionTemplateDecl>(D);
  3703. CXXConversionDecl *Conv;
  3704. if (ConvTemplate)
  3705. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3706. else
  3707. Conv = cast<CXXConversionDecl>(D);
  3708. // If this is an explicit conversion, and we're not allowed to consider
  3709. // explicit conversions, skip it.
  3710. if (!AllowExplicit && Conv->isExplicit())
  3711. continue;
  3712. if (AllowRvalues) {
  3713. bool DerivedToBase = false;
  3714. bool ObjCConversion = false;
  3715. bool ObjCLifetimeConversion = false;
  3716. // If we are initializing an rvalue reference, don't permit conversion
  3717. // functions that return lvalues.
  3718. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  3719. const ReferenceType *RefType
  3720. = Conv->getConversionType()->getAs<LValueReferenceType>();
  3721. if (RefType && !RefType->getPointeeType()->isFunctionType())
  3722. continue;
  3723. }
  3724. if (!ConvTemplate &&
  3725. S.CompareReferenceRelationship(
  3726. DeclLoc,
  3727. Conv->getConversionType().getNonReferenceType()
  3728. .getUnqualifiedType(),
  3729. DeclType.getNonReferenceType().getUnqualifiedType(),
  3730. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  3731. Sema::Ref_Incompatible)
  3732. continue;
  3733. } else {
  3734. // If the conversion function doesn't return a reference type,
  3735. // it can't be considered for this conversion. An rvalue reference
  3736. // is only acceptable if its referencee is a function type.
  3737. const ReferenceType *RefType =
  3738. Conv->getConversionType()->getAs<ReferenceType>();
  3739. if (!RefType ||
  3740. (!RefType->isLValueReferenceType() &&
  3741. !RefType->getPointeeType()->isFunctionType()))
  3742. continue;
  3743. }
  3744. if (ConvTemplate)
  3745. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
  3746. Init, DeclType, CandidateSet,
  3747. /*AllowObjCConversionOnExplicit=*/false);
  3748. else
  3749. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
  3750. DeclType, CandidateSet,
  3751. /*AllowObjCConversionOnExplicit=*/false);
  3752. }
  3753. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3754. OverloadCandidateSet::iterator Best;
  3755. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  3756. case OR_Success:
  3757. // C++ [over.ics.ref]p1:
  3758. //
  3759. // [...] If the parameter binds directly to the result of
  3760. // applying a conversion function to the argument
  3761. // expression, the implicit conversion sequence is a
  3762. // user-defined conversion sequence (13.3.3.1.2), with the
  3763. // second standard conversion sequence either an identity
  3764. // conversion or, if the conversion function returns an
  3765. // entity of a type that is a derived class of the parameter
  3766. // type, a derived-to-base Conversion.
  3767. if (!Best->FinalConversion.DirectBinding)
  3768. return false;
  3769. ICS.setUserDefined();
  3770. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  3771. ICS.UserDefined.After = Best->FinalConversion;
  3772. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  3773. ICS.UserDefined.ConversionFunction = Best->Function;
  3774. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  3775. ICS.UserDefined.EllipsisConversion = false;
  3776. assert(ICS.UserDefined.After.ReferenceBinding &&
  3777. ICS.UserDefined.After.DirectBinding &&
  3778. "Expected a direct reference binding!");
  3779. return true;
  3780. case OR_Ambiguous:
  3781. ICS.setAmbiguous();
  3782. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  3783. Cand != CandidateSet.end(); ++Cand)
  3784. if (Cand->Viable)
  3785. ICS.Ambiguous.addConversion(Cand->Function);
  3786. return true;
  3787. case OR_No_Viable_Function:
  3788. case OR_Deleted:
  3789. // There was no suitable conversion, or we found a deleted
  3790. // conversion; continue with other checks.
  3791. return false;
  3792. }
  3793. llvm_unreachable("Invalid OverloadResult!");
  3794. }
  3795. /// \brief Compute an implicit conversion sequence for reference
  3796. /// initialization.
  3797. static ImplicitConversionSequence
  3798. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  3799. SourceLocation DeclLoc,
  3800. bool SuppressUserConversions,
  3801. bool AllowExplicit) {
  3802. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  3803. // Most paths end in a failed conversion.
  3804. ImplicitConversionSequence ICS;
  3805. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3806. QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
  3807. QualType T2 = Init->getType();
  3808. // If the initializer is the address of an overloaded function, try
  3809. // to resolve the overloaded function. If all goes well, T2 is the
  3810. // type of the resulting function.
  3811. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  3812. DeclAccessPair Found;
  3813. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  3814. false, Found))
  3815. T2 = Fn->getType();
  3816. }
  3817. // Compute some basic properties of the types and the initializer.
  3818. bool isRValRef = DeclType->isRValueReferenceType();
  3819. bool DerivedToBase = false;
  3820. bool ObjCConversion = false;
  3821. bool ObjCLifetimeConversion = false;
  3822. Expr::Classification InitCategory = Init->Classify(S.Context);
  3823. Sema::ReferenceCompareResult RefRelationship
  3824. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  3825. ObjCConversion, ObjCLifetimeConversion);
  3826. // C++0x [dcl.init.ref]p5:
  3827. // A reference to type "cv1 T1" is initialized by an expression
  3828. // of type "cv2 T2" as follows:
  3829. // -- If reference is an lvalue reference and the initializer expression
  3830. if (!isRValRef) {
  3831. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  3832. // reference-compatible with "cv2 T2," or
  3833. //
  3834. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  3835. if (InitCategory.isLValue() &&
  3836. RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
  3837. // C++ [over.ics.ref]p1:
  3838. // When a parameter of reference type binds directly (8.5.3)
  3839. // to an argument expression, the implicit conversion sequence
  3840. // is the identity conversion, unless the argument expression
  3841. // has a type that is a derived class of the parameter type,
  3842. // in which case the implicit conversion sequence is a
  3843. // derived-to-base Conversion (13.3.3.1).
  3844. ICS.setStandard();
  3845. ICS.Standard.First = ICK_Identity;
  3846. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3847. : ObjCConversion? ICK_Compatible_Conversion
  3848. : ICK_Identity;
  3849. ICS.Standard.Third = ICK_Identity;
  3850. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3851. ICS.Standard.setToType(0, T2);
  3852. ICS.Standard.setToType(1, T1);
  3853. ICS.Standard.setToType(2, T1);
  3854. ICS.Standard.ReferenceBinding = true;
  3855. ICS.Standard.DirectBinding = true;
  3856. ICS.Standard.IsLvalueReference = !isRValRef;
  3857. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3858. ICS.Standard.BindsToRvalue = false;
  3859. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3860. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3861. ICS.Standard.CopyConstructor = nullptr;
  3862. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3863. // Nothing more to do: the inaccessibility/ambiguity check for
  3864. // derived-to-base conversions is suppressed when we're
  3865. // computing the implicit conversion sequence (C++
  3866. // [over.best.ics]p2).
  3867. return ICS;
  3868. }
  3869. // -- has a class type (i.e., T2 is a class type), where T1 is
  3870. // not reference-related to T2, and can be implicitly
  3871. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  3872. // is reference-compatible with "cv3 T3" 92) (this
  3873. // conversion is selected by enumerating the applicable
  3874. // conversion functions (13.3.1.6) and choosing the best
  3875. // one through overload resolution (13.3)),
  3876. if (!SuppressUserConversions && T2->isRecordType() &&
  3877. !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3878. RefRelationship == Sema::Ref_Incompatible) {
  3879. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3880. Init, T2, /*AllowRvalues=*/false,
  3881. AllowExplicit))
  3882. return ICS;
  3883. }
  3884. }
  3885. // -- Otherwise, the reference shall be an lvalue reference to a
  3886. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3887. // shall be an rvalue reference.
  3888. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  3889. return ICS;
  3890. // -- If the initializer expression
  3891. //
  3892. // -- is an xvalue, class prvalue, array prvalue or function
  3893. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  3894. if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
  3895. (InitCategory.isXValue() ||
  3896. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  3897. (InitCategory.isLValue() && T2->isFunctionType()))) {
  3898. ICS.setStandard();
  3899. ICS.Standard.First = ICK_Identity;
  3900. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3901. : ObjCConversion? ICK_Compatible_Conversion
  3902. : ICK_Identity;
  3903. ICS.Standard.Third = ICK_Identity;
  3904. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3905. ICS.Standard.setToType(0, T2);
  3906. ICS.Standard.setToType(1, T1);
  3907. ICS.Standard.setToType(2, T1);
  3908. ICS.Standard.ReferenceBinding = true;
  3909. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  3910. // binding unless we're binding to a class prvalue.
  3911. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  3912. // allow the use of rvalue references in C++98/03 for the benefit of
  3913. // standard library implementors; therefore, we need the xvalue check here.
  3914. ICS.Standard.DirectBinding =
  3915. S.getLangOpts().CPlusPlus11 ||
  3916. !(InitCategory.isPRValue() || T2->isRecordType());
  3917. ICS.Standard.IsLvalueReference = !isRValRef;
  3918. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3919. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  3920. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3921. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3922. ICS.Standard.CopyConstructor = nullptr;
  3923. ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
  3924. return ICS;
  3925. }
  3926. // -- has a class type (i.e., T2 is a class type), where T1 is not
  3927. // reference-related to T2, and can be implicitly converted to
  3928. // an xvalue, class prvalue, or function lvalue of type
  3929. // "cv3 T3", where "cv1 T1" is reference-compatible with
  3930. // "cv3 T3",
  3931. //
  3932. // then the reference is bound to the value of the initializer
  3933. // expression in the first case and to the result of the conversion
  3934. // in the second case (or, in either case, to an appropriate base
  3935. // class subobject).
  3936. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3937. T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3938. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3939. Init, T2, /*AllowRvalues=*/true,
  3940. AllowExplicit)) {
  3941. // In the second case, if the reference is an rvalue reference
  3942. // and the second standard conversion sequence of the
  3943. // user-defined conversion sequence includes an lvalue-to-rvalue
  3944. // conversion, the program is ill-formed.
  3945. if (ICS.isUserDefined() && isRValRef &&
  3946. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  3947. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3948. return ICS;
  3949. }
  3950. // A temporary of function type cannot be created; don't even try.
  3951. if (T1->isFunctionType())
  3952. return ICS;
  3953. // -- Otherwise, a temporary of type "cv1 T1" is created and
  3954. // initialized from the initializer expression using the
  3955. // rules for a non-reference copy initialization (8.5). The
  3956. // reference is then bound to the temporary. If T1 is
  3957. // reference-related to T2, cv1 must be the same
  3958. // cv-qualification as, or greater cv-qualification than,
  3959. // cv2; otherwise, the program is ill-formed.
  3960. if (RefRelationship == Sema::Ref_Related) {
  3961. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  3962. // we would be reference-compatible or reference-compatible with
  3963. // added qualification. But that wasn't the case, so the reference
  3964. // initialization fails.
  3965. //
  3966. // Note that we only want to check address spaces and cvr-qualifiers here.
  3967. // ObjC GC and lifetime qualifiers aren't important.
  3968. Qualifiers T1Quals = T1.getQualifiers();
  3969. Qualifiers T2Quals = T2.getQualifiers();
  3970. T1Quals.removeObjCGCAttr();
  3971. T1Quals.removeObjCLifetime();
  3972. T2Quals.removeObjCGCAttr();
  3973. T2Quals.removeObjCLifetime();
  3974. if (!T1Quals.compatiblyIncludes(T2Quals))
  3975. return ICS;
  3976. }
  3977. // If at least one of the types is a class type, the types are not
  3978. // related, and we aren't allowed any user conversions, the
  3979. // reference binding fails. This case is important for breaking
  3980. // recursion, since TryImplicitConversion below will attempt to
  3981. // create a temporary through the use of a copy constructor.
  3982. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3983. (T1->isRecordType() || T2->isRecordType()))
  3984. return ICS;
  3985. // If T1 is reference-related to T2 and the reference is an rvalue
  3986. // reference, the initializer expression shall not be an lvalue.
  3987. if (RefRelationship >= Sema::Ref_Related &&
  3988. isRValRef && Init->Classify(S.Context).isLValue())
  3989. return ICS;
  3990. // C++ [over.ics.ref]p2:
  3991. // When a parameter of reference type is not bound directly to
  3992. // an argument expression, the conversion sequence is the one
  3993. // required to convert the argument expression to the
  3994. // underlying type of the reference according to
  3995. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  3996. // to copy-initializing a temporary of the underlying type with
  3997. // the argument expression. Any difference in top-level
  3998. // cv-qualification is subsumed by the initialization itself
  3999. // and does not constitute a conversion.
  4000. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  4001. /*AllowExplicit=*/false,
  4002. /*InOverloadResolution=*/false,
  4003. /*CStyle=*/false,
  4004. /*AllowObjCWritebackConversion=*/false,
  4005. /*AllowObjCConversionOnExplicit=*/false);
  4006. // Of course, that's still a reference binding.
  4007. if (ICS.isStandard()) {
  4008. ICS.Standard.ReferenceBinding = true;
  4009. ICS.Standard.IsLvalueReference = !isRValRef;
  4010. ICS.Standard.BindsToFunctionLvalue = false;
  4011. ICS.Standard.BindsToRvalue = true;
  4012. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4013. ICS.Standard.ObjCLifetimeConversionBinding = false;
  4014. } else if (ICS.isUserDefined()) {
  4015. const ReferenceType *LValRefType =
  4016. ICS.UserDefined.ConversionFunction->getReturnType()
  4017. ->getAs<LValueReferenceType>();
  4018. // C++ [over.ics.ref]p3:
  4019. // Except for an implicit object parameter, for which see 13.3.1, a
  4020. // standard conversion sequence cannot be formed if it requires [...]
  4021. // binding an rvalue reference to an lvalue other than a function
  4022. // lvalue.
  4023. // Note that the function case is not possible here.
  4024. if (DeclType->isRValueReferenceType() && LValRefType) {
  4025. // FIXME: This is the wrong BadConversionSequence. The problem is binding
  4026. // an rvalue reference to a (non-function) lvalue, not binding an lvalue
  4027. // reference to an rvalue!
  4028. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
  4029. return ICS;
  4030. }
  4031. ICS.UserDefined.Before.setAsIdentityConversion();
  4032. ICS.UserDefined.After.ReferenceBinding = true;
  4033. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  4034. ICS.UserDefined.After.BindsToFunctionLvalue = false;
  4035. ICS.UserDefined.After.BindsToRvalue = !LValRefType;
  4036. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4037. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  4038. }
  4039. return ICS;
  4040. }
  4041. static ImplicitConversionSequence
  4042. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4043. bool SuppressUserConversions,
  4044. bool InOverloadResolution,
  4045. bool AllowObjCWritebackConversion,
  4046. bool AllowExplicit = false);
  4047. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  4048. /// initializer list From.
  4049. static ImplicitConversionSequence
  4050. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  4051. bool SuppressUserConversions,
  4052. bool InOverloadResolution,
  4053. bool AllowObjCWritebackConversion) {
  4054. // C++11 [over.ics.list]p1:
  4055. // When an argument is an initializer list, it is not an expression and
  4056. // special rules apply for converting it to a parameter type.
  4057. ImplicitConversionSequence Result;
  4058. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  4059. // We need a complete type for what follows. Incomplete types can never be
  4060. // initialized from init lists.
  4061. if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
  4062. return Result;
  4063. // Per DR1467:
  4064. // If the parameter type is a class X and the initializer list has a single
  4065. // element of type cv U, where U is X or a class derived from X, the
  4066. // implicit conversion sequence is the one required to convert the element
  4067. // to the parameter type.
  4068. //
  4069. // Otherwise, if the parameter type is a character array [... ]
  4070. // and the initializer list has a single element that is an
  4071. // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
  4072. // implicit conversion sequence is the identity conversion.
  4073. if (From->getNumInits() == 1) {
  4074. if (ToType->isRecordType()) {
  4075. QualType InitType = From->getInit(0)->getType();
  4076. if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
  4077. S.IsDerivedFrom(InitType, ToType))
  4078. return TryCopyInitialization(S, From->getInit(0), ToType,
  4079. SuppressUserConversions,
  4080. InOverloadResolution,
  4081. AllowObjCWritebackConversion);
  4082. }
  4083. // FIXME: Check the other conditions here: array of character type,
  4084. // initializer is a string literal.
  4085. if (ToType->isArrayType()) {
  4086. InitializedEntity Entity =
  4087. InitializedEntity::InitializeParameter(S.Context, ToType,
  4088. /*Consumed=*/false);
  4089. if (S.CanPerformCopyInitialization(Entity, From)) {
  4090. Result.setStandard();
  4091. Result.Standard.setAsIdentityConversion();
  4092. Result.Standard.setFromType(ToType);
  4093. Result.Standard.setAllToTypes(ToType);
  4094. return Result;
  4095. }
  4096. }
  4097. }
  4098. // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
  4099. // C++11 [over.ics.list]p2:
  4100. // If the parameter type is std::initializer_list<X> or "array of X" and
  4101. // all the elements can be implicitly converted to X, the implicit
  4102. // conversion sequence is the worst conversion necessary to convert an
  4103. // element of the list to X.
  4104. //
  4105. // C++14 [over.ics.list]p3:
  4106. // Otherwise, if the parameter type is "array of N X", if the initializer
  4107. // list has exactly N elements or if it has fewer than N elements and X is
  4108. // default-constructible, and if all the elements of the initializer list
  4109. // can be implicitly converted to X, the implicit conversion sequence is
  4110. // the worst conversion necessary to convert an element of the list to X.
  4111. //
  4112. // FIXME: We're missing a lot of these checks.
  4113. bool toStdInitializerList = false;
  4114. QualType X;
  4115. if (ToType->isArrayType())
  4116. X = S.Context.getAsArrayType(ToType)->getElementType();
  4117. else
  4118. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  4119. if (!X.isNull()) {
  4120. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  4121. Expr *Init = From->getInit(i);
  4122. ImplicitConversionSequence ICS =
  4123. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  4124. InOverloadResolution,
  4125. AllowObjCWritebackConversion);
  4126. // If a single element isn't convertible, fail.
  4127. if (ICS.isBad()) {
  4128. Result = ICS;
  4129. break;
  4130. }
  4131. // Otherwise, look for the worst conversion.
  4132. if (Result.isBad() ||
  4133. CompareImplicitConversionSequences(S, ICS, Result) ==
  4134. ImplicitConversionSequence::Worse)
  4135. Result = ICS;
  4136. }
  4137. // For an empty list, we won't have computed any conversion sequence.
  4138. // Introduce the identity conversion sequence.
  4139. if (From->getNumInits() == 0) {
  4140. Result.setStandard();
  4141. Result.Standard.setAsIdentityConversion();
  4142. Result.Standard.setFromType(ToType);
  4143. Result.Standard.setAllToTypes(ToType);
  4144. }
  4145. Result.setStdInitializerListElement(toStdInitializerList);
  4146. return Result;
  4147. }
  4148. // C++14 [over.ics.list]p4:
  4149. // C++11 [over.ics.list]p3:
  4150. // Otherwise, if the parameter is a non-aggregate class X and overload
  4151. // resolution chooses a single best constructor [...] the implicit
  4152. // conversion sequence is a user-defined conversion sequence. If multiple
  4153. // constructors are viable but none is better than the others, the
  4154. // implicit conversion sequence is a user-defined conversion sequence.
  4155. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  4156. // This function can deal with initializer lists.
  4157. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  4158. /*AllowExplicit=*/false,
  4159. InOverloadResolution, /*CStyle=*/false,
  4160. AllowObjCWritebackConversion,
  4161. /*AllowObjCConversionOnExplicit=*/false);
  4162. }
  4163. // C++14 [over.ics.list]p5:
  4164. // C++11 [over.ics.list]p4:
  4165. // Otherwise, if the parameter has an aggregate type which can be
  4166. // initialized from the initializer list [...] the implicit conversion
  4167. // sequence is a user-defined conversion sequence.
  4168. if (ToType->isAggregateType()) {
  4169. // Type is an aggregate, argument is an init list. At this point it comes
  4170. // down to checking whether the initialization works.
  4171. // FIXME: Find out whether this parameter is consumed or not.
  4172. InitializedEntity Entity =
  4173. InitializedEntity::InitializeParameter(S.Context, ToType,
  4174. /*Consumed=*/false);
  4175. if (S.CanPerformCopyInitialization(Entity, From)) {
  4176. Result.setUserDefined();
  4177. Result.UserDefined.Before.setAsIdentityConversion();
  4178. // Initializer lists don't have a type.
  4179. Result.UserDefined.Before.setFromType(QualType());
  4180. Result.UserDefined.Before.setAllToTypes(QualType());
  4181. Result.UserDefined.After.setAsIdentityConversion();
  4182. Result.UserDefined.After.setFromType(ToType);
  4183. Result.UserDefined.After.setAllToTypes(ToType);
  4184. Result.UserDefined.ConversionFunction = nullptr;
  4185. }
  4186. return Result;
  4187. }
  4188. // C++14 [over.ics.list]p6:
  4189. // C++11 [over.ics.list]p5:
  4190. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  4191. if (ToType->isReferenceType()) {
  4192. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  4193. // mention initializer lists in any way. So we go by what list-
  4194. // initialization would do and try to extrapolate from that.
  4195. QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
  4196. // If the initializer list has a single element that is reference-related
  4197. // to the parameter type, we initialize the reference from that.
  4198. if (From->getNumInits() == 1) {
  4199. Expr *Init = From->getInit(0);
  4200. QualType T2 = Init->getType();
  4201. // If the initializer is the address of an overloaded function, try
  4202. // to resolve the overloaded function. If all goes well, T2 is the
  4203. // type of the resulting function.
  4204. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4205. DeclAccessPair Found;
  4206. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4207. Init, ToType, false, Found))
  4208. T2 = Fn->getType();
  4209. }
  4210. // Compute some basic properties of the types and the initializer.
  4211. bool dummy1 = false;
  4212. bool dummy2 = false;
  4213. bool dummy3 = false;
  4214. Sema::ReferenceCompareResult RefRelationship
  4215. = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
  4216. dummy2, dummy3);
  4217. if (RefRelationship >= Sema::Ref_Related) {
  4218. return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
  4219. SuppressUserConversions,
  4220. /*AllowExplicit=*/false);
  4221. }
  4222. }
  4223. // Otherwise, we bind the reference to a temporary created from the
  4224. // initializer list.
  4225. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4226. InOverloadResolution,
  4227. AllowObjCWritebackConversion);
  4228. if (Result.isFailure())
  4229. return Result;
  4230. assert(!Result.isEllipsis() &&
  4231. "Sub-initialization cannot result in ellipsis conversion.");
  4232. // Can we even bind to a temporary?
  4233. if (ToType->isRValueReferenceType() ||
  4234. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4235. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4236. Result.UserDefined.After;
  4237. SCS.ReferenceBinding = true;
  4238. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4239. SCS.BindsToRvalue = true;
  4240. SCS.BindsToFunctionLvalue = false;
  4241. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4242. SCS.ObjCLifetimeConversionBinding = false;
  4243. } else
  4244. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4245. From, ToType);
  4246. return Result;
  4247. }
  4248. // C++14 [over.ics.list]p7:
  4249. // C++11 [over.ics.list]p6:
  4250. // Otherwise, if the parameter type is not a class:
  4251. if (!ToType->isRecordType()) {
  4252. // - if the initializer list has one element that is not itself an
  4253. // initializer list, the implicit conversion sequence is the one
  4254. // required to convert the element to the parameter type.
  4255. unsigned NumInits = From->getNumInits();
  4256. if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
  4257. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4258. SuppressUserConversions,
  4259. InOverloadResolution,
  4260. AllowObjCWritebackConversion);
  4261. // - if the initializer list has no elements, the implicit conversion
  4262. // sequence is the identity conversion.
  4263. else if (NumInits == 0) {
  4264. Result.setStandard();
  4265. Result.Standard.setAsIdentityConversion();
  4266. Result.Standard.setFromType(ToType);
  4267. Result.Standard.setAllToTypes(ToType);
  4268. }
  4269. return Result;
  4270. }
  4271. // C++14 [over.ics.list]p8:
  4272. // C++11 [over.ics.list]p7:
  4273. // In all cases other than those enumerated above, no conversion is possible
  4274. return Result;
  4275. }
  4276. /// TryCopyInitialization - Try to copy-initialize a value of type
  4277. /// ToType from the expression From. Return the implicit conversion
  4278. /// sequence required to pass this argument, which may be a bad
  4279. /// conversion sequence (meaning that the argument cannot be passed to
  4280. /// a parameter of this type). If @p SuppressUserConversions, then we
  4281. /// do not permit any user-defined conversion sequences.
  4282. static ImplicitConversionSequence
  4283. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4284. bool SuppressUserConversions,
  4285. bool InOverloadResolution,
  4286. bool AllowObjCWritebackConversion,
  4287. bool AllowExplicit) {
  4288. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4289. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4290. InOverloadResolution,AllowObjCWritebackConversion);
  4291. // HLSL Change Starts
  4292. if (S.getLangOpts().HLSL) {
  4293. // Note that this is incorrect. Copy initialization isn't syntactically
  4294. // allowed in HLSL, but C++ uses it to perform matching for argments to
  4295. // parameters.
  4296. //
  4297. // The correct fix should go to implicit conversions, but because the type
  4298. // system isn't currently up to spec, it's easier to isolate the behavior by
  4299. // putting this only on this path.
  4300. const bool ListInitFalse = false;
  4301. const bool SuppressDiagTrue = true;
  4302. const Sema::CheckedConversionKind kind = Sema::CCK_ImplicitConversion;
  4303. ImplicitConversionSequence ICS;
  4304. ICS.setStandard();
  4305. unsigned msg;
  4306. CastKind castKind;
  4307. CXXCastPath castPath;
  4308. ExprResult E(From);
  4309. if (::hlsl::TryStaticCastForHLSL(
  4310. &S, E, ToType, kind, From->getSourceRange(), msg, castKind,
  4311. castPath, ListInitFalse, SuppressDiagTrue, &ICS.Standard)) {
  4312. return ICS;
  4313. }
  4314. }
  4315. // HLSL Change Ends
  4316. if (ToType->isReferenceType())
  4317. return TryReferenceInit(S, From, ToType,
  4318. /*FIXME:*/From->getLocStart(),
  4319. SuppressUserConversions,
  4320. AllowExplicit);
  4321. return TryImplicitConversion(S, From, ToType,
  4322. SuppressUserConversions,
  4323. /*AllowExplicit=*/false,
  4324. InOverloadResolution,
  4325. /*CStyle=*/false,
  4326. AllowObjCWritebackConversion,
  4327. /*AllowObjCConversionOnExplicit=*/false);
  4328. }
  4329. static bool TryCopyInitialization(const CanQualType FromQTy,
  4330. const CanQualType ToQTy,
  4331. Sema &S,
  4332. SourceLocation Loc,
  4333. ExprValueKind FromVK) {
  4334. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4335. ImplicitConversionSequence ICS =
  4336. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4337. return !ICS.isBad();
  4338. }
  4339. /// TryObjectArgumentInitialization - Try to initialize the object
  4340. /// parameter of the given member function (@c Method) from the
  4341. /// expression @p From.
  4342. static ImplicitConversionSequence
  4343. TryObjectArgumentInitialization(Sema &S, QualType FromType,
  4344. Expr::Classification FromClassification,
  4345. CXXMethodDecl *Method,
  4346. CXXRecordDecl *ActingContext) {
  4347. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4348. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4349. // const volatile object.
  4350. unsigned Quals = isa<CXXDestructorDecl>(Method) ?
  4351. Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
  4352. QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
  4353. // Set up the conversion sequence as a "bad" conversion, to allow us
  4354. // to exit early.
  4355. ImplicitConversionSequence ICS;
  4356. // We need to have an object of class type.
  4357. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4358. FromType = PT->getPointeeType();
  4359. // When we had a pointer, it's implicitly dereferenced, so we
  4360. // better have an lvalue.
  4361. assert(FromClassification.isLValue());
  4362. }
  4363. assert(FromType->isRecordType());
  4364. // C++0x [over.match.funcs]p4:
  4365. // For non-static member functions, the type of the implicit object
  4366. // parameter is
  4367. //
  4368. // - "lvalue reference to cv X" for functions declared without a
  4369. // ref-qualifier or with the & ref-qualifier
  4370. // - "rvalue reference to cv X" for functions declared with the &&
  4371. // ref-qualifier
  4372. //
  4373. // where X is the class of which the function is a member and cv is the
  4374. // cv-qualification on the member function declaration.
  4375. //
  4376. // However, when finding an implicit conversion sequence for the argument, we
  4377. // are not allowed to create temporaries or perform user-defined conversions
  4378. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4379. // reference binding here, that allows class rvalues to bind to
  4380. // non-constant references.
  4381. // First check the qualifiers.
  4382. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4383. // HLSL Change Starts - for calls other than subscript overloads, disregard const
  4384. FromTypeCanon.removeLocalRestrict(); // HLSL Change - disregard restrict.
  4385. if (!S.getLangOpts().HLSL ||
  4386. (Method != nullptr && Method->getDeclName() == S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  4387. // HLSL Change Ends
  4388. if (ImplicitParamType.getCVRQualifiers()
  4389. != FromTypeCanon.getLocalCVRQualifiers() &&
  4390. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4391. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4392. FromType, ImplicitParamType);
  4393. return ICS;
  4394. }
  4395. } // HLSL Change - end branch
  4396. // Check that we have either the same type or a derived type. It
  4397. // affects the conversion rank.
  4398. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4399. ImplicitConversionKind SecondKind;
  4400. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4401. SecondKind = ICK_Identity;
  4402. } else if (S.IsDerivedFrom(FromType, ClassType))
  4403. SecondKind = ICK_Derived_To_Base;
  4404. else {
  4405. ICS.setBad(BadConversionSequence::unrelated_class,
  4406. FromType, ImplicitParamType);
  4407. return ICS;
  4408. }
  4409. // Check the ref-qualifier.
  4410. switch (Method->getRefQualifier()) {
  4411. case RQ_None:
  4412. // Do nothing; we don't care about lvalueness or rvalueness.
  4413. break;
  4414. case RQ_LValue:
  4415. if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
  4416. // non-const lvalue reference cannot bind to an rvalue
  4417. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4418. ImplicitParamType);
  4419. return ICS;
  4420. }
  4421. break;
  4422. case RQ_RValue:
  4423. if (!FromClassification.isRValue()) {
  4424. // rvalue reference cannot bind to an lvalue
  4425. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4426. ImplicitParamType);
  4427. return ICS;
  4428. }
  4429. break;
  4430. }
  4431. // Success. Mark this as a reference binding.
  4432. ICS.setStandard();
  4433. ICS.Standard.setAsIdentityConversion();
  4434. ICS.Standard.Second = SecondKind;
  4435. ICS.Standard.setFromType(FromType);
  4436. ICS.Standard.setAllToTypes(ImplicitParamType);
  4437. ICS.Standard.ReferenceBinding = true;
  4438. ICS.Standard.DirectBinding = true;
  4439. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4440. ICS.Standard.BindsToFunctionLvalue = false;
  4441. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4442. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4443. = (Method->getRefQualifier() == RQ_None);
  4444. ICS.Standard.ComponentConversion = ICK_Identity;
  4445. return ICS;
  4446. }
  4447. // HLSL Change Starts
  4448. static void
  4449. InitCallParamConversions(Sema &S, const FunctionProtoType *Proto,
  4450. ParmVarDecl *Param, unsigned ArgIdx, Expr *Arg,
  4451. bool SuppressUserConversions,
  4452. bool InOverloadResolution, bool AllowExplicit,
  4453. ImplicitConversionSequence &InConversion,
  4454. ImplicitConversionSequence &OutConversion) {
  4455. hlsl::ParameterModifier paramMods = Proto->getParamMods()[ArgIdx];
  4456. QualType ParamType = Proto->getParamType(ArgIdx);
  4457. if (paramMods.isAnyIn()) {
  4458. InConversion =
  4459. TryCopyInitialization(S, Arg, ParamType, SuppressUserConversions,
  4460. InOverloadResolution, false, AllowExplicit);
  4461. }
  4462. if (paramMods.isAnyOut()) {
  4463. // TryCopyInitialization takes an expression but there isn't one at this
  4464. // point - we're just trying to figure out whether the result value can be
  4465. // converted back into the argument.
  4466. if (Arg->getType().isConstant(S.getASTContext()) || !Arg->isLValue()) {
  4467. OutConversion.setBad(
  4468. BadConversionSequence::FailureKind::rvalue_ref_to_lvalue, ParamType,
  4469. Arg->getType());
  4470. return;
  4471. }
  4472. Expr *OutFrom = DeclRefExpr::Create(
  4473. S.getASTContext(), NestedNameSpecifierLoc(), SourceLocation(), Param,
  4474. true, Param->getLocation(), ParamType.getNonReferenceType(), VK_RValue, nullptr);
  4475. OutConversion = TryCopyInitialization(
  4476. S, OutFrom, Arg->getType(), SuppressUserConversions,
  4477. InOverloadResolution, false, AllowExplicit);
  4478. }
  4479. }
  4480. // HLSL Change Ends
  4481. /// PerformObjectArgumentInitialization - Perform initialization of
  4482. /// the implicit object parameter for the given Method with the given
  4483. /// expression.
  4484. ExprResult
  4485. Sema::PerformObjectArgumentInitialization(Expr *From,
  4486. NestedNameSpecifier *Qualifier,
  4487. NamedDecl *FoundDecl,
  4488. CXXMethodDecl *Method) {
  4489. QualType FromRecordType, DestType;
  4490. QualType ImplicitParamRecordType =
  4491. Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
  4492. Expr::Classification FromClassification;
  4493. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4494. FromRecordType = PT->getPointeeType();
  4495. DestType = Method->getThisType(Context);
  4496. FromClassification = Expr::Classification::makeSimpleLValue();
  4497. } else {
  4498. FromRecordType = From->getType();
  4499. DestType = ImplicitParamRecordType;
  4500. FromClassification = From->Classify(Context);
  4501. }
  4502. // Note that we always use the true parent context when performing
  4503. // the actual argument initialization.
  4504. ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
  4505. *this, From->getType(), FromClassification, Method, Method->getParent());
  4506. if (ICS.isBad()) {
  4507. if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
  4508. Qualifiers FromQs = FromRecordType.getQualifiers();
  4509. Qualifiers ToQs = DestType.getQualifiers();
  4510. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4511. if (CVR) {
  4512. Diag(From->getLocStart(),
  4513. diag::err_member_function_call_bad_cvr)
  4514. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4515. << From->getSourceRange();
  4516. Diag(Method->getLocation(), diag::note_previous_decl)
  4517. << Method->getDeclName();
  4518. return ExprError();
  4519. }
  4520. }
  4521. return Diag(From->getLocStart(),
  4522. diag::err_implicit_object_parameter_init)
  4523. << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
  4524. }
  4525. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4526. ExprResult FromRes =
  4527. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4528. if (FromRes.isInvalid())
  4529. return ExprError();
  4530. From = FromRes.get();
  4531. }
  4532. if (!Context.hasSameType(From->getType(), DestType))
  4533. From = ImpCastExprToType(From, DestType, CK_NoOp,
  4534. From->getValueKind()).get();
  4535. return From;
  4536. }
  4537. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4538. /// expression From to bool (C++0x [conv]p3).
  4539. static ImplicitConversionSequence
  4540. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4541. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4542. /*SuppressUserConversions=*/false,
  4543. /*AllowExplicit=*/true,
  4544. /*InOverloadResolution=*/false,
  4545. /*CStyle=*/false,
  4546. /*AllowObjCWritebackConversion=*/false,
  4547. /*AllowObjCConversionOnExplicit=*/false);
  4548. }
  4549. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4550. /// of the expression From to bool (C++0x [conv]p3).
  4551. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4552. if (checkPlaceholderForOverload(*this, From))
  4553. return ExprError();
  4554. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4555. if (!ICS.isBad())
  4556. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4557. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4558. return Diag(From->getLocStart(),
  4559. diag::err_typecheck_bool_condition)
  4560. << From->getType() << From->getSourceRange();
  4561. return ExprError();
  4562. }
  4563. /// Check that the specified conversion is permitted in a converted constant
  4564. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4565. /// is acceptable.
  4566. static bool CheckConvertedConstantConversions(Sema &S,
  4567. StandardConversionSequence &SCS) {
  4568. // Since we know that the target type is an integral or unscoped enumeration
  4569. // type, most conversion kinds are impossible. All possible First and Third
  4570. // conversions are fine.
  4571. switch (SCS.Second) {
  4572. case ICK_Identity:
  4573. case ICK_NoReturn_Adjustment:
  4574. case ICK_Integral_Promotion:
  4575. case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
  4576. return true;
  4577. case ICK_Boolean_Conversion:
  4578. // Conversion from an integral or unscoped enumeration type to bool is
  4579. // classified as ICK_Boolean_Conversion, but it's also arguably an integral
  4580. // conversion, so we allow it in a converted constant expression.
  4581. //
  4582. // FIXME: Per core issue 1407, we should not allow this, but that breaks
  4583. // a lot of popular code. We should at least add a warning for this
  4584. // (non-conforming) extension.
  4585. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4586. SCS.getToType(2)->isBooleanType();
  4587. case ICK_Pointer_Conversion:
  4588. case ICK_Pointer_Member:
  4589. // C++1z: null pointer conversions and null member pointer conversions are
  4590. // only permitted if the source type is std::nullptr_t.
  4591. return SCS.getFromType()->isNullPtrType();
  4592. case ICK_Floating_Promotion:
  4593. case ICK_Complex_Promotion:
  4594. case ICK_Floating_Conversion:
  4595. case ICK_Complex_Conversion:
  4596. case ICK_Floating_Integral:
  4597. case ICK_Compatible_Conversion:
  4598. case ICK_Derived_To_Base:
  4599. case ICK_Vector_Conversion:
  4600. case ICK_Vector_Splat:
  4601. case ICK_Complex_Real:
  4602. case ICK_Block_Pointer_Conversion:
  4603. case ICK_TransparentUnionConversion:
  4604. case ICK_Writeback_Conversion:
  4605. case ICK_Zero_Event_Conversion:
  4606. case ICK_Flat_Conversion: // HLSL Change
  4607. return false;
  4608. case ICK_Lvalue_To_Rvalue:
  4609. case ICK_Array_To_Pointer:
  4610. case ICK_Function_To_Pointer:
  4611. llvm_unreachable("found a first conversion kind in Second");
  4612. case ICK_Qualification:
  4613. llvm_unreachable("found a third conversion kind in Second");
  4614. case ICK_Num_Conversion_Kinds:
  4615. break;
  4616. }
  4617. llvm_unreachable("unknown conversion kind");
  4618. }
  4619. /// CheckConvertedConstantExpression - Check that the expression From is a
  4620. /// converted constant expression of type T, perform the conversion and produce
  4621. /// the converted expression, per C++11 [expr.const]p3.
  4622. static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
  4623. QualType T, APValue &Value,
  4624. Sema::CCEKind CCE,
  4625. bool RequireInt) {
  4626. assert((S.getLangOpts().CPlusPlus11 || S.getLangOpts().HLSLVersion >= 2017) &&
  4627. "converted constant expression outside C++11");
  4628. if (checkPlaceholderForOverload(S, From))
  4629. return ExprError();
  4630. // C++1z [expr.const]p3:
  4631. // A converted constant expression of type T is an expression,
  4632. // implicitly converted to type T, where the converted
  4633. // expression is a constant expression and the implicit conversion
  4634. // sequence contains only [... list of conversions ...].
  4635. ImplicitConversionSequence ICS =
  4636. TryCopyInitialization(S, From, T,
  4637. /*SuppressUserConversions=*/false,
  4638. /*InOverloadResolution=*/false,
  4639. /*AllowObjcWritebackConversion=*/false,
  4640. /*AllowExplicit=*/false);
  4641. StandardConversionSequence *SCS = nullptr;
  4642. switch (ICS.getKind()) {
  4643. case ImplicitConversionSequence::StandardConversion:
  4644. SCS = &ICS.Standard;
  4645. break;
  4646. case ImplicitConversionSequence::UserDefinedConversion:
  4647. // We are converting to a non-class type, so the Before sequence
  4648. // must be trivial.
  4649. SCS = &ICS.UserDefined.After;
  4650. break;
  4651. case ImplicitConversionSequence::AmbiguousConversion:
  4652. case ImplicitConversionSequence::BadConversion:
  4653. if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
  4654. return S.Diag(From->getLocStart(),
  4655. diag::err_typecheck_converted_constant_expression)
  4656. << From->getType() << From->getSourceRange() << T;
  4657. return ExprError();
  4658. case ImplicitConversionSequence::EllipsisConversion:
  4659. llvm_unreachable("ellipsis conversion in converted constant expression");
  4660. }
  4661. // Check that we would only use permitted conversions.
  4662. if (!CheckConvertedConstantConversions(S, *SCS)) {
  4663. return S.Diag(From->getLocStart(),
  4664. diag::err_typecheck_converted_constant_expression_disallowed)
  4665. << From->getType() << From->getSourceRange() << T;
  4666. }
  4667. // [...] and where the reference binding (if any) binds directly.
  4668. if (SCS->ReferenceBinding && !SCS->DirectBinding) {
  4669. return S.Diag(From->getLocStart(),
  4670. diag::err_typecheck_converted_constant_expression_indirect)
  4671. << From->getType() << From->getSourceRange() << T;
  4672. }
  4673. ExprResult Result =
  4674. S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
  4675. if (Result.isInvalid())
  4676. return Result;
  4677. // Check for a narrowing implicit conversion.
  4678. APValue PreNarrowingValue;
  4679. QualType PreNarrowingType;
  4680. switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
  4681. PreNarrowingType)) {
  4682. case NK_Variable_Narrowing:
  4683. // Implicit conversion to a narrower type, and the value is not a constant
  4684. // expression. We'll diagnose this in a moment.
  4685. case NK_Not_Narrowing:
  4686. break;
  4687. case NK_Constant_Narrowing:
  4688. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4689. << CCE << /*Constant*/1
  4690. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
  4691. break;
  4692. case NK_Type_Narrowing:
  4693. S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
  4694. << CCE << /*Constant*/0 << From->getType() << T;
  4695. break;
  4696. }
  4697. // Check the expression is a constant expression.
  4698. SmallVector<PartialDiagnosticAt, 8> Notes;
  4699. Expr::EvalResult Eval;
  4700. Eval.Diag = &Notes;
  4701. if ((T->isReferenceType()
  4702. ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
  4703. : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
  4704. (RequireInt && !Eval.Val.isInt())) {
  4705. // The expression can't be folded, so we can't keep it at this position in
  4706. // the AST.
  4707. Result = ExprError();
  4708. } else {
  4709. Value = Eval.Val;
  4710. if (Notes.empty()) {
  4711. // It's a constant expression.
  4712. return Result;
  4713. }
  4714. }
  4715. // It's not a constant expression. Produce an appropriate diagnostic.
  4716. if (Notes.size() == 1 &&
  4717. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  4718. S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  4719. else {
  4720. S.Diag(From->getLocStart(), diag::err_expr_not_cce)
  4721. << CCE << From->getSourceRange();
  4722. for (unsigned I = 0; I < Notes.size(); ++I)
  4723. S.Diag(Notes[I].first, Notes[I].second);
  4724. }
  4725. return ExprError();
  4726. }
  4727. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4728. APValue &Value, CCEKind CCE) {
  4729. return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
  4730. }
  4731. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4732. llvm::APSInt &Value,
  4733. CCEKind CCE) {
  4734. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  4735. APValue V;
  4736. auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
  4737. if (!R.isInvalid())
  4738. Value = V.getInt();
  4739. return R;
  4740. }
  4741. /// dropPointerConversions - If the given standard conversion sequence
  4742. /// involves any pointer conversions, remove them. This may change
  4743. /// the result type of the conversion sequence.
  4744. static void dropPointerConversion(StandardConversionSequence &SCS) {
  4745. if (SCS.Second == ICK_Pointer_Conversion) {
  4746. SCS.Second = ICK_Identity;
  4747. SCS.Third = ICK_Identity;
  4748. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  4749. }
  4750. }
  4751. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  4752. /// convert the expression From to an Objective-C pointer type.
  4753. static ImplicitConversionSequence
  4754. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  4755. // Do an implicit conversion to 'id'.
  4756. QualType Ty = S.Context.getObjCIdType();
  4757. ImplicitConversionSequence ICS
  4758. = TryImplicitConversion(S, From, Ty,
  4759. // FIXME: Are these flags correct?
  4760. /*SuppressUserConversions=*/false,
  4761. /*AllowExplicit=*/true,
  4762. /*InOverloadResolution=*/false,
  4763. /*CStyle=*/false,
  4764. /*AllowObjCWritebackConversion=*/false,
  4765. /*AllowObjCConversionOnExplicit=*/true);
  4766. // Strip off any final conversions to 'id'.
  4767. switch (ICS.getKind()) {
  4768. case ImplicitConversionSequence::BadConversion:
  4769. case ImplicitConversionSequence::AmbiguousConversion:
  4770. case ImplicitConversionSequence::EllipsisConversion:
  4771. break;
  4772. case ImplicitConversionSequence::UserDefinedConversion:
  4773. dropPointerConversion(ICS.UserDefined.After);
  4774. break;
  4775. case ImplicitConversionSequence::StandardConversion:
  4776. dropPointerConversion(ICS.Standard);
  4777. break;
  4778. }
  4779. return ICS;
  4780. }
  4781. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  4782. /// conversion of the expression From to an Objective-C pointer type.
  4783. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  4784. if (checkPlaceholderForOverload(*this, From))
  4785. return ExprError();
  4786. QualType Ty = Context.getObjCIdType();
  4787. ImplicitConversionSequence ICS =
  4788. TryContextuallyConvertToObjCPointer(*this, From);
  4789. if (!ICS.isBad())
  4790. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  4791. return ExprError();
  4792. }
  4793. /// Determine whether the provided type is an integral type, or an enumeration
  4794. /// type of a permitted flavor.
  4795. bool Sema::ICEConvertDiagnoser::match(QualType T) {
  4796. return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
  4797. : T->isIntegralOrUnscopedEnumerationType();
  4798. }
  4799. static ExprResult
  4800. diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
  4801. Sema::ContextualImplicitConverter &Converter,
  4802. QualType T, UnresolvedSetImpl &ViableConversions) {
  4803. if (Converter.Suppress)
  4804. return ExprError();
  4805. Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
  4806. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4807. CXXConversionDecl *Conv =
  4808. cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  4809. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  4810. Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
  4811. }
  4812. return From;
  4813. }
  4814. static bool
  4815. diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4816. Sema::ContextualImplicitConverter &Converter,
  4817. QualType T, bool HadMultipleCandidates,
  4818. UnresolvedSetImpl &ExplicitConversions) {
  4819. if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
  4820. DeclAccessPair Found = ExplicitConversions[0];
  4821. CXXConversionDecl *Conversion =
  4822. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4823. // The user probably meant to invoke the given explicit
  4824. // conversion; use it.
  4825. QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
  4826. std::string TypeStr;
  4827. ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
  4828. Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
  4829. << FixItHint::CreateInsertion(From->getLocStart(),
  4830. "static_cast<" + TypeStr + ">(")
  4831. << FixItHint::CreateInsertion(
  4832. SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
  4833. Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
  4834. // If we aren't in a SFINAE context, build a call to the
  4835. // explicit conversion function.
  4836. if (SemaRef.isSFINAEContext())
  4837. return true;
  4838. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4839. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4840. HadMultipleCandidates);
  4841. if (Result.isInvalid())
  4842. return true;
  4843. // Record usage of conversion in an implicit cast.
  4844. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4845. CK_UserDefinedConversion, Result.get(),
  4846. nullptr, Result.get()->getValueKind());
  4847. }
  4848. return false;
  4849. }
  4850. static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
  4851. Sema::ContextualImplicitConverter &Converter,
  4852. QualType T, bool HadMultipleCandidates,
  4853. DeclAccessPair &Found) {
  4854. CXXConversionDecl *Conversion =
  4855. cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4856. SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
  4857. QualType ToType = Conversion->getConversionType().getNonReferenceType();
  4858. if (!Converter.SuppressConversion) {
  4859. if (SemaRef.isSFINAEContext())
  4860. return true;
  4861. Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
  4862. << From->getSourceRange();
  4863. }
  4864. ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
  4865. HadMultipleCandidates);
  4866. if (Result.isInvalid())
  4867. return true;
  4868. // Record usage of conversion in an implicit cast.
  4869. From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
  4870. CK_UserDefinedConversion, Result.get(),
  4871. nullptr, Result.get()->getValueKind());
  4872. return false;
  4873. }
  4874. static ExprResult finishContextualImplicitConversion(
  4875. Sema &SemaRef, SourceLocation Loc, Expr *From,
  4876. Sema::ContextualImplicitConverter &Converter) {
  4877. if (!Converter.match(From->getType()) && !Converter.Suppress)
  4878. Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
  4879. << From->getSourceRange();
  4880. return SemaRef.DefaultLvalueConversion(From);
  4881. }
  4882. static void
  4883. collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
  4884. UnresolvedSetImpl &ViableConversions,
  4885. OverloadCandidateSet &CandidateSet) {
  4886. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4887. DeclAccessPair FoundDecl = ViableConversions[I];
  4888. NamedDecl *D = FoundDecl.getDecl();
  4889. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  4890. if (isa<UsingShadowDecl>(D))
  4891. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4892. CXXConversionDecl *Conv;
  4893. FunctionTemplateDecl *ConvTemplate;
  4894. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  4895. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4896. else
  4897. Conv = cast<CXXConversionDecl>(D);
  4898. if (ConvTemplate)
  4899. SemaRef.AddTemplateConversionCandidate(
  4900. ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
  4901. /*AllowObjCConversionOnExplicit=*/false);
  4902. else
  4903. SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
  4904. ToType, CandidateSet,
  4905. /*AllowObjCConversionOnExplicit=*/false);
  4906. }
  4907. }
  4908. /// \brief Attempt to convert the given expression to a type which is accepted
  4909. /// by the given converter.
  4910. ///
  4911. /// This routine will attempt to convert an expression of class type to a
  4912. /// type accepted by the specified converter. In C++11 and before, the class
  4913. /// must have a single non-explicit conversion function converting to a matching
  4914. /// type. In C++1y, there can be multiple such conversion functions, but only
  4915. /// one target type.
  4916. ///
  4917. /// \param Loc The source location of the construct that requires the
  4918. /// conversion.
  4919. ///
  4920. /// \param From The expression we're converting from.
  4921. ///
  4922. /// \param Converter Used to control and diagnose the conversion process.
  4923. ///
  4924. /// \returns The expression, converted to an integral or enumeration type if
  4925. /// successful.
  4926. ExprResult Sema::PerformContextualImplicitConversion(
  4927. SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
  4928. // We can't perform any more checking for type-dependent expressions.
  4929. if (From->isTypeDependent())
  4930. return From;
  4931. // Process placeholders immediately.
  4932. if (From->hasPlaceholderType()) {
  4933. ExprResult result = CheckPlaceholderExpr(From);
  4934. if (result.isInvalid())
  4935. return result;
  4936. From = result.get();
  4937. }
  4938. // If the expression already has a matching type, we're golden.
  4939. QualType T = From->getType();
  4940. if (Converter.match(T))
  4941. return DefaultLvalueConversion(From);
  4942. // FIXME: Check for missing '()' if T is a function type?
  4943. // We can only perform contextual implicit conversions on objects of class
  4944. // type.
  4945. const RecordType *RecordTy = T->getAs<RecordType>();
  4946. if (!RecordTy || !getLangOpts().CPlusPlus) {
  4947. if (!Converter.Suppress)
  4948. Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
  4949. return From;
  4950. }
  4951. // We must have a complete class type.
  4952. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  4953. ContextualImplicitConverter &Converter;
  4954. Expr *From;
  4955. TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
  4956. : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
  4957. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  4958. Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  4959. }
  4960. } IncompleteDiagnoser(Converter, From);
  4961. if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
  4962. return From;
  4963. // Look for a conversion to an integral or enumeration type.
  4964. UnresolvedSet<4>
  4965. ViableConversions; // These are *potentially* viable in C++1y.
  4966. UnresolvedSet<4> ExplicitConversions;
  4967. const auto &Conversions =
  4968. cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  4969. bool HadMultipleCandidates =
  4970. (std::distance(Conversions.begin(), Conversions.end()) > 1);
  4971. // To check that there is only one target type, in C++1y:
  4972. QualType ToType;
  4973. bool HasUniqueTargetType = true;
  4974. // Collect explicit or viable (potentially in C++1y) conversions.
  4975. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4976. NamedDecl *D = (*I)->getUnderlyingDecl();
  4977. CXXConversionDecl *Conversion;
  4978. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4979. if (ConvTemplate) {
  4980. if (getLangOpts().CPlusPlus14)
  4981. Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4982. else
  4983. continue; // C++11 does not consider conversion operator templates(?).
  4984. } else
  4985. Conversion = cast<CXXConversionDecl>(D);
  4986. assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
  4987. "Conversion operator templates are considered potentially "
  4988. "viable in C++1y");
  4989. QualType CurToType = Conversion->getConversionType().getNonReferenceType();
  4990. if (Converter.match(CurToType) || ConvTemplate) {
  4991. if (Conversion->isExplicit()) {
  4992. // FIXME: For C++1y, do we need this restriction?
  4993. // cf. diagnoseNoViableConversion()
  4994. if (!ConvTemplate)
  4995. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  4996. } else {
  4997. if (!ConvTemplate && getLangOpts().CPlusPlus14) {
  4998. if (ToType.isNull())
  4999. ToType = CurToType.getUnqualifiedType();
  5000. else if (HasUniqueTargetType &&
  5001. (CurToType.getUnqualifiedType() != ToType))
  5002. HasUniqueTargetType = false;
  5003. }
  5004. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  5005. }
  5006. }
  5007. }
  5008. if (getLangOpts().CPlusPlus14) {
  5009. // C++1y [conv]p6:
  5010. // ... An expression e of class type E appearing in such a context
  5011. // is said to be contextually implicitly converted to a specified
  5012. // type T and is well-formed if and only if e can be implicitly
  5013. // converted to a type T that is determined as follows: E is searched
  5014. // for conversion functions whose return type is cv T or reference to
  5015. // cv T such that T is allowed by the context. There shall be
  5016. // exactly one such T.
  5017. // If no unique T is found:
  5018. if (ToType.isNull()) {
  5019. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5020. HadMultipleCandidates,
  5021. ExplicitConversions))
  5022. return ExprError();
  5023. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5024. }
  5025. // If more than one unique Ts are found:
  5026. if (!HasUniqueTargetType)
  5027. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5028. ViableConversions);
  5029. // If one unique T is found:
  5030. // First, build a candidate set from the previously recorded
  5031. // potentially viable conversions.
  5032. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5033. collectViableConversionCandidates(*this, From, ToType, ViableConversions,
  5034. CandidateSet);
  5035. // Then, perform overload resolution over the candidate set.
  5036. OverloadCandidateSet::iterator Best;
  5037. switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
  5038. case OR_Success: {
  5039. // Apply this conversion.
  5040. DeclAccessPair Found =
  5041. DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
  5042. if (recordConversion(*this, Loc, From, Converter, T,
  5043. HadMultipleCandidates, Found))
  5044. return ExprError();
  5045. break;
  5046. }
  5047. case OR_Ambiguous:
  5048. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5049. ViableConversions);
  5050. case OR_No_Viable_Function:
  5051. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5052. HadMultipleCandidates,
  5053. ExplicitConversions))
  5054. return ExprError();
  5055. // fall through 'OR_Deleted' case.
  5056. case OR_Deleted:
  5057. // We'll complain below about a non-integral condition type.
  5058. break;
  5059. }
  5060. } else {
  5061. switch (ViableConversions.size()) {
  5062. case 0: {
  5063. if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
  5064. HadMultipleCandidates,
  5065. ExplicitConversions))
  5066. return ExprError();
  5067. // We'll complain below about a non-integral condition type.
  5068. break;
  5069. }
  5070. case 1: {
  5071. // Apply this conversion.
  5072. DeclAccessPair Found = ViableConversions[0];
  5073. if (recordConversion(*this, Loc, From, Converter, T,
  5074. HadMultipleCandidates, Found))
  5075. return ExprError();
  5076. break;
  5077. }
  5078. default:
  5079. return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
  5080. ViableConversions);
  5081. }
  5082. }
  5083. return finishContextualImplicitConversion(*this, Loc, From, Converter);
  5084. }
  5085. /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
  5086. /// an acceptable non-member overloaded operator for a call whose
  5087. /// arguments have types T1 (and, if non-empty, T2). This routine
  5088. /// implements the check in C++ [over.match.oper]p3b2 concerning
  5089. /// enumeration types.
  5090. static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
  5091. FunctionDecl *Fn,
  5092. ArrayRef<Expr *> Args) {
  5093. QualType T1 = Args[0]->getType();
  5094. QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
  5095. if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
  5096. return true;
  5097. if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
  5098. return true;
  5099. const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
  5100. if (Proto->getNumParams() < 1)
  5101. return false;
  5102. if (T1->isEnumeralType()) {
  5103. QualType ArgType = Proto->getParamType(0).getNonReferenceType();
  5104. if (Context.hasSameUnqualifiedType(T1, ArgType))
  5105. return true;
  5106. }
  5107. if (Proto->getNumParams() < 2)
  5108. return false;
  5109. if (!T2.isNull() && T2->isEnumeralType()) {
  5110. QualType ArgType = Proto->getParamType(1).getNonReferenceType();
  5111. if (Context.hasSameUnqualifiedType(T2, ArgType))
  5112. return true;
  5113. }
  5114. return false;
  5115. }
  5116. /// AddOverloadCandidate - Adds the given function to the set of
  5117. /// candidate functions, using the given function call arguments. If
  5118. /// @p SuppressUserConversions, then don't allow user-defined
  5119. /// conversions via constructors or conversion operators.
  5120. ///
  5121. /// \param PartialOverloading true if we are performing "partial" overloading
  5122. /// based on an incomplete set of function arguments. This feature is used by
  5123. /// code completion.
  5124. void
  5125. Sema::AddOverloadCandidate(FunctionDecl *Function,
  5126. DeclAccessPair FoundDecl,
  5127. ArrayRef<Expr *> Args,
  5128. OverloadCandidateSet &CandidateSet,
  5129. bool SuppressUserConversions,
  5130. bool PartialOverloading,
  5131. bool AllowExplicit) {
  5132. const FunctionProtoType *Proto
  5133. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  5134. assert(Proto && "Functions without a prototype cannot be overloaded");
  5135. assert(!Function->getDescribedFunctionTemplate() &&
  5136. "Use AddTemplateOverloadCandidate for function templates");
  5137. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  5138. if (!isa<CXXConstructorDecl>(Method)) {
  5139. // If we get here, it's because we're calling a member function
  5140. // that is named without a member access expression (e.g.,
  5141. // "this->f") that was either written explicitly or created
  5142. // implicitly. This can happen with a qualified call to a member
  5143. // function, e.g., X::f(). We use an empty type for the implied
  5144. // object argument (C++ [over.call.func]p3), and the acting context
  5145. // is irrelevant.
  5146. AddMethodCandidate(Method, FoundDecl, Method->getParent(),
  5147. QualType(), Expr::Classification::makeSimpleLValue(),
  5148. Args, CandidateSet, SuppressUserConversions,
  5149. PartialOverloading);
  5150. return;
  5151. }
  5152. // We treat a constructor like a non-member function, since its object
  5153. // argument doesn't participate in overload resolution.
  5154. }
  5155. if (!CandidateSet.isNewCandidate(Function) || hlsl::IsIntrinsicOp(Function))
  5156. return;
  5157. // C++ [over.match.oper]p3:
  5158. // if no operand has a class type, only those non-member functions in the
  5159. // lookup set that have a first parameter of type T1 or "reference to
  5160. // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
  5161. // is a right operand) a second parameter of type T2 or "reference to
  5162. // (possibly cv-qualified) T2", when T2 is an enumeration type, are
  5163. // candidate functions.
  5164. if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
  5165. !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
  5166. return;
  5167. // C++11 [class.copy]p11: [DR1402]
  5168. // A defaulted move constructor that is defined as deleted is ignored by
  5169. // overload resolution.
  5170. CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
  5171. if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
  5172. Constructor->isMoveConstructor())
  5173. return;
  5174. // Overload resolution is always an unevaluated context.
  5175. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5176. // Add this candidate
  5177. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  5178. Candidate.FoundDecl = FoundDecl;
  5179. Candidate.Function = Function;
  5180. Candidate.Viable = true;
  5181. Candidate.IsSurrogate = false;
  5182. Candidate.IgnoreObjectArgument = false;
  5183. Candidate.ExplicitCallArguments = Args.size();
  5184. if (Constructor) {
  5185. // C++ [class.copy]p3:
  5186. // A member function template is never instantiated to perform the copy
  5187. // of a class object to an object of its class type.
  5188. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  5189. if (Args.size() == 1 &&
  5190. Constructor->isSpecializationCopyingObject() &&
  5191. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  5192. IsDerivedFrom(Args[0]->getType(), ClassType))) {
  5193. Candidate.Viable = false;
  5194. Candidate.FailureKind = ovl_fail_illegal_constructor;
  5195. return;
  5196. }
  5197. }
  5198. unsigned NumParams = Proto->getNumParams();
  5199. // (C++ 13.3.2p2): A candidate function having fewer than m
  5200. // parameters is viable only if it has an ellipsis in its parameter
  5201. // list (8.3.5).
  5202. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5203. !Proto->isVariadic()) {
  5204. Candidate.Viable = false;
  5205. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5206. return;
  5207. }
  5208. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5209. // is viable only if the (m+1)st parameter has a default argument
  5210. // (8.3.6). For the purposes of overload resolution, the
  5211. // parameter list is truncated on the right, so that there are
  5212. // exactly m parameters.
  5213. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  5214. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5215. // Not enough arguments.
  5216. Candidate.Viable = false;
  5217. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5218. return;
  5219. }
  5220. // (CUDA B.1): Check for invalid calls between targets.
  5221. if (getLangOpts().CUDA)
  5222. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5223. // Skip the check for callers that are implicit members, because in this
  5224. // case we may not yet know what the member's target is; the target is
  5225. // inferred for the member automatically, based on the bases and fields of
  5226. // the class.
  5227. if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
  5228. Candidate.Viable = false;
  5229. Candidate.FailureKind = ovl_fail_bad_target;
  5230. return;
  5231. }
  5232. // Determine the implicit conversion sequences for each of the
  5233. // arguments.
  5234. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5235. if (ArgIdx < NumParams) {
  5236. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5237. // exist for each argument an implicit conversion sequence
  5238. // (13.3.3.1) that converts that argument to the corresponding
  5239. // parameter of F.
  5240. // HLSL Change Starts
  5241. if (getLangOpts().HLSL) {
  5242. InitCallParamConversions(
  5243. *this, Proto, Function->getParamDecl(ArgIdx), ArgIdx, Args[ArgIdx],
  5244. SuppressUserConversions, true, AllowExplicit,
  5245. Candidate.Conversions[ArgIdx], Candidate.OutConversions[ArgIdx]);
  5246. } else {
  5247. QualType ParamType = Proto->getParamType(ArgIdx);
  5248. Candidate.Conversions[ArgIdx]
  5249. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5250. SuppressUserConversions,
  5251. /*InOverloadResolution=*/true,
  5252. /*AllowObjCWritebackConversion=*/
  5253. getLangOpts().ObjCAutoRefCount,
  5254. AllowExplicit);
  5255. }
  5256. // HLSL Change Ends
  5257. if ((Candidate.Conversions[ArgIdx].isInitialized() && Candidate.Conversions[ArgIdx].isBad())
  5258. || (Candidate.OutConversions[ArgIdx].isInitialized() && Candidate.OutConversions[ArgIdx].isBad())) { // HLSL Change - add out conversion, check initialized
  5259. Candidate.Viable = false;
  5260. Candidate.FailureKind = ovl_fail_bad_conversion;
  5261. return;
  5262. }
  5263. } else {
  5264. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5265. // argument for which there is no corresponding parameter is
  5266. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5267. Candidate.Conversions[ArgIdx].setEllipsis();
  5268. }
  5269. }
  5270. if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
  5271. Candidate.Viable = false;
  5272. Candidate.FailureKind = ovl_fail_enable_if;
  5273. Candidate.DeductionFailure.Data = FailedAttr;
  5274. return;
  5275. }
  5276. }
  5277. ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
  5278. bool IsInstance) {
  5279. SmallVector<ObjCMethodDecl*, 4> Methods;
  5280. if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
  5281. return nullptr;
  5282. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5283. bool Match = true;
  5284. ObjCMethodDecl *Method = Methods[b];
  5285. unsigned NumNamedArgs = Sel.getNumArgs();
  5286. // Method might have more arguments than selector indicates. This is due
  5287. // to addition of c-style arguments in method.
  5288. if (Method->param_size() > NumNamedArgs)
  5289. NumNamedArgs = Method->param_size();
  5290. if (Args.size() < NumNamedArgs)
  5291. continue;
  5292. for (unsigned i = 0; i < NumNamedArgs; i++) {
  5293. // We can't do any type-checking on a type-dependent argument.
  5294. if (Args[i]->isTypeDependent()) {
  5295. Match = false;
  5296. break;
  5297. }
  5298. ParmVarDecl *param = Method->parameters()[i];
  5299. Expr *argExpr = Args[i];
  5300. assert(argExpr && "SelectBestMethod(): missing expression");
  5301. // Strip the unbridged-cast placeholder expression off unless it's
  5302. // a consumed argument.
  5303. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  5304. !param->hasAttr<CFConsumedAttr>())
  5305. argExpr = stripARCUnbridgedCast(argExpr);
  5306. // If the parameter is __unknown_anytype, move on to the next method.
  5307. if (param->getType() == Context.UnknownAnyTy) {
  5308. Match = false;
  5309. break;
  5310. }
  5311. ImplicitConversionSequence ConversionState
  5312. = TryCopyInitialization(*this, argExpr, param->getType(),
  5313. /*SuppressUserConversions*/false,
  5314. /*InOverloadResolution=*/true,
  5315. /*AllowObjCWritebackConversion=*/
  5316. getLangOpts().ObjCAutoRefCount,
  5317. /*AllowExplicit*/false);
  5318. if (ConversionState.isBad()) {
  5319. Match = false;
  5320. break;
  5321. }
  5322. }
  5323. // Promote additional arguments to variadic methods.
  5324. if (Match && Method->isVariadic()) {
  5325. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  5326. if (Args[i]->isTypeDependent()) {
  5327. Match = false;
  5328. break;
  5329. }
  5330. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  5331. nullptr);
  5332. if (Arg.isInvalid()) {
  5333. Match = false;
  5334. break;
  5335. }
  5336. }
  5337. } else {
  5338. // Check for extra arguments to non-variadic methods.
  5339. if (Args.size() != NumNamedArgs)
  5340. Match = false;
  5341. else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
  5342. // Special case when selectors have no argument. In this case, select
  5343. // one with the most general result type of 'id'.
  5344. for (unsigned b = 0, e = Methods.size(); b < e; b++) {
  5345. QualType ReturnT = Methods[b]->getReturnType();
  5346. if (ReturnT->isObjCIdType())
  5347. return Methods[b];
  5348. }
  5349. }
  5350. }
  5351. if (Match)
  5352. return Method;
  5353. }
  5354. return nullptr;
  5355. }
  5356. static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
  5357. EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
  5358. bool MissingImplicitThis) {
  5359. // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
  5360. // we need to find the first failing one.
  5361. if (!Function->hasAttrs())
  5362. return nullptr;
  5363. AttrVec Attrs = Function->getAttrs();
  5364. AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
  5365. IsNotEnableIfAttr);
  5366. if (Attrs.begin() == E)
  5367. return nullptr;
  5368. std::reverse(Attrs.begin(), E);
  5369. SFINAETrap Trap(*this);
  5370. // Convert the arguments.
  5371. SmallVector<Expr *, 16> ConvertedArgs;
  5372. bool InitializationFailed = false;
  5373. bool ContainsValueDependentExpr = false;
  5374. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5375. if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
  5376. !cast<CXXMethodDecl>(Function)->isStatic() &&
  5377. !isa<CXXConstructorDecl>(Function)) {
  5378. CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
  5379. ExprResult R =
  5380. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  5381. Method, Method);
  5382. if (R.isInvalid()) {
  5383. InitializationFailed = true;
  5384. break;
  5385. }
  5386. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5387. ConvertedArgs.push_back(R.get());
  5388. } else {
  5389. ExprResult R =
  5390. PerformCopyInitialization(InitializedEntity::InitializeParameter(
  5391. Context,
  5392. Function->getParamDecl(i)),
  5393. SourceLocation(),
  5394. Args[i]);
  5395. if (R.isInvalid()) {
  5396. InitializationFailed = true;
  5397. break;
  5398. }
  5399. ContainsValueDependentExpr |= R.get()->isValueDependent();
  5400. ConvertedArgs.push_back(R.get());
  5401. }
  5402. }
  5403. if (InitializationFailed || Trap.hasErrorOccurred())
  5404. return cast<EnableIfAttr>(Attrs[0]);
  5405. for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
  5406. APValue Result;
  5407. EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
  5408. if (EIA->getCond()->isValueDependent()) {
  5409. // Don't even try now, we'll examine it after instantiation.
  5410. continue;
  5411. }
  5412. if (!EIA->getCond()->EvaluateWithSubstitution(
  5413. Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
  5414. if (!ContainsValueDependentExpr)
  5415. return EIA;
  5416. } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
  5417. return EIA;
  5418. }
  5419. }
  5420. return nullptr;
  5421. }
  5422. /// \brief Add all of the function declarations in the given function set to
  5423. /// the overload candidate set.
  5424. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  5425. ArrayRef<Expr *> Args,
  5426. OverloadCandidateSet& CandidateSet,
  5427. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5428. bool SuppressUserConversions,
  5429. bool PartialOverloading) {
  5430. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  5431. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  5432. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  5433. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  5434. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  5435. cast<CXXMethodDecl>(FD)->getParent(),
  5436. Args[0]->getType(), Args[0]->Classify(Context),
  5437. Args.slice(1), CandidateSet,
  5438. SuppressUserConversions, PartialOverloading);
  5439. else
  5440. AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
  5441. SuppressUserConversions, PartialOverloading);
  5442. } else {
  5443. FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
  5444. if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
  5445. !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
  5446. AddMethodTemplateCandidate(FunTmpl, F.getPair(),
  5447. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  5448. ExplicitTemplateArgs,
  5449. Args[0]->getType(),
  5450. Args[0]->Classify(Context), Args.slice(1),
  5451. CandidateSet, SuppressUserConversions,
  5452. PartialOverloading);
  5453. else
  5454. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  5455. ExplicitTemplateArgs, Args,
  5456. CandidateSet, SuppressUserConversions,
  5457. PartialOverloading);
  5458. }
  5459. }
  5460. }
  5461. /// AddMethodCandidate - Adds a named decl (which is some kind of
  5462. /// method) as a method candidate to the given overload set.
  5463. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
  5464. QualType ObjectType,
  5465. Expr::Classification ObjectClassification,
  5466. ArrayRef<Expr *> Args,
  5467. OverloadCandidateSet& CandidateSet,
  5468. bool SuppressUserConversions) {
  5469. NamedDecl *Decl = FoundDecl.getDecl();
  5470. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  5471. if (isa<UsingShadowDecl>(Decl))
  5472. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  5473. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  5474. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  5475. "Expected a member function template");
  5476. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  5477. /*ExplicitArgs*/ nullptr,
  5478. ObjectType, ObjectClassification,
  5479. Args, CandidateSet,
  5480. SuppressUserConversions);
  5481. } else {
  5482. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  5483. ObjectType, ObjectClassification,
  5484. Args,
  5485. CandidateSet, SuppressUserConversions);
  5486. }
  5487. }
  5488. /// AddMethodCandidate - Adds the given C++ member function to the set
  5489. /// of candidate functions, using the given function call arguments
  5490. /// and the object argument (@c Object). For example, in a call
  5491. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  5492. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  5493. /// allow user-defined conversions via constructors or conversion
  5494. /// operators.
  5495. void
  5496. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  5497. CXXRecordDecl *ActingContext, QualType ObjectType,
  5498. Expr::Classification ObjectClassification,
  5499. ArrayRef<Expr *> Args,
  5500. OverloadCandidateSet &CandidateSet,
  5501. bool SuppressUserConversions,
  5502. bool PartialOverloading) {
  5503. const FunctionProtoType *Proto
  5504. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  5505. assert(Proto && "Methods without a prototype cannot be overloaded");
  5506. assert(!isa<CXXConstructorDecl>(Method) &&
  5507. "Use AddOverloadCandidate for constructors");
  5508. if (!CandidateSet.isNewCandidate(Method))
  5509. return;
  5510. // C++11 [class.copy]p23: [DR1402]
  5511. // A defaulted move assignment operator that is defined as deleted is
  5512. // ignored by overload resolution.
  5513. if (Method->isDefaulted() && Method->isDeleted() &&
  5514. Method->isMoveAssignmentOperator())
  5515. return;
  5516. // Overload resolution is always an unevaluated context.
  5517. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5518. // Add this candidate
  5519. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5520. Candidate.FoundDecl = FoundDecl;
  5521. Candidate.Function = Method;
  5522. Candidate.IsSurrogate = false;
  5523. Candidate.IgnoreObjectArgument = false;
  5524. Candidate.ExplicitCallArguments = Args.size();
  5525. unsigned NumParams = Proto->getNumParams();
  5526. // (C++ 13.3.2p2): A candidate function having fewer than m
  5527. // parameters is viable only if it has an ellipsis in its parameter
  5528. // list (8.3.5).
  5529. if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
  5530. !Proto->isVariadic()) {
  5531. Candidate.Viable = false;
  5532. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5533. return;
  5534. }
  5535. // (C++ 13.3.2p2): A candidate function having more than m parameters
  5536. // is viable only if the (m+1)st parameter has a default argument
  5537. // (8.3.6). For the purposes of overload resolution, the
  5538. // parameter list is truncated on the right, so that there are
  5539. // exactly m parameters.
  5540. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  5541. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  5542. // Not enough arguments.
  5543. Candidate.Viable = false;
  5544. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5545. return;
  5546. }
  5547. Candidate.Viable = true;
  5548. if (Method->isStatic() || ObjectType.isNull())
  5549. // The implicit object argument is ignored.
  5550. Candidate.IgnoreObjectArgument = true;
  5551. else {
  5552. // Determine the implicit conversion sequence for the object
  5553. // parameter.
  5554. Candidate.Conversions[0]
  5555. = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
  5556. Method, ActingContext);
  5557. if (Candidate.Conversions[0].isBad()) {
  5558. Candidate.Viable = false;
  5559. Candidate.FailureKind = ovl_fail_bad_conversion;
  5560. return;
  5561. }
  5562. }
  5563. // (CUDA B.1): Check for invalid calls between targets.
  5564. if (getLangOpts().CUDA)
  5565. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  5566. if (CheckCUDATarget(Caller, Method)) {
  5567. Candidate.Viable = false;
  5568. Candidate.FailureKind = ovl_fail_bad_target;
  5569. return;
  5570. }
  5571. // Determine the implicit conversion sequences for each of the
  5572. // arguments.
  5573. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5574. if (ArgIdx < NumParams) {
  5575. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5576. // exist for each argument an implicit conversion sequence
  5577. // (13.3.3.1) that converts that argument to the corresponding
  5578. // parameter of F.
  5579. QualType ParamType = Proto->getParamType(ArgIdx);
  5580. // HLSL Change Starts
  5581. if (getLangOpts().HLSL && Method->getDeclName() == Context.DeclarationNames.getCXXOperatorName(OO_Subscript)) {
  5582. Candidate.Conversions[ArgIdx + 1] = hlsl::TrySubscriptIndexInitialization(
  5583. this, Args[ArgIdx], ParamType);
  5584. goto EvaluateCandidate;
  5585. }
  5586. // HLSL Change Ends
  5587. Candidate.Conversions[ArgIdx + 1]
  5588. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5589. SuppressUserConversions,
  5590. /*InOverloadResolution=*/true,
  5591. /*AllowObjCWritebackConversion=*/
  5592. getLangOpts().ObjCAutoRefCount);
  5593. EvaluateCandidate:// HLSL Change - present alterantive to TryCopyInitialization
  5594. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  5595. Candidate.Viable = false;
  5596. Candidate.FailureKind = ovl_fail_bad_conversion;
  5597. return;
  5598. }
  5599. } else {
  5600. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5601. // argument for which there is no corresponding parameter is
  5602. // considered to "match the ellipsis" (C+ 13.3.3.1.3).
  5603. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  5604. }
  5605. }
  5606. if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
  5607. Candidate.Viable = false;
  5608. Candidate.FailureKind = ovl_fail_enable_if;
  5609. Candidate.DeductionFailure.Data = FailedAttr;
  5610. return;
  5611. }
  5612. }
  5613. /// \brief Add a C++ member function template as a candidate to the candidate
  5614. /// set, using template argument deduction to produce an appropriate member
  5615. /// function template specialization.
  5616. void
  5617. Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
  5618. DeclAccessPair FoundDecl,
  5619. CXXRecordDecl *ActingContext,
  5620. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5621. QualType ObjectType,
  5622. Expr::Classification ObjectClassification,
  5623. ArrayRef<Expr *> Args,
  5624. OverloadCandidateSet& CandidateSet,
  5625. bool SuppressUserConversions,
  5626. bool PartialOverloading) {
  5627. if (!CandidateSet.isNewCandidate(MethodTmpl))
  5628. return;
  5629. // C++ [over.match.funcs]p7:
  5630. // In each case where a candidate is a function template, candidate
  5631. // function template specializations are generated using template argument
  5632. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5633. // candidate functions in the usual way.113) A given name can refer to one
  5634. // or more function templates and also to a set of overloaded non-template
  5635. // functions. In such a case, the candidate functions generated from each
  5636. // function template are combined with the set of non-template candidate
  5637. // functions.
  5638. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5639. FunctionDecl *Specialization = nullptr;
  5640. if (TemplateDeductionResult Result
  5641. = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
  5642. Specialization, Info, PartialOverloading)) {
  5643. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5644. Candidate.FoundDecl = FoundDecl;
  5645. Candidate.Function = MethodTmpl->getTemplatedDecl();
  5646. Candidate.Viable = false;
  5647. Candidate.FailureKind = ovl_fail_bad_deduction;
  5648. Candidate.IsSurrogate = false;
  5649. Candidate.IgnoreObjectArgument = false;
  5650. Candidate.ExplicitCallArguments = Args.size();
  5651. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5652. Info);
  5653. return;
  5654. }
  5655. // Add the function template specialization produced by template argument
  5656. // deduction as a candidate.
  5657. assert(Specialization && "Missing member function template specialization?");
  5658. assert(isa<CXXMethodDecl>(Specialization) &&
  5659. "Specialization is not a member function?");
  5660. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  5661. ActingContext, ObjectType, ObjectClassification, Args,
  5662. CandidateSet, SuppressUserConversions, PartialOverloading);
  5663. }
  5664. /// \brief Add a C++ function template specialization as a candidate
  5665. /// in the candidate set, using template argument deduction to produce
  5666. /// an appropriate function template specialization.
  5667. void
  5668. Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
  5669. DeclAccessPair FoundDecl,
  5670. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5671. ArrayRef<Expr *> Args,
  5672. OverloadCandidateSet& CandidateSet,
  5673. bool SuppressUserConversions,
  5674. bool PartialOverloading) {
  5675. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5676. return;
  5677. // C++ [over.match.funcs]p7:
  5678. // In each case where a candidate is a function template, candidate
  5679. // function template specializations are generated using template argument
  5680. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5681. // candidate functions in the usual way.113) A given name can refer to one
  5682. // or more function templates and also to a set of overloaded non-template
  5683. // functions. In such a case, the candidate functions generated from each
  5684. // function template are combined with the set of non-template candidate
  5685. // functions.
  5686. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5687. FunctionDecl *Specialization = nullptr;
  5688. if (TemplateDeductionResult Result
  5689. = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
  5690. Specialization, Info, PartialOverloading)) {
  5691. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5692. Candidate.FoundDecl = FoundDecl;
  5693. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5694. Candidate.Viable = false;
  5695. Candidate.FailureKind = ovl_fail_bad_deduction;
  5696. Candidate.IsSurrogate = false;
  5697. Candidate.IgnoreObjectArgument = false;
  5698. Candidate.ExplicitCallArguments = Args.size();
  5699. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5700. Info);
  5701. return;
  5702. }
  5703. // Add the function template specialization produced by template argument
  5704. // deduction as a candidate.
  5705. assert(Specialization && "Missing function template specialization?");
  5706. AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
  5707. SuppressUserConversions, PartialOverloading);
  5708. }
  5709. /// Determine whether this is an allowable conversion from the result
  5710. /// of an explicit conversion operator to the expected type, per C++
  5711. /// [over.match.conv]p1 and [over.match.ref]p1.
  5712. ///
  5713. /// \param ConvType The return type of the conversion function.
  5714. ///
  5715. /// \param ToType The type we are converting to.
  5716. ///
  5717. /// \param AllowObjCPointerConversion Allow a conversion from one
  5718. /// Objective-C pointer to another.
  5719. ///
  5720. /// \returns true if the conversion is allowable, false otherwise.
  5721. static bool isAllowableExplicitConversion(Sema &S,
  5722. QualType ConvType, QualType ToType,
  5723. bool AllowObjCPointerConversion) {
  5724. QualType ToNonRefType = ToType.getNonReferenceType();
  5725. // Easy case: the types are the same.
  5726. if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
  5727. return true;
  5728. // Allow qualification conversions.
  5729. bool ObjCLifetimeConversion;
  5730. if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
  5731. ObjCLifetimeConversion))
  5732. return true;
  5733. // If we're not allowed to consider Objective-C pointer conversions,
  5734. // we're done.
  5735. if (!AllowObjCPointerConversion)
  5736. return false;
  5737. // Is this an Objective-C pointer conversion?
  5738. bool IncompatibleObjC = false;
  5739. QualType ConvertedType;
  5740. return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
  5741. IncompatibleObjC);
  5742. }
  5743. /// AddConversionCandidate - Add a C++ conversion function as a
  5744. /// candidate in the candidate set (C++ [over.match.conv],
  5745. /// C++ [over.match.copy]). From is the expression we're converting from,
  5746. /// and ToType is the type that we're eventually trying to convert to
  5747. /// (which may or may not be the same type as the type that the
  5748. /// conversion function produces).
  5749. void
  5750. Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
  5751. DeclAccessPair FoundDecl,
  5752. CXXRecordDecl *ActingContext,
  5753. Expr *From, QualType ToType,
  5754. OverloadCandidateSet& CandidateSet,
  5755. bool AllowObjCConversionOnExplicit) {
  5756. assert(!Conversion->getDescribedFunctionTemplate() &&
  5757. "Conversion function templates use AddTemplateConversionCandidate");
  5758. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  5759. if (!CandidateSet.isNewCandidate(Conversion))
  5760. return;
  5761. // If the conversion function has an undeduced return type, trigger its
  5762. // deduction now.
  5763. if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
  5764. if (DeduceReturnType(Conversion, From->getExprLoc()))
  5765. return;
  5766. ConvType = Conversion->getConversionType().getNonReferenceType();
  5767. }
  5768. // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
  5769. // operator is only a candidate if its return type is the target type or
  5770. // can be converted to the target type with a qualification conversion.
  5771. if (Conversion->isExplicit() &&
  5772. !isAllowableExplicitConversion(*this, ConvType, ToType,
  5773. AllowObjCConversionOnExplicit))
  5774. return;
  5775. // Overload resolution is always an unevaluated context.
  5776. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5777. // Add this candidate
  5778. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  5779. Candidate.FoundDecl = FoundDecl;
  5780. Candidate.Function = Conversion;
  5781. Candidate.IsSurrogate = false;
  5782. Candidate.IgnoreObjectArgument = false;
  5783. Candidate.FinalConversion.setAsIdentityConversion();
  5784. Candidate.FinalConversion.setFromType(ConvType);
  5785. Candidate.FinalConversion.setAllToTypes(ToType);
  5786. Candidate.Viable = true;
  5787. Candidate.ExplicitCallArguments = 1;
  5788. // C++ [over.match.funcs]p4:
  5789. // For conversion functions, the function is considered to be a member of
  5790. // the class of the implicit implied object argument for the purpose of
  5791. // defining the type of the implicit object parameter.
  5792. //
  5793. // Determine the implicit conversion sequence for the implicit
  5794. // object parameter.
  5795. QualType ImplicitParamType = From->getType();
  5796. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  5797. ImplicitParamType = FromPtrType->getPointeeType();
  5798. CXXRecordDecl *ConversionContext
  5799. = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
  5800. Candidate.Conversions[0]
  5801. = TryObjectArgumentInitialization(*this, From->getType(),
  5802. From->Classify(Context),
  5803. Conversion, ConversionContext);
  5804. if (Candidate.Conversions[0].isBad()) {
  5805. Candidate.Viable = false;
  5806. Candidate.FailureKind = ovl_fail_bad_conversion;
  5807. return;
  5808. }
  5809. // We won't go through a user-defined type conversion function to convert a
  5810. // derived to base as such conversions are given Conversion Rank. They only
  5811. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  5812. QualType FromCanon
  5813. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  5814. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  5815. if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
  5816. Candidate.Viable = false;
  5817. Candidate.FailureKind = ovl_fail_trivial_conversion;
  5818. return;
  5819. }
  5820. // To determine what the conversion from the result of calling the
  5821. // conversion function to the type we're eventually trying to
  5822. // convert to (ToType), we need to synthesize a call to the
  5823. // conversion function and attempt copy initialization from it. This
  5824. // makes sure that we get the right semantics with respect to
  5825. // lvalues/rvalues and the type. Fortunately, we can allocate this
  5826. // call on the stack and we don't need its arguments to be
  5827. // well-formed.
  5828. DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
  5829. VK_LValue, From->getLocStart());
  5830. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  5831. Context.getPointerType(Conversion->getType()),
  5832. CK_FunctionToPointerDecay,
  5833. &ConversionRef, VK_RValue);
  5834. QualType ConversionType = Conversion->getConversionType();
  5835. if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
  5836. Candidate.Viable = false;
  5837. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5838. return;
  5839. }
  5840. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  5841. // Note that it is safe to allocate CallExpr on the stack here because
  5842. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  5843. // allocator).
  5844. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  5845. CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
  5846. From->getLocStart());
  5847. ImplicitConversionSequence ICS =
  5848. TryCopyInitialization(*this, &Call, ToType,
  5849. /*SuppressUserConversions=*/true,
  5850. /*InOverloadResolution=*/false,
  5851. /*AllowObjCWritebackConversion=*/false);
  5852. switch (ICS.getKind()) {
  5853. case ImplicitConversionSequence::StandardConversion:
  5854. Candidate.FinalConversion = ICS.Standard;
  5855. // C++ [over.ics.user]p3:
  5856. // If the user-defined conversion is specified by a specialization of a
  5857. // conversion function template, the second standard conversion sequence
  5858. // shall have exact match rank.
  5859. if (Conversion->getPrimaryTemplate() &&
  5860. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  5861. Candidate.Viable = false;
  5862. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  5863. return;
  5864. }
  5865. // C++0x [dcl.init.ref]p5:
  5866. // In the second case, if the reference is an rvalue reference and
  5867. // the second standard conversion sequence of the user-defined
  5868. // conversion sequence includes an lvalue-to-rvalue conversion, the
  5869. // program is ill-formed.
  5870. if (ToType->isRValueReferenceType() &&
  5871. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5872. Candidate.Viable = false;
  5873. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5874. return;
  5875. }
  5876. break;
  5877. case ImplicitConversionSequence::BadConversion:
  5878. Candidate.Viable = false;
  5879. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5880. return;
  5881. default:
  5882. llvm_unreachable(
  5883. "Can only end up with a standard conversion sequence or failure");
  5884. }
  5885. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  5886. Candidate.Viable = false;
  5887. Candidate.FailureKind = ovl_fail_enable_if;
  5888. Candidate.DeductionFailure.Data = FailedAttr;
  5889. return;
  5890. }
  5891. }
  5892. /// \brief Adds a conversion function template specialization
  5893. /// candidate to the overload set, using template argument deduction
  5894. /// to deduce the template arguments of the conversion function
  5895. /// template from the type that we are converting to (C++
  5896. /// [temp.deduct.conv]).
  5897. void
  5898. Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
  5899. DeclAccessPair FoundDecl,
  5900. CXXRecordDecl *ActingDC,
  5901. Expr *From, QualType ToType,
  5902. OverloadCandidateSet &CandidateSet,
  5903. bool AllowObjCConversionOnExplicit) {
  5904. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  5905. "Only conversion function templates permitted here");
  5906. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5907. return;
  5908. TemplateDeductionInfo Info(CandidateSet.getLocation());
  5909. CXXConversionDecl *Specialization = nullptr;
  5910. if (TemplateDeductionResult Result
  5911. = DeduceTemplateArguments(FunctionTemplate, ToType,
  5912. Specialization, Info)) {
  5913. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5914. Candidate.FoundDecl = FoundDecl;
  5915. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5916. Candidate.Viable = false;
  5917. Candidate.FailureKind = ovl_fail_bad_deduction;
  5918. Candidate.IsSurrogate = false;
  5919. Candidate.IgnoreObjectArgument = false;
  5920. Candidate.ExplicitCallArguments = 1;
  5921. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5922. Info);
  5923. return;
  5924. }
  5925. // Add the conversion function template specialization produced by
  5926. // template argument deduction as a candidate.
  5927. assert(Specialization && "Missing function template specialization?");
  5928. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  5929. CandidateSet, AllowObjCConversionOnExplicit);
  5930. }
  5931. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  5932. /// converts the given @c Object to a function pointer via the
  5933. /// conversion function @c Conversion, and then attempts to call it
  5934. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  5935. /// the type of function that we'll eventually be calling.
  5936. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  5937. DeclAccessPair FoundDecl,
  5938. CXXRecordDecl *ActingContext,
  5939. const FunctionProtoType *Proto,
  5940. Expr *Object,
  5941. ArrayRef<Expr *> Args,
  5942. OverloadCandidateSet& CandidateSet) {
  5943. if (!CandidateSet.isNewCandidate(Conversion))
  5944. return;
  5945. // Overload resolution is always an unevaluated context.
  5946. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5947. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5948. Candidate.FoundDecl = FoundDecl;
  5949. Candidate.Function = nullptr;
  5950. Candidate.Surrogate = Conversion;
  5951. Candidate.Viable = true;
  5952. Candidate.IsSurrogate = true;
  5953. Candidate.IgnoreObjectArgument = false;
  5954. Candidate.ExplicitCallArguments = Args.size();
  5955. // Determine the implicit conversion sequence for the implicit
  5956. // object parameter.
  5957. ImplicitConversionSequence ObjectInit
  5958. = TryObjectArgumentInitialization(*this, Object->getType(),
  5959. Object->Classify(Context),
  5960. Conversion, ActingContext);
  5961. if (ObjectInit.isBad()) {
  5962. Candidate.Viable = false;
  5963. Candidate.FailureKind = ovl_fail_bad_conversion;
  5964. Candidate.Conversions[0] = ObjectInit;
  5965. return;
  5966. }
  5967. // The first conversion is actually a user-defined conversion whose
  5968. // first conversion is ObjectInit's standard conversion (which is
  5969. // effectively a reference binding). Record it as such.
  5970. Candidate.Conversions[0].setUserDefined();
  5971. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  5972. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  5973. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  5974. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  5975. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  5976. Candidate.Conversions[0].UserDefined.After
  5977. = Candidate.Conversions[0].UserDefined.Before;
  5978. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  5979. // Find the
  5980. unsigned NumParams = Proto->getNumParams();
  5981. // (C++ 13.3.2p2): A candidate function having fewer than m
  5982. // parameters is viable only if it has an ellipsis in its parameter
  5983. // list (8.3.5).
  5984. if (Args.size() > NumParams && !Proto->isVariadic()) {
  5985. Candidate.Viable = false;
  5986. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5987. return;
  5988. }
  5989. // Function types don't have any default arguments, so just check if
  5990. // we have enough arguments.
  5991. if (Args.size() < NumParams) {
  5992. // Not enough arguments.
  5993. Candidate.Viable = false;
  5994. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5995. return;
  5996. }
  5997. // Determine the implicit conversion sequences for each of the
  5998. // arguments.
  5999. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6000. if (ArgIdx < NumParams) {
  6001. // (C++ 13.3.2p3): for F to be a viable function, there shall
  6002. // exist for each argument an implicit conversion sequence
  6003. // (13.3.3.1) that converts that argument to the corresponding
  6004. // parameter of F.
  6005. QualType ParamType = Proto->getParamType(ArgIdx);
  6006. Candidate.Conversions[ArgIdx + 1]
  6007. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  6008. /*SuppressUserConversions=*/false,
  6009. /*InOverloadResolution=*/false,
  6010. /*AllowObjCWritebackConversion=*/
  6011. getLangOpts().ObjCAutoRefCount);
  6012. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  6013. Candidate.Viable = false;
  6014. Candidate.FailureKind = ovl_fail_bad_conversion;
  6015. return;
  6016. }
  6017. } else {
  6018. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  6019. // argument for which there is no corresponding parameter is
  6020. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  6021. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  6022. }
  6023. }
  6024. if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
  6025. Candidate.Viable = false;
  6026. Candidate.FailureKind = ovl_fail_enable_if;
  6027. Candidate.DeductionFailure.Data = FailedAttr;
  6028. return;
  6029. }
  6030. }
  6031. /// \brief Add overload candidates for overloaded operators that are
  6032. /// member functions.
  6033. ///
  6034. /// Add the overloaded operator candidates that are member functions
  6035. /// for the operator Op that was used in an operator expression such
  6036. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  6037. /// CandidateSet will store the added overload candidates. (C++
  6038. /// [over.match.oper]).
  6039. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  6040. SourceLocation OpLoc,
  6041. ArrayRef<Expr *> Args,
  6042. OverloadCandidateSet& CandidateSet,
  6043. SourceRange OpRange) {
  6044. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  6045. // C++ [over.match.oper]p3:
  6046. // For a unary operator @ with an operand of a type whose
  6047. // cv-unqualified version is T1, and for a binary operator @ with
  6048. // a left operand of a type whose cv-unqualified version is T1 and
  6049. // a right operand of a type whose cv-unqualified version is T2,
  6050. // three sets of candidate functions, designated member
  6051. // candidates, non-member candidates and built-in candidates, are
  6052. // constructed as follows:
  6053. QualType T1 = Args[0]->getType();
  6054. // -- If T1 is a complete class type or a class currently being
  6055. // defined, the set of member candidates is the result of the
  6056. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  6057. // the set of member candidates is empty.
  6058. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  6059. // Complete the type if it can be completed.
  6060. RequireCompleteType(OpLoc, T1, 0);
  6061. // If the type is neither complete nor being defined, bail out now.
  6062. if (!T1Rec->getDecl()->getDefinition())
  6063. return;
  6064. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  6065. LookupQualifiedName(Operators, T1Rec->getDecl());
  6066. Operators.suppressDiagnostics();
  6067. for (LookupResult::iterator Oper = Operators.begin(),
  6068. OperEnd = Operators.end();
  6069. Oper != OperEnd;
  6070. ++Oper)
  6071. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  6072. Args[0]->Classify(Context),
  6073. Args.slice(1),
  6074. CandidateSet,
  6075. /* SuppressUserConversions = */ false);
  6076. }
  6077. }
  6078. /// AddBuiltinCandidate - Add a candidate for a built-in
  6079. /// operator. ResultTy and ParamTys are the result and parameter types
  6080. /// of the built-in candidate, respectively. Args and NumArgs are the
  6081. /// arguments being passed to the candidate. IsAssignmentOperator
  6082. /// should be true when this built-in candidate is an assignment
  6083. /// operator. NumContextualBoolArguments is the number of arguments
  6084. /// (at the beginning of the argument list) that will be contextually
  6085. /// converted to bool.
  6086. void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
  6087. ArrayRef<Expr *> Args,
  6088. OverloadCandidateSet& CandidateSet,
  6089. bool IsAssignmentOperator,
  6090. unsigned NumContextualBoolArguments) {
  6091. // Overload resolution is always an unevaluated context.
  6092. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  6093. // Add this candidate
  6094. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  6095. Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
  6096. Candidate.Function = nullptr;
  6097. Candidate.IsSurrogate = false;
  6098. Candidate.IgnoreObjectArgument = false;
  6099. Candidate.BuiltinTypes.ResultTy = ResultTy;
  6100. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  6101. Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
  6102. // Determine the implicit conversion sequences for each of the
  6103. // arguments.
  6104. Candidate.Viable = true;
  6105. Candidate.ExplicitCallArguments = Args.size();
  6106. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6107. // C++ [over.match.oper]p4:
  6108. // For the built-in assignment operators, conversions of the
  6109. // left operand are restricted as follows:
  6110. // -- no temporaries are introduced to hold the left operand, and
  6111. // -- no user-defined conversions are applied to the left
  6112. // operand to achieve a type match with the left-most
  6113. // parameter of a built-in candidate.
  6114. //
  6115. // We block these conversions by turning off user-defined
  6116. // conversions, since that is the only way that initialization of
  6117. // a reference to a non-class type can occur from something that
  6118. // is not of the same type.
  6119. if (ArgIdx < NumContextualBoolArguments) {
  6120. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  6121. "Contextual conversion to bool requires bool type");
  6122. Candidate.Conversions[ArgIdx]
  6123. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  6124. } else {
  6125. Candidate.Conversions[ArgIdx]
  6126. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  6127. ArgIdx == 0 && IsAssignmentOperator,
  6128. /*InOverloadResolution=*/false,
  6129. /*AllowObjCWritebackConversion=*/
  6130. getLangOpts().ObjCAutoRefCount);
  6131. }
  6132. if (Candidate.Conversions[ArgIdx].isBad()) {
  6133. Candidate.Viable = false;
  6134. Candidate.FailureKind = ovl_fail_bad_conversion;
  6135. break;
  6136. }
  6137. }
  6138. }
  6139. namespace {
  6140. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  6141. /// candidate operator functions for built-in operators (C++
  6142. /// [over.built]). The types are separated into pointer types and
  6143. /// enumeration types.
  6144. class BuiltinCandidateTypeSet {
  6145. /// TypeSet - A set of types.
  6146. typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
  6147. /// PointerTypes - The set of pointer types that will be used in the
  6148. /// built-in candidates.
  6149. TypeSet PointerTypes;
  6150. /// MemberPointerTypes - The set of member pointer types that will be
  6151. /// used in the built-in candidates.
  6152. TypeSet MemberPointerTypes;
  6153. /// EnumerationTypes - The set of enumeration types that will be
  6154. /// used in the built-in candidates.
  6155. TypeSet EnumerationTypes;
  6156. /// \brief The set of vector types that will be used in the built-in
  6157. /// candidates.
  6158. TypeSet VectorTypes;
  6159. /// \brief A flag indicating non-record types are viable candidates
  6160. bool HasNonRecordTypes;
  6161. /// \brief A flag indicating whether either arithmetic or enumeration types
  6162. /// were present in the candidate set.
  6163. bool HasArithmeticOrEnumeralTypes;
  6164. /// \brief A flag indicating whether the nullptr type was present in the
  6165. /// candidate set.
  6166. bool HasNullPtrType;
  6167. /// Sema - The semantic analysis instance where we are building the
  6168. /// candidate type set.
  6169. Sema &SemaRef;
  6170. /// Context - The AST context in which we will build the type sets.
  6171. ASTContext &Context;
  6172. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6173. const Qualifiers &VisibleQuals);
  6174. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  6175. public:
  6176. /// iterator - Iterates through the types that are part of the set.
  6177. typedef TypeSet::iterator iterator;
  6178. BuiltinCandidateTypeSet(Sema &SemaRef)
  6179. : HasNonRecordTypes(false),
  6180. HasArithmeticOrEnumeralTypes(false),
  6181. HasNullPtrType(false),
  6182. SemaRef(SemaRef),
  6183. Context(SemaRef.Context) { }
  6184. void AddTypesConvertedFrom(QualType Ty,
  6185. SourceLocation Loc,
  6186. bool AllowUserConversions,
  6187. bool AllowExplicitConversions,
  6188. const Qualifiers &VisibleTypeConversionsQuals);
  6189. /// pointer_begin - First pointer type found;
  6190. iterator pointer_begin() { return PointerTypes.begin(); }
  6191. /// pointer_end - Past the last pointer type found;
  6192. iterator pointer_end() { return PointerTypes.end(); }
  6193. /// member_pointer_begin - First member pointer type found;
  6194. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  6195. /// member_pointer_end - Past the last member pointer type found;
  6196. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  6197. /// enumeration_begin - First enumeration type found;
  6198. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  6199. /// enumeration_end - Past the last enumeration type found;
  6200. iterator enumeration_end() { return EnumerationTypes.end(); }
  6201. iterator vector_begin() { return VectorTypes.begin(); }
  6202. iterator vector_end() { return VectorTypes.end(); }
  6203. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  6204. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  6205. bool hasNullPtrType() const { return HasNullPtrType; }
  6206. };
  6207. } // end anonymous namespace
  6208. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  6209. /// the set of pointer types along with any more-qualified variants of
  6210. /// that type. For example, if @p Ty is "int const *", this routine
  6211. /// will add "int const *", "int const volatile *", "int const
  6212. /// restrict *", and "int const volatile restrict *" to the set of
  6213. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6214. /// false otherwise.
  6215. ///
  6216. /// FIXME: what to do about extended qualifiers?
  6217. bool
  6218. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  6219. const Qualifiers &VisibleQuals) {
  6220. // Insert this type.
  6221. if (!PointerTypes.insert(Ty).second)
  6222. return false;
  6223. QualType PointeeTy;
  6224. const PointerType *PointerTy = Ty->getAs<PointerType>();
  6225. bool buildObjCPtr = false;
  6226. if (!PointerTy) {
  6227. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  6228. PointeeTy = PTy->getPointeeType();
  6229. buildObjCPtr = true;
  6230. } else {
  6231. PointeeTy = PointerTy->getPointeeType();
  6232. }
  6233. // Don't add qualified variants of arrays. For one, they're not allowed
  6234. // (the qualifier would sink to the element type), and for another, the
  6235. // only overload situation where it matters is subscript or pointer +- int,
  6236. // and those shouldn't have qualifier variants anyway.
  6237. if (PointeeTy->isArrayType())
  6238. return true;
  6239. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6240. bool hasVolatile = VisibleQuals.hasVolatile();
  6241. bool hasRestrict = VisibleQuals.hasRestrict();
  6242. // Iterate through all strict supersets of BaseCVR.
  6243. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6244. if ((CVR | BaseCVR) != CVR) continue;
  6245. // Skip over volatile if no volatile found anywhere in the types.
  6246. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  6247. // Skip over restrict if no restrict found anywhere in the types, or if
  6248. // the type cannot be restrict-qualified.
  6249. if ((CVR & Qualifiers::Restrict) &&
  6250. (!hasRestrict ||
  6251. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  6252. continue;
  6253. // Build qualified pointee type.
  6254. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6255. // Build qualified pointer type.
  6256. QualType QPointerTy;
  6257. if (!buildObjCPtr)
  6258. QPointerTy = Context.getPointerType(QPointeeTy);
  6259. else
  6260. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  6261. // Insert qualified pointer type.
  6262. PointerTypes.insert(QPointerTy);
  6263. }
  6264. return true;
  6265. }
  6266. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  6267. /// to the set of pointer types along with any more-qualified variants of
  6268. /// that type. For example, if @p Ty is "int const *", this routine
  6269. /// will add "int const *", "int const volatile *", "int const
  6270. /// restrict *", and "int const volatile restrict *" to the set of
  6271. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  6272. /// false otherwise.
  6273. ///
  6274. /// FIXME: what to do about extended qualifiers?
  6275. bool
  6276. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  6277. QualType Ty) {
  6278. // Insert this type.
  6279. if (!MemberPointerTypes.insert(Ty).second)
  6280. return false;
  6281. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  6282. assert(PointerTy && "type was not a member pointer type!");
  6283. QualType PointeeTy = PointerTy->getPointeeType();
  6284. // Don't add qualified variants of arrays. For one, they're not allowed
  6285. // (the qualifier would sink to the element type), and for another, the
  6286. // only overload situation where it matters is subscript or pointer +- int,
  6287. // and those shouldn't have qualifier variants anyway.
  6288. if (PointeeTy->isArrayType())
  6289. return true;
  6290. const Type *ClassTy = PointerTy->getClass();
  6291. // Iterate through all strict supersets of the pointee type's CVR
  6292. // qualifiers.
  6293. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  6294. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  6295. if ((CVR | BaseCVR) != CVR) continue;
  6296. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  6297. MemberPointerTypes.insert(
  6298. Context.getMemberPointerType(QPointeeTy, ClassTy));
  6299. }
  6300. return true;
  6301. }
  6302. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  6303. /// Ty can be implicit converted to the given set of @p Types. We're
  6304. /// primarily interested in pointer types and enumeration types. We also
  6305. /// take member pointer types, for the conditional operator.
  6306. /// AllowUserConversions is true if we should look at the conversion
  6307. /// functions of a class type, and AllowExplicitConversions if we
  6308. /// should also include the explicit conversion functions of a class
  6309. /// type.
  6310. void
  6311. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  6312. SourceLocation Loc,
  6313. bool AllowUserConversions,
  6314. bool AllowExplicitConversions,
  6315. const Qualifiers &VisibleQuals) {
  6316. // Only deal with canonical types.
  6317. Ty = Context.getCanonicalType(Ty);
  6318. // Look through reference types; they aren't part of the type of an
  6319. // expression for the purposes of conversions.
  6320. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  6321. Ty = RefTy->getPointeeType();
  6322. // If we're dealing with an array type, decay to the pointer.
  6323. if (Ty->isArrayType())
  6324. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  6325. // Otherwise, we don't care about qualifiers on the type.
  6326. Ty = Ty.getLocalUnqualifiedType();
  6327. // Flag if we ever add a non-record type.
  6328. const RecordType *TyRec = Ty->getAs<RecordType>();
  6329. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  6330. // Flag if we encounter an arithmetic type.
  6331. HasArithmeticOrEnumeralTypes =
  6332. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  6333. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  6334. PointerTypes.insert(Ty);
  6335. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  6336. // Insert our type, and its more-qualified variants, into the set
  6337. // of types.
  6338. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  6339. return;
  6340. } else if (Ty->isMemberPointerType()) {
  6341. // Member pointers are far easier, since the pointee can't be converted.
  6342. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  6343. return;
  6344. } else if (Ty->isEnumeralType()) {
  6345. HasArithmeticOrEnumeralTypes = true;
  6346. EnumerationTypes.insert(Ty);
  6347. } else if (Ty->isVectorType()) {
  6348. // We treat vector types as arithmetic types in many contexts as an
  6349. // extension.
  6350. HasArithmeticOrEnumeralTypes = true;
  6351. VectorTypes.insert(Ty);
  6352. } else if (Ty->isNullPtrType()) {
  6353. HasNullPtrType = true;
  6354. } else if (AllowUserConversions && TyRec) {
  6355. // No conversion functions in incomplete types.
  6356. if (SemaRef.RequireCompleteType(Loc, Ty, 0))
  6357. return;
  6358. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6359. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6360. if (isa<UsingShadowDecl>(D))
  6361. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6362. // Skip conversion function templates; they don't tell us anything
  6363. // about which builtin types we can convert to.
  6364. if (isa<FunctionTemplateDecl>(D))
  6365. continue;
  6366. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  6367. if (AllowExplicitConversions || !Conv->isExplicit()) {
  6368. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  6369. VisibleQuals);
  6370. }
  6371. }
  6372. }
  6373. }
  6374. /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
  6375. /// the volatile- and non-volatile-qualified assignment operators for the
  6376. /// given type to the candidate set.
  6377. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  6378. QualType T,
  6379. ArrayRef<Expr *> Args,
  6380. OverloadCandidateSet &CandidateSet) {
  6381. QualType ParamTypes[2];
  6382. // T& operator=(T&, T)
  6383. ParamTypes[0] = S.Context.getLValueReferenceType(T);
  6384. ParamTypes[1] = T;
  6385. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6386. /*IsAssignmentOperator=*/true);
  6387. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  6388. // volatile T& operator=(volatile T&, T)
  6389. ParamTypes[0]
  6390. = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
  6391. ParamTypes[1] = T;
  6392. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  6393. /*IsAssignmentOperator=*/true);
  6394. }
  6395. }
  6396. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  6397. /// if any, found in visible type conversion functions found in ArgExpr's type.
  6398. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  6399. Qualifiers VRQuals;
  6400. const RecordType *TyRec;
  6401. if (const MemberPointerType *RHSMPType =
  6402. ArgExpr->getType()->getAs<MemberPointerType>())
  6403. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  6404. else
  6405. TyRec = ArgExpr->getType()->getAs<RecordType>();
  6406. if (!TyRec) {
  6407. // Just to be safe, assume the worst case.
  6408. VRQuals.addVolatile();
  6409. VRQuals.addRestrict();
  6410. return VRQuals;
  6411. }
  6412. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  6413. if (!ClassDecl->hasDefinition())
  6414. return VRQuals;
  6415. for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
  6416. if (isa<UsingShadowDecl>(D))
  6417. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  6418. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  6419. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  6420. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  6421. CanTy = ResTypeRef->getPointeeType();
  6422. // Need to go down the pointer/mempointer chain and add qualifiers
  6423. // as see them.
  6424. bool done = false;
  6425. while (!done) {
  6426. if (CanTy.isRestrictQualified())
  6427. VRQuals.addRestrict();
  6428. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  6429. CanTy = ResTypePtr->getPointeeType();
  6430. else if (const MemberPointerType *ResTypeMPtr =
  6431. CanTy->getAs<MemberPointerType>())
  6432. CanTy = ResTypeMPtr->getPointeeType();
  6433. else
  6434. done = true;
  6435. if (CanTy.isVolatileQualified())
  6436. VRQuals.addVolatile();
  6437. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  6438. return VRQuals;
  6439. }
  6440. }
  6441. }
  6442. return VRQuals;
  6443. }
  6444. namespace {
  6445. /// \brief Helper class to manage the addition of builtin operator overload
  6446. /// candidates. It provides shared state and utility methods used throughout
  6447. /// the process, as well as a helper method to add each group of builtin
  6448. /// operator overloads from the standard to a candidate set.
  6449. class BuiltinOperatorOverloadBuilder {
  6450. // Common instance state available to all overload candidate addition methods.
  6451. Sema &S;
  6452. ArrayRef<Expr *> Args;
  6453. Qualifiers VisibleTypeConversionsQuals;
  6454. bool HasArithmeticOrEnumeralCandidateType;
  6455. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  6456. OverloadCandidateSet &CandidateSet;
  6457. // Define some constants used to index and iterate over the arithemetic types
  6458. // provided via the getArithmeticType() method below.
  6459. // The "promoted arithmetic types" are the arithmetic
  6460. // types are that preserved by promotion (C++ [over.built]p2).
  6461. static const unsigned FirstIntegralType = 3;
  6462. static const unsigned LastIntegralType = 20;
  6463. static const unsigned FirstPromotedIntegralType = 3,
  6464. LastPromotedIntegralType = 11;
  6465. static const unsigned FirstPromotedArithmeticType = 0,
  6466. LastPromotedArithmeticType = 11;
  6467. static const unsigned NumArithmeticTypes = 20;
  6468. /// \brief Get the canonical type for a given arithmetic type index.
  6469. CanQualType getArithmeticType(unsigned index) {
  6470. assert(index < NumArithmeticTypes);
  6471. static CanQualType ASTContext::* const
  6472. ArithmeticTypes[NumArithmeticTypes] = {
  6473. // Start of promoted types.
  6474. &ASTContext::FloatTy,
  6475. &ASTContext::DoubleTy,
  6476. &ASTContext::LongDoubleTy,
  6477. // Start of integral types.
  6478. &ASTContext::IntTy,
  6479. &ASTContext::LongTy,
  6480. &ASTContext::LongLongTy,
  6481. &ASTContext::Int128Ty,
  6482. &ASTContext::UnsignedIntTy,
  6483. &ASTContext::UnsignedLongTy,
  6484. &ASTContext::UnsignedLongLongTy,
  6485. &ASTContext::UnsignedInt128Ty,
  6486. // End of promoted types.
  6487. &ASTContext::BoolTy,
  6488. &ASTContext::CharTy,
  6489. &ASTContext::WCharTy,
  6490. &ASTContext::Char16Ty,
  6491. &ASTContext::Char32Ty,
  6492. &ASTContext::SignedCharTy,
  6493. &ASTContext::ShortTy,
  6494. &ASTContext::UnsignedCharTy,
  6495. &ASTContext::UnsignedShortTy,
  6496. // End of integral types.
  6497. // FIXME: What about complex? What about half?
  6498. };
  6499. return S.Context.*ArithmeticTypes[index];
  6500. }
  6501. /// \brief Gets the canonical type resulting from the usual arithemetic
  6502. /// converions for the given arithmetic types.
  6503. CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
  6504. // Accelerator table for performing the usual arithmetic conversions.
  6505. // The rules are basically:
  6506. // - if either is floating-point, use the wider floating-point
  6507. // - if same signedness, use the higher rank
  6508. // - if same size, use unsigned of the higher rank
  6509. // - use the larger type
  6510. // These rules, together with the axiom that higher ranks are
  6511. // never smaller, are sufficient to precompute all of these results
  6512. // *except* when dealing with signed types of higher rank.
  6513. // (we could precompute SLL x UI for all known platforms, but it's
  6514. // better not to make any assumptions).
  6515. // We assume that int128 has a higher rank than long long on all platforms.
  6516. enum PromotedType {
  6517. Dep=-1,
  6518. Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
  6519. };
  6520. static const PromotedType ConversionsTable[LastPromotedArithmeticType]
  6521. [LastPromotedArithmeticType] = {
  6522. /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
  6523. /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
  6524. /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
  6525. /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
  6526. /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
  6527. /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
  6528. /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
  6529. /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
  6530. /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
  6531. /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
  6532. /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
  6533. };
  6534. assert(L < LastPromotedArithmeticType);
  6535. assert(R < LastPromotedArithmeticType);
  6536. int Idx = ConversionsTable[L][R];
  6537. // Fast path: the table gives us a concrete answer.
  6538. if (Idx != Dep) return getArithmeticType(Idx);
  6539. // Slow path: we need to compare widths.
  6540. // An invariant is that the signed type has higher rank.
  6541. CanQualType LT = getArithmeticType(L),
  6542. RT = getArithmeticType(R);
  6543. unsigned LW = S.Context.getIntWidth(LT),
  6544. RW = S.Context.getIntWidth(RT);
  6545. // If they're different widths, use the signed type.
  6546. if (LW > RW) return LT;
  6547. else if (LW < RW) return RT;
  6548. // Otherwise, use the unsigned type of the signed type's rank.
  6549. if (L == SL || R == SL) return S.Context.UnsignedLongTy;
  6550. assert(L == SLL || R == SLL);
  6551. return S.Context.UnsignedLongLongTy;
  6552. }
  6553. /// \brief Helper method to factor out the common pattern of adding overloads
  6554. /// for '++' and '--' builtin operators.
  6555. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  6556. bool HasVolatile,
  6557. bool HasRestrict) {
  6558. QualType ParamTypes[2] = {
  6559. S.Context.getLValueReferenceType(CandidateTy),
  6560. S.Context.IntTy
  6561. };
  6562. // Non-volatile version.
  6563. if (Args.size() == 1)
  6564. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6565. else
  6566. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6567. // Use a heuristic to reduce number of builtin candidates in the set:
  6568. // add volatile version only if there are conversions to a volatile type.
  6569. if (HasVolatile) {
  6570. ParamTypes[0] =
  6571. S.Context.getLValueReferenceType(
  6572. S.Context.getVolatileType(CandidateTy));
  6573. if (Args.size() == 1)
  6574. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6575. else
  6576. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6577. }
  6578. // Add restrict version only if there are conversions to a restrict type
  6579. // and our candidate type is a non-restrict-qualified pointer.
  6580. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  6581. !CandidateTy.isRestrictQualified()) {
  6582. ParamTypes[0]
  6583. = S.Context.getLValueReferenceType(
  6584. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  6585. if (Args.size() == 1)
  6586. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6587. else
  6588. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6589. if (HasVolatile) {
  6590. ParamTypes[0]
  6591. = S.Context.getLValueReferenceType(
  6592. S.Context.getCVRQualifiedType(CandidateTy,
  6593. (Qualifiers::Volatile |
  6594. Qualifiers::Restrict)));
  6595. if (Args.size() == 1)
  6596. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  6597. else
  6598. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
  6599. }
  6600. }
  6601. }
  6602. public:
  6603. BuiltinOperatorOverloadBuilder(
  6604. Sema &S, ArrayRef<Expr *> Args,
  6605. Qualifiers VisibleTypeConversionsQuals,
  6606. bool HasArithmeticOrEnumeralCandidateType,
  6607. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  6608. OverloadCandidateSet &CandidateSet)
  6609. : S(S), Args(Args),
  6610. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  6611. HasArithmeticOrEnumeralCandidateType(
  6612. HasArithmeticOrEnumeralCandidateType),
  6613. CandidateTypes(CandidateTypes),
  6614. CandidateSet(CandidateSet) {
  6615. // Validate some of our static helper constants in debug builds.
  6616. assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
  6617. "Invalid first promoted integral type");
  6618. assert(getArithmeticType(LastPromotedIntegralType - 1)
  6619. == S.Context.UnsignedInt128Ty &&
  6620. "Invalid last promoted integral type");
  6621. assert(getArithmeticType(FirstPromotedArithmeticType)
  6622. == S.Context.FloatTy &&
  6623. "Invalid first promoted arithmetic type");
  6624. assert(getArithmeticType(LastPromotedArithmeticType - 1)
  6625. == S.Context.UnsignedInt128Ty &&
  6626. "Invalid last promoted arithmetic type");
  6627. }
  6628. // C++ [over.built]p3:
  6629. //
  6630. // For every pair (T, VQ), where T is an arithmetic type, and VQ
  6631. // is either volatile or empty, there exist candidate operator
  6632. // functions of the form
  6633. //
  6634. // VQ T& operator++(VQ T&);
  6635. // T operator++(VQ T&, int);
  6636. //
  6637. // C++ [over.built]p4:
  6638. //
  6639. // For every pair (T, VQ), where T is an arithmetic type other
  6640. // than bool, and VQ is either volatile or empty, there exist
  6641. // candidate operator functions of the form
  6642. //
  6643. // VQ T& operator--(VQ T&);
  6644. // T operator--(VQ T&, int);
  6645. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  6646. if (!HasArithmeticOrEnumeralCandidateType)
  6647. return;
  6648. for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
  6649. Arith < NumArithmeticTypes; ++Arith) {
  6650. addPlusPlusMinusMinusStyleOverloads(
  6651. getArithmeticType(Arith),
  6652. VisibleTypeConversionsQuals.hasVolatile(),
  6653. VisibleTypeConversionsQuals.hasRestrict());
  6654. }
  6655. }
  6656. // C++ [over.built]p5:
  6657. //
  6658. // For every pair (T, VQ), where T is a cv-qualified or
  6659. // cv-unqualified object type, and VQ is either volatile or
  6660. // empty, there exist candidate operator functions of the form
  6661. //
  6662. // T*VQ& operator++(T*VQ&);
  6663. // T*VQ& operator--(T*VQ&);
  6664. // T* operator++(T*VQ&, int);
  6665. // T* operator--(T*VQ&, int);
  6666. void addPlusPlusMinusMinusPointerOverloads() {
  6667. for (BuiltinCandidateTypeSet::iterator
  6668. Ptr = CandidateTypes[0].pointer_begin(),
  6669. PtrEnd = CandidateTypes[0].pointer_end();
  6670. Ptr != PtrEnd; ++Ptr) {
  6671. // Skip pointer types that aren't pointers to object types.
  6672. if (!(*Ptr)->getPointeeType()->isObjectType())
  6673. continue;
  6674. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  6675. (!(*Ptr).isVolatileQualified() &&
  6676. VisibleTypeConversionsQuals.hasVolatile()),
  6677. (!(*Ptr).isRestrictQualified() &&
  6678. VisibleTypeConversionsQuals.hasRestrict()));
  6679. }
  6680. }
  6681. // C++ [over.built]p6:
  6682. // For every cv-qualified or cv-unqualified object type T, there
  6683. // exist candidate operator functions of the form
  6684. //
  6685. // T& operator*(T*);
  6686. //
  6687. // C++ [over.built]p7:
  6688. // For every function type T that does not have cv-qualifiers or a
  6689. // ref-qualifier, there exist candidate operator functions of the form
  6690. // T& operator*(T*);
  6691. void addUnaryStarPointerOverloads() {
  6692. for (BuiltinCandidateTypeSet::iterator
  6693. Ptr = CandidateTypes[0].pointer_begin(),
  6694. PtrEnd = CandidateTypes[0].pointer_end();
  6695. Ptr != PtrEnd; ++Ptr) {
  6696. QualType ParamTy = *Ptr;
  6697. QualType PointeeTy = ParamTy->getPointeeType();
  6698. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  6699. continue;
  6700. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  6701. if (Proto->getTypeQuals() || Proto->getRefQualifier())
  6702. continue;
  6703. S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
  6704. &ParamTy, Args, CandidateSet);
  6705. }
  6706. }
  6707. // C++ [over.built]p9:
  6708. // For every promoted arithmetic type T, there exist candidate
  6709. // operator functions of the form
  6710. //
  6711. // T operator+(T);
  6712. // T operator-(T);
  6713. void addUnaryPlusOrMinusArithmeticOverloads() {
  6714. if (!HasArithmeticOrEnumeralCandidateType)
  6715. return;
  6716. for (unsigned Arith = FirstPromotedArithmeticType;
  6717. Arith < LastPromotedArithmeticType; ++Arith) {
  6718. QualType ArithTy = getArithmeticType(Arith);
  6719. S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
  6720. }
  6721. // Extension: We also add these operators for vector types.
  6722. for (BuiltinCandidateTypeSet::iterator
  6723. Vec = CandidateTypes[0].vector_begin(),
  6724. VecEnd = CandidateTypes[0].vector_end();
  6725. Vec != VecEnd; ++Vec) {
  6726. QualType VecTy = *Vec;
  6727. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6728. }
  6729. }
  6730. // C++ [over.built]p8:
  6731. // For every type T, there exist candidate operator functions of
  6732. // the form
  6733. //
  6734. // T* operator+(T*);
  6735. void addUnaryPlusPointerOverloads() {
  6736. for (BuiltinCandidateTypeSet::iterator
  6737. Ptr = CandidateTypes[0].pointer_begin(),
  6738. PtrEnd = CandidateTypes[0].pointer_end();
  6739. Ptr != PtrEnd; ++Ptr) {
  6740. QualType ParamTy = *Ptr;
  6741. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
  6742. }
  6743. }
  6744. // C++ [over.built]p10:
  6745. // For every promoted integral type T, there exist candidate
  6746. // operator functions of the form
  6747. //
  6748. // T operator~(T);
  6749. void addUnaryTildePromotedIntegralOverloads() {
  6750. if (!HasArithmeticOrEnumeralCandidateType)
  6751. return;
  6752. for (unsigned Int = FirstPromotedIntegralType;
  6753. Int < LastPromotedIntegralType; ++Int) {
  6754. QualType IntTy = getArithmeticType(Int);
  6755. S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
  6756. }
  6757. // Extension: We also add this operator for vector types.
  6758. for (BuiltinCandidateTypeSet::iterator
  6759. Vec = CandidateTypes[0].vector_begin(),
  6760. VecEnd = CandidateTypes[0].vector_end();
  6761. Vec != VecEnd; ++Vec) {
  6762. QualType VecTy = *Vec;
  6763. S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
  6764. }
  6765. }
  6766. // C++ [over.match.oper]p16:
  6767. // For every pointer to member type T, there exist candidate operator
  6768. // functions of the form
  6769. //
  6770. // bool operator==(T,T);
  6771. // bool operator!=(T,T);
  6772. void addEqualEqualOrNotEqualMemberPointerOverloads() {
  6773. /// Set of (canonical) types that we've already handled.
  6774. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6775. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6776. for (BuiltinCandidateTypeSet::iterator
  6777. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6778. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6779. MemPtr != MemPtrEnd;
  6780. ++MemPtr) {
  6781. // Don't add the same builtin candidate twice.
  6782. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  6783. continue;
  6784. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  6785. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6786. }
  6787. }
  6788. }
  6789. // C++ [over.built]p15:
  6790. //
  6791. // For every T, where T is an enumeration type, a pointer type, or
  6792. // std::nullptr_t, there exist candidate operator functions of the form
  6793. //
  6794. // bool operator<(T, T);
  6795. // bool operator>(T, T);
  6796. // bool operator<=(T, T);
  6797. // bool operator>=(T, T);
  6798. // bool operator==(T, T);
  6799. // bool operator!=(T, T);
  6800. void addRelationalPointerOrEnumeralOverloads() {
  6801. // C++ [over.match.oper]p3:
  6802. // [...]the built-in candidates include all of the candidate operator
  6803. // functions defined in 13.6 that, compared to the given operator, [...]
  6804. // do not have the same parameter-type-list as any non-template non-member
  6805. // candidate.
  6806. //
  6807. // Note that in practice, this only affects enumeration types because there
  6808. // aren't any built-in candidates of record type, and a user-defined operator
  6809. // must have an operand of record or enumeration type. Also, the only other
  6810. // overloaded operator with enumeration arguments, operator=,
  6811. // cannot be overloaded for enumeration types, so this is the only place
  6812. // where we must suppress candidates like this.
  6813. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  6814. UserDefinedBinaryOperators;
  6815. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6816. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  6817. CandidateTypes[ArgIdx].enumeration_end()) {
  6818. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  6819. CEnd = CandidateSet.end();
  6820. C != CEnd; ++C) {
  6821. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  6822. continue;
  6823. if (C->Function->isFunctionTemplateSpecialization())
  6824. continue;
  6825. QualType FirstParamType =
  6826. C->Function->getParamDecl(0)->getType().getUnqualifiedType();
  6827. QualType SecondParamType =
  6828. C->Function->getParamDecl(1)->getType().getUnqualifiedType();
  6829. // Skip if either parameter isn't of enumeral type.
  6830. if (!FirstParamType->isEnumeralType() ||
  6831. !SecondParamType->isEnumeralType())
  6832. continue;
  6833. // Add this operator to the set of known user-defined operators.
  6834. UserDefinedBinaryOperators.insert(
  6835. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  6836. S.Context.getCanonicalType(SecondParamType)));
  6837. }
  6838. }
  6839. }
  6840. /// Set of (canonical) types that we've already handled.
  6841. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6842. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  6843. for (BuiltinCandidateTypeSet::iterator
  6844. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  6845. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  6846. Ptr != PtrEnd; ++Ptr) {
  6847. // Don't add the same builtin candidate twice.
  6848. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6849. continue;
  6850. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6851. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6852. }
  6853. for (BuiltinCandidateTypeSet::iterator
  6854. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6855. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6856. Enum != EnumEnd; ++Enum) {
  6857. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  6858. // Don't add the same builtin candidate twice, or if a user defined
  6859. // candidate exists.
  6860. if (!AddedTypes.insert(CanonType).second ||
  6861. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  6862. CanonType)))
  6863. continue;
  6864. QualType ParamTypes[2] = { *Enum, *Enum };
  6865. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
  6866. }
  6867. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  6868. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  6869. if (AddedTypes.insert(NullPtrTy).second &&
  6870. !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
  6871. NullPtrTy))) {
  6872. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  6873. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
  6874. CandidateSet);
  6875. }
  6876. }
  6877. }
  6878. }
  6879. // C++ [over.built]p13:
  6880. //
  6881. // For every cv-qualified or cv-unqualified object type T
  6882. // there exist candidate operator functions of the form
  6883. //
  6884. // T* operator+(T*, ptrdiff_t);
  6885. // T& operator[](T*, ptrdiff_t); [BELOW]
  6886. // T* operator-(T*, ptrdiff_t);
  6887. // T* operator+(ptrdiff_t, T*);
  6888. // T& operator[](ptrdiff_t, T*); [BELOW]
  6889. //
  6890. // C++ [over.built]p14:
  6891. //
  6892. // For every T, where T is a pointer to object type, there
  6893. // exist candidate operator functions of the form
  6894. //
  6895. // ptrdiff_t operator-(T, T);
  6896. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  6897. /// Set of (canonical) types that we've already handled.
  6898. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6899. for (int Arg = 0; Arg < 2; ++Arg) {
  6900. QualType AsymetricParamTypes[2] = {
  6901. S.Context.getPointerDiffType(),
  6902. S.Context.getPointerDiffType(),
  6903. };
  6904. for (BuiltinCandidateTypeSet::iterator
  6905. Ptr = CandidateTypes[Arg].pointer_begin(),
  6906. PtrEnd = CandidateTypes[Arg].pointer_end();
  6907. Ptr != PtrEnd; ++Ptr) {
  6908. QualType PointeeTy = (*Ptr)->getPointeeType();
  6909. if (!PointeeTy->isObjectType())
  6910. continue;
  6911. AsymetricParamTypes[Arg] = *Ptr;
  6912. if (Arg == 0 || Op == OO_Plus) {
  6913. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  6914. // T* operator+(ptrdiff_t, T*);
  6915. S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
  6916. }
  6917. if (Op == OO_Minus) {
  6918. // ptrdiff_t operator-(T, T);
  6919. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  6920. continue;
  6921. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6922. S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
  6923. Args, CandidateSet);
  6924. }
  6925. }
  6926. }
  6927. }
  6928. // C++ [over.built]p12:
  6929. //
  6930. // For every pair of promoted arithmetic types L and R, there
  6931. // exist candidate operator functions of the form
  6932. //
  6933. // LR operator*(L, R);
  6934. // LR operator/(L, R);
  6935. // LR operator+(L, R);
  6936. // LR operator-(L, R);
  6937. // bool operator<(L, R);
  6938. // bool operator>(L, R);
  6939. // bool operator<=(L, R);
  6940. // bool operator>=(L, R);
  6941. // bool operator==(L, R);
  6942. // bool operator!=(L, R);
  6943. //
  6944. // where LR is the result of the usual arithmetic conversions
  6945. // between types L and R.
  6946. //
  6947. // C++ [over.built]p24:
  6948. //
  6949. // For every pair of promoted arithmetic types L and R, there exist
  6950. // candidate operator functions of the form
  6951. //
  6952. // LR operator?(bool, L, R);
  6953. //
  6954. // where LR is the result of the usual arithmetic conversions
  6955. // between types L and R.
  6956. // Our candidates ignore the first parameter.
  6957. void addGenericBinaryArithmeticOverloads(bool isComparison) {
  6958. if (!HasArithmeticOrEnumeralCandidateType)
  6959. return;
  6960. for (unsigned Left = FirstPromotedArithmeticType;
  6961. Left < LastPromotedArithmeticType; ++Left) {
  6962. for (unsigned Right = FirstPromotedArithmeticType;
  6963. Right < LastPromotedArithmeticType; ++Right) {
  6964. QualType LandR[2] = { getArithmeticType(Left),
  6965. getArithmeticType(Right) };
  6966. QualType Result =
  6967. isComparison ? S.Context.BoolTy
  6968. : getUsualArithmeticConversions(Left, Right);
  6969. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6970. }
  6971. }
  6972. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  6973. // conditional operator for vector types.
  6974. for (BuiltinCandidateTypeSet::iterator
  6975. Vec1 = CandidateTypes[0].vector_begin(),
  6976. Vec1End = CandidateTypes[0].vector_end();
  6977. Vec1 != Vec1End; ++Vec1) {
  6978. for (BuiltinCandidateTypeSet::iterator
  6979. Vec2 = CandidateTypes[1].vector_begin(),
  6980. Vec2End = CandidateTypes[1].vector_end();
  6981. Vec2 != Vec2End; ++Vec2) {
  6982. QualType LandR[2] = { *Vec1, *Vec2 };
  6983. QualType Result = S.Context.BoolTy;
  6984. if (!isComparison) {
  6985. if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
  6986. Result = *Vec1;
  6987. else
  6988. Result = *Vec2;
  6989. }
  6990. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  6991. }
  6992. }
  6993. }
  6994. // C++ [over.built]p17:
  6995. //
  6996. // For every pair of promoted integral types L and R, there
  6997. // exist candidate operator functions of the form
  6998. //
  6999. // LR operator%(L, R);
  7000. // LR operator&(L, R);
  7001. // LR operator^(L, R);
  7002. // LR operator|(L, R);
  7003. // L operator<<(L, R);
  7004. // L operator>>(L, R);
  7005. //
  7006. // where LR is the result of the usual arithmetic conversions
  7007. // between types L and R.
  7008. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  7009. if (!HasArithmeticOrEnumeralCandidateType)
  7010. return;
  7011. for (unsigned Left = FirstPromotedIntegralType;
  7012. Left < LastPromotedIntegralType; ++Left) {
  7013. for (unsigned Right = FirstPromotedIntegralType;
  7014. Right < LastPromotedIntegralType; ++Right) {
  7015. QualType LandR[2] = { getArithmeticType(Left),
  7016. getArithmeticType(Right) };
  7017. QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
  7018. ? LandR[0]
  7019. : getUsualArithmeticConversions(Left, Right);
  7020. S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
  7021. }
  7022. }
  7023. }
  7024. // C++ [over.built]p20:
  7025. //
  7026. // For every pair (T, VQ), where T is an enumeration or
  7027. // pointer to member type and VQ is either volatile or
  7028. // empty, there exist candidate operator functions of the form
  7029. //
  7030. // VQ T& operator=(VQ T&, T);
  7031. void addAssignmentMemberPointerOrEnumeralOverloads() {
  7032. /// Set of (canonical) types that we've already handled.
  7033. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7034. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7035. for (BuiltinCandidateTypeSet::iterator
  7036. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7037. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7038. Enum != EnumEnd; ++Enum) {
  7039. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7040. continue;
  7041. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
  7042. }
  7043. for (BuiltinCandidateTypeSet::iterator
  7044. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7045. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7046. MemPtr != MemPtrEnd; ++MemPtr) {
  7047. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7048. continue;
  7049. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
  7050. }
  7051. }
  7052. }
  7053. // C++ [over.built]p19:
  7054. //
  7055. // For every pair (T, VQ), where T is any type and VQ is either
  7056. // volatile or empty, there exist candidate operator functions
  7057. // of the form
  7058. //
  7059. // T*VQ& operator=(T*VQ&, T*);
  7060. //
  7061. // C++ [over.built]p21:
  7062. //
  7063. // For every pair (T, VQ), where T is a cv-qualified or
  7064. // cv-unqualified object type and VQ is either volatile or
  7065. // empty, there exist candidate operator functions of the form
  7066. //
  7067. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  7068. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  7069. void addAssignmentPointerOverloads(bool isEqualOp) {
  7070. /// Set of (canonical) types that we've already handled.
  7071. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7072. for (BuiltinCandidateTypeSet::iterator
  7073. Ptr = CandidateTypes[0].pointer_begin(),
  7074. PtrEnd = CandidateTypes[0].pointer_end();
  7075. Ptr != PtrEnd; ++Ptr) {
  7076. // If this is operator=, keep track of the builtin candidates we added.
  7077. if (isEqualOp)
  7078. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  7079. else if (!(*Ptr)->getPointeeType()->isObjectType())
  7080. continue;
  7081. // non-volatile version
  7082. QualType ParamTypes[2] = {
  7083. S.Context.getLValueReferenceType(*Ptr),
  7084. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  7085. };
  7086. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7087. /*IsAssigmentOperator=*/ isEqualOp);
  7088. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7089. VisibleTypeConversionsQuals.hasVolatile();
  7090. if (NeedVolatile) {
  7091. // volatile version
  7092. ParamTypes[0] =
  7093. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7094. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7095. /*IsAssigmentOperator=*/isEqualOp);
  7096. }
  7097. if (!(*Ptr).isRestrictQualified() &&
  7098. VisibleTypeConversionsQuals.hasRestrict()) {
  7099. // restrict version
  7100. ParamTypes[0]
  7101. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7102. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7103. /*IsAssigmentOperator=*/isEqualOp);
  7104. if (NeedVolatile) {
  7105. // volatile restrict version
  7106. ParamTypes[0]
  7107. = S.Context.getLValueReferenceType(
  7108. S.Context.getCVRQualifiedType(*Ptr,
  7109. (Qualifiers::Volatile |
  7110. Qualifiers::Restrict)));
  7111. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7112. /*IsAssigmentOperator=*/isEqualOp);
  7113. }
  7114. }
  7115. }
  7116. if (isEqualOp) {
  7117. for (BuiltinCandidateTypeSet::iterator
  7118. Ptr = CandidateTypes[1].pointer_begin(),
  7119. PtrEnd = CandidateTypes[1].pointer_end();
  7120. Ptr != PtrEnd; ++Ptr) {
  7121. // Make sure we don't add the same candidate twice.
  7122. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7123. continue;
  7124. QualType ParamTypes[2] = {
  7125. S.Context.getLValueReferenceType(*Ptr),
  7126. *Ptr,
  7127. };
  7128. // non-volatile version
  7129. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7130. /*IsAssigmentOperator=*/true);
  7131. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  7132. VisibleTypeConversionsQuals.hasVolatile();
  7133. if (NeedVolatile) {
  7134. // volatile version
  7135. ParamTypes[0] =
  7136. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  7137. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7138. /*IsAssigmentOperator=*/true);
  7139. }
  7140. if (!(*Ptr).isRestrictQualified() &&
  7141. VisibleTypeConversionsQuals.hasRestrict()) {
  7142. // restrict version
  7143. ParamTypes[0]
  7144. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  7145. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7146. /*IsAssigmentOperator=*/true);
  7147. if (NeedVolatile) {
  7148. // volatile restrict version
  7149. ParamTypes[0]
  7150. = S.Context.getLValueReferenceType(
  7151. S.Context.getCVRQualifiedType(*Ptr,
  7152. (Qualifiers::Volatile |
  7153. Qualifiers::Restrict)));
  7154. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7155. /*IsAssigmentOperator=*/true);
  7156. }
  7157. }
  7158. }
  7159. }
  7160. }
  7161. // C++ [over.built]p18:
  7162. //
  7163. // For every triple (L, VQ, R), where L is an arithmetic type,
  7164. // VQ is either volatile or empty, and R is a promoted
  7165. // arithmetic type, there exist candidate operator functions of
  7166. // the form
  7167. //
  7168. // VQ L& operator=(VQ L&, R);
  7169. // VQ L& operator*=(VQ L&, R);
  7170. // VQ L& operator/=(VQ L&, R);
  7171. // VQ L& operator+=(VQ L&, R);
  7172. // VQ L& operator-=(VQ L&, R);
  7173. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  7174. if (!HasArithmeticOrEnumeralCandidateType)
  7175. return;
  7176. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  7177. for (unsigned Right = FirstPromotedArithmeticType;
  7178. Right < LastPromotedArithmeticType; ++Right) {
  7179. QualType ParamTypes[2];
  7180. ParamTypes[1] = getArithmeticType(Right);
  7181. // Add this built-in operator as a candidate (VQ is empty).
  7182. ParamTypes[0] =
  7183. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7184. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7185. /*IsAssigmentOperator=*/isEqualOp);
  7186. // Add this built-in operator as a candidate (VQ is 'volatile').
  7187. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7188. ParamTypes[0] =
  7189. S.Context.getVolatileType(getArithmeticType(Left));
  7190. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7191. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7192. /*IsAssigmentOperator=*/isEqualOp);
  7193. }
  7194. }
  7195. }
  7196. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  7197. for (BuiltinCandidateTypeSet::iterator
  7198. Vec1 = CandidateTypes[0].vector_begin(),
  7199. Vec1End = CandidateTypes[0].vector_end();
  7200. Vec1 != Vec1End; ++Vec1) {
  7201. for (BuiltinCandidateTypeSet::iterator
  7202. Vec2 = CandidateTypes[1].vector_begin(),
  7203. Vec2End = CandidateTypes[1].vector_end();
  7204. Vec2 != Vec2End; ++Vec2) {
  7205. QualType ParamTypes[2];
  7206. ParamTypes[1] = *Vec2;
  7207. // Add this built-in operator as a candidate (VQ is empty).
  7208. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  7209. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7210. /*IsAssigmentOperator=*/isEqualOp);
  7211. // Add this built-in operator as a candidate (VQ is 'volatile').
  7212. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7213. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  7214. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7215. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
  7216. /*IsAssigmentOperator=*/isEqualOp);
  7217. }
  7218. }
  7219. }
  7220. }
  7221. // C++ [over.built]p22:
  7222. //
  7223. // For every triple (L, VQ, R), where L is an integral type, VQ
  7224. // is either volatile or empty, and R is a promoted integral
  7225. // type, there exist candidate operator functions of the form
  7226. //
  7227. // VQ L& operator%=(VQ L&, R);
  7228. // VQ L& operator<<=(VQ L&, R);
  7229. // VQ L& operator>>=(VQ L&, R);
  7230. // VQ L& operator&=(VQ L&, R);
  7231. // VQ L& operator^=(VQ L&, R);
  7232. // VQ L& operator|=(VQ L&, R);
  7233. void addAssignmentIntegralOverloads() {
  7234. if (!HasArithmeticOrEnumeralCandidateType)
  7235. return;
  7236. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  7237. for (unsigned Right = FirstPromotedIntegralType;
  7238. Right < LastPromotedIntegralType; ++Right) {
  7239. QualType ParamTypes[2];
  7240. ParamTypes[1] = getArithmeticType(Right);
  7241. // Add this built-in operator as a candidate (VQ is empty).
  7242. ParamTypes[0] =
  7243. S.Context.getLValueReferenceType(getArithmeticType(Left));
  7244. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7245. if (VisibleTypeConversionsQuals.hasVolatile()) {
  7246. // Add this built-in operator as a candidate (VQ is 'volatile').
  7247. ParamTypes[0] = getArithmeticType(Left);
  7248. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  7249. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  7250. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
  7251. }
  7252. }
  7253. }
  7254. }
  7255. // C++ [over.operator]p23:
  7256. //
  7257. // There also exist candidate operator functions of the form
  7258. //
  7259. // bool operator!(bool);
  7260. // bool operator&&(bool, bool);
  7261. // bool operator||(bool, bool);
  7262. void addExclaimOverload() {
  7263. QualType ParamTy = S.Context.BoolTy;
  7264. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
  7265. /*IsAssignmentOperator=*/false,
  7266. /*NumContextualBoolArguments=*/1);
  7267. }
  7268. void addAmpAmpOrPipePipeOverload() {
  7269. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  7270. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
  7271. /*IsAssignmentOperator=*/false,
  7272. /*NumContextualBoolArguments=*/2);
  7273. }
  7274. // C++ [over.built]p13:
  7275. //
  7276. // For every cv-qualified or cv-unqualified object type T there
  7277. // exist candidate operator functions of the form
  7278. //
  7279. // T* operator+(T*, ptrdiff_t); [ABOVE]
  7280. // T& operator[](T*, ptrdiff_t);
  7281. // T* operator-(T*, ptrdiff_t); [ABOVE]
  7282. // T* operator+(ptrdiff_t, T*); [ABOVE]
  7283. // T& operator[](ptrdiff_t, T*);
  7284. void addSubscriptOverloads() {
  7285. for (BuiltinCandidateTypeSet::iterator
  7286. Ptr = CandidateTypes[0].pointer_begin(),
  7287. PtrEnd = CandidateTypes[0].pointer_end();
  7288. Ptr != PtrEnd; ++Ptr) {
  7289. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  7290. QualType PointeeType = (*Ptr)->getPointeeType();
  7291. if (!PointeeType->isObjectType())
  7292. continue;
  7293. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7294. // T& operator[](T*, ptrdiff_t)
  7295. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7296. }
  7297. for (BuiltinCandidateTypeSet::iterator
  7298. Ptr = CandidateTypes[1].pointer_begin(),
  7299. PtrEnd = CandidateTypes[1].pointer_end();
  7300. Ptr != PtrEnd; ++Ptr) {
  7301. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  7302. QualType PointeeType = (*Ptr)->getPointeeType();
  7303. if (!PointeeType->isObjectType())
  7304. continue;
  7305. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  7306. // T& operator[](ptrdiff_t, T*)
  7307. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7308. }
  7309. }
  7310. // C++ [over.built]p11:
  7311. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  7312. // C1 is the same type as C2 or is a derived class of C2, T is an object
  7313. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  7314. // there exist candidate operator functions of the form
  7315. //
  7316. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  7317. //
  7318. // where CV12 is the union of CV1 and CV2.
  7319. void addArrowStarOverloads() {
  7320. for (BuiltinCandidateTypeSet::iterator
  7321. Ptr = CandidateTypes[0].pointer_begin(),
  7322. PtrEnd = CandidateTypes[0].pointer_end();
  7323. Ptr != PtrEnd; ++Ptr) {
  7324. QualType C1Ty = (*Ptr);
  7325. QualType C1;
  7326. QualifierCollector Q1;
  7327. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  7328. if (!isa<RecordType>(C1))
  7329. continue;
  7330. // heuristic to reduce number of builtin candidates in the set.
  7331. // Add volatile/restrict version only if there are conversions to a
  7332. // volatile/restrict type.
  7333. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  7334. continue;
  7335. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  7336. continue;
  7337. for (BuiltinCandidateTypeSet::iterator
  7338. MemPtr = CandidateTypes[1].member_pointer_begin(),
  7339. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  7340. MemPtr != MemPtrEnd; ++MemPtr) {
  7341. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  7342. QualType C2 = QualType(mptr->getClass(), 0);
  7343. C2 = C2.getUnqualifiedType();
  7344. if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
  7345. break;
  7346. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  7347. // build CV12 T&
  7348. QualType T = mptr->getPointeeType();
  7349. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  7350. T.isVolatileQualified())
  7351. continue;
  7352. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  7353. T.isRestrictQualified())
  7354. continue;
  7355. T = Q1.apply(S.Context, T);
  7356. QualType ResultTy = S.Context.getLValueReferenceType(T);
  7357. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
  7358. }
  7359. }
  7360. }
  7361. // Note that we don't consider the first argument, since it has been
  7362. // contextually converted to bool long ago. The candidates below are
  7363. // therefore added as binary.
  7364. //
  7365. // C++ [over.built]p25:
  7366. // For every type T, where T is a pointer, pointer-to-member, or scoped
  7367. // enumeration type, there exist candidate operator functions of the form
  7368. //
  7369. // T operator?(bool, T, T);
  7370. //
  7371. void addConditionalOperatorOverloads() {
  7372. /// Set of (canonical) types that we've already handled.
  7373. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  7374. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  7375. for (BuiltinCandidateTypeSet::iterator
  7376. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  7377. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  7378. Ptr != PtrEnd; ++Ptr) {
  7379. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
  7380. continue;
  7381. QualType ParamTypes[2] = { *Ptr, *Ptr };
  7382. S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
  7383. }
  7384. for (BuiltinCandidateTypeSet::iterator
  7385. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  7386. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  7387. MemPtr != MemPtrEnd; ++MemPtr) {
  7388. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
  7389. continue;
  7390. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  7391. S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
  7392. }
  7393. if (S.getLangOpts().CPlusPlus11) {
  7394. for (BuiltinCandidateTypeSet::iterator
  7395. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  7396. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  7397. Enum != EnumEnd; ++Enum) {
  7398. if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
  7399. continue;
  7400. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
  7401. continue;
  7402. QualType ParamTypes[2] = { *Enum, *Enum };
  7403. S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
  7404. }
  7405. }
  7406. }
  7407. }
  7408. };
  7409. } // end anonymous namespace
  7410. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  7411. /// operator overloads to the candidate set (C++ [over.built]), based
  7412. /// on the operator @p Op and the arguments given. For example, if the
  7413. /// operator is a binary '+', this routine might add "int
  7414. /// operator+(int, int)" to cover integer addition.
  7415. void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  7416. SourceLocation OpLoc,
  7417. ArrayRef<Expr *> Args,
  7418. OverloadCandidateSet &CandidateSet) {
  7419. // Find all of the types that the arguments can convert to, but only
  7420. // if the operator we're looking at has built-in operator candidates
  7421. // that make use of these types. Also record whether we encounter non-record
  7422. // candidate types or either arithmetic or enumeral candidate types.
  7423. Qualifiers VisibleTypeConversionsQuals;
  7424. VisibleTypeConversionsQuals.addConst();
  7425. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
  7426. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  7427. bool HasNonRecordCandidateType = false;
  7428. bool HasArithmeticOrEnumeralCandidateType = false;
  7429. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  7430. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  7431. CandidateTypes.emplace_back(*this);
  7432. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  7433. OpLoc,
  7434. true,
  7435. (Op == OO_Exclaim ||
  7436. Op == OO_AmpAmp ||
  7437. Op == OO_PipePipe),
  7438. VisibleTypeConversionsQuals);
  7439. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  7440. CandidateTypes[ArgIdx].hasNonRecordTypes();
  7441. HasArithmeticOrEnumeralCandidateType =
  7442. HasArithmeticOrEnumeralCandidateType ||
  7443. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  7444. }
  7445. // Exit early when no non-record types have been added to the candidate set
  7446. // for any of the arguments to the operator.
  7447. //
  7448. // We can't exit early for !, ||, or &&, since there we have always have
  7449. // 'bool' overloads.
  7450. if (!HasNonRecordCandidateType &&
  7451. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  7452. return;
  7453. // Setup an object to manage the common state for building overloads.
  7454. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
  7455. VisibleTypeConversionsQuals,
  7456. HasArithmeticOrEnumeralCandidateType,
  7457. CandidateTypes, CandidateSet);
  7458. // Dispatch over the operation to add in only those overloads which apply.
  7459. switch (Op) {
  7460. case OO_None:
  7461. case NUM_OVERLOADED_OPERATORS:
  7462. llvm_unreachable("Expected an overloaded operator");
  7463. case OO_New:
  7464. case OO_Delete:
  7465. case OO_Array_New:
  7466. case OO_Array_Delete:
  7467. case OO_Call:
  7468. llvm_unreachable(
  7469. "Special operators don't use AddBuiltinOperatorCandidates");
  7470. case OO_Comma:
  7471. case OO_Arrow:
  7472. // C++ [over.match.oper]p3:
  7473. // -- For the operator ',', the unary operator '&', or the
  7474. // operator '->', the built-in candidates set is empty.
  7475. break;
  7476. case OO_Plus: // '+' is either unary or binary
  7477. if (Args.size() == 1)
  7478. OpBuilder.addUnaryPlusPointerOverloads();
  7479. // Fall through.
  7480. case OO_Minus: // '-' is either unary or binary
  7481. if (Args.size() == 1) {
  7482. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  7483. } else {
  7484. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  7485. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7486. }
  7487. break;
  7488. case OO_Star: // '*' is either unary or binary
  7489. if (Args.size() == 1)
  7490. OpBuilder.addUnaryStarPointerOverloads();
  7491. else
  7492. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7493. break;
  7494. case OO_Slash:
  7495. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7496. break;
  7497. case OO_PlusPlus:
  7498. case OO_MinusMinus:
  7499. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  7500. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  7501. break;
  7502. case OO_EqualEqual:
  7503. case OO_ExclaimEqual:
  7504. OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
  7505. // Fall through.
  7506. case OO_Less:
  7507. case OO_Greater:
  7508. case OO_LessEqual:
  7509. case OO_GreaterEqual:
  7510. OpBuilder.addRelationalPointerOrEnumeralOverloads();
  7511. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
  7512. break;
  7513. case OO_Percent:
  7514. case OO_Caret:
  7515. case OO_Pipe:
  7516. case OO_LessLess:
  7517. case OO_GreaterGreater:
  7518. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7519. break;
  7520. case OO_Amp: // '&' is either unary or binary
  7521. if (Args.size() == 1)
  7522. // C++ [over.match.oper]p3:
  7523. // -- For the operator ',', the unary operator '&', or the
  7524. // operator '->', the built-in candidates set is empty.
  7525. break;
  7526. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  7527. break;
  7528. case OO_Tilde:
  7529. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  7530. break;
  7531. case OO_Equal:
  7532. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  7533. // Fall through.
  7534. case OO_PlusEqual:
  7535. case OO_MinusEqual:
  7536. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  7537. // Fall through.
  7538. case OO_StarEqual:
  7539. case OO_SlashEqual:
  7540. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  7541. break;
  7542. case OO_PercentEqual:
  7543. case OO_LessLessEqual:
  7544. case OO_GreaterGreaterEqual:
  7545. case OO_AmpEqual:
  7546. case OO_CaretEqual:
  7547. case OO_PipeEqual:
  7548. OpBuilder.addAssignmentIntegralOverloads();
  7549. break;
  7550. case OO_Exclaim:
  7551. OpBuilder.addExclaimOverload();
  7552. break;
  7553. case OO_AmpAmp:
  7554. case OO_PipePipe:
  7555. OpBuilder.addAmpAmpOrPipePipeOverload();
  7556. break;
  7557. case OO_Subscript:
  7558. OpBuilder.addSubscriptOverloads();
  7559. break;
  7560. case OO_ArrowStar:
  7561. OpBuilder.addArrowStarOverloads();
  7562. break;
  7563. case OO_Conditional:
  7564. OpBuilder.addConditionalOperatorOverloads();
  7565. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  7566. break;
  7567. }
  7568. }
  7569. /// \brief Add function candidates found via argument-dependent lookup
  7570. /// to the set of overloading candidates.
  7571. ///
  7572. /// This routine performs argument-dependent name lookup based on the
  7573. /// given function name (which may also be an operator name) and adds
  7574. /// all of the overload candidates found by ADL to the overload
  7575. /// candidate set (C++ [basic.lookup.argdep]).
  7576. void
  7577. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  7578. SourceLocation Loc,
  7579. ArrayRef<Expr *> Args,
  7580. TemplateArgumentListInfo *ExplicitTemplateArgs,
  7581. OverloadCandidateSet& CandidateSet,
  7582. bool PartialOverloading) {
  7583. ADLResult Fns;
  7584. // FIXME: This approach for uniquing ADL results (and removing
  7585. // redundant candidates from the set) relies on pointer-equality,
  7586. // which means we need to key off the canonical decl. However,
  7587. // always going back to the canonical decl might not get us the
  7588. // right set of default arguments. What default arguments are
  7589. // we supposed to consider on ADL candidates, anyway?
  7590. // FIXME: Pass in the explicit template arguments?
  7591. ArgumentDependentLookup(Name, Loc, Args, Fns);
  7592. // Erase all of the candidates we already knew about.
  7593. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  7594. CandEnd = CandidateSet.end();
  7595. Cand != CandEnd; ++Cand)
  7596. if (Cand->Function) {
  7597. Fns.erase(Cand->Function);
  7598. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  7599. Fns.erase(FunTmpl);
  7600. }
  7601. // For each of the ADL candidates we found, add it to the overload
  7602. // set.
  7603. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  7604. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  7605. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  7606. if (ExplicitTemplateArgs)
  7607. continue;
  7608. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
  7609. PartialOverloading);
  7610. } else
  7611. AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
  7612. FoundDecl, ExplicitTemplateArgs,
  7613. Args, CandidateSet, PartialOverloading);
  7614. }
  7615. }
  7616. /// isBetterOverloadCandidate - Determines whether the first overload
  7617. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  7618. bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
  7619. const OverloadCandidate &Cand2,
  7620. SourceLocation Loc,
  7621. bool UserDefinedConversion) {
  7622. // Define viable functions to be better candidates than non-viable
  7623. // functions.
  7624. if (!Cand2.Viable)
  7625. return Cand1.Viable;
  7626. else if (!Cand1.Viable)
  7627. return false;
  7628. // C++ [over.match.best]p1:
  7629. //
  7630. // -- if F is a static member function, ICS1(F) is defined such
  7631. // that ICS1(F) is neither better nor worse than ICS1(G) for
  7632. // any function G, and, symmetrically, ICS1(G) is neither
  7633. // better nor worse than ICS1(F).
  7634. unsigned StartArg = 0;
  7635. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  7636. StartArg = 1;
  7637. // C++ [over.match.best]p1:
  7638. // A viable function F1 is defined to be a better function than another
  7639. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  7640. // conversion sequence than ICSi(F2), and then...
  7641. unsigned NumArgs = Cand1.NumConversions;
  7642. assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
  7643. bool HasBetterConversion = false;
  7644. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  7645. switch (CompareImplicitConversionSequences(S,
  7646. Cand1.Conversions[ArgIdx],
  7647. Cand2.Conversions[ArgIdx])) {
  7648. case ImplicitConversionSequence::Better:
  7649. // Cand1 has a better conversion sequence.
  7650. HasBetterConversion = true;
  7651. break;
  7652. case ImplicitConversionSequence::Worse:
  7653. // Cand1 can't be better than Cand2.
  7654. return false;
  7655. case ImplicitConversionSequence::Indistinguishable:
  7656. // Do nothing.
  7657. break;
  7658. }
  7659. }
  7660. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  7661. // ICSj(F2), or, if not that,
  7662. if (HasBetterConversion)
  7663. return true;
  7664. // -- the context is an initialization by user-defined conversion
  7665. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  7666. // from the return type of F1 to the destination type (i.e.,
  7667. // the type of the entity being initialized) is a better
  7668. // conversion sequence than the standard conversion sequence
  7669. // from the return type of F2 to the destination type.
  7670. if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
  7671. isa<CXXConversionDecl>(Cand1.Function) &&
  7672. isa<CXXConversionDecl>(Cand2.Function)) {
  7673. // First check whether we prefer one of the conversion functions over the
  7674. // other. This only distinguishes the results in non-standard, extension
  7675. // cases such as the conversion from a lambda closure type to a function
  7676. // pointer or block.
  7677. ImplicitConversionSequence::CompareKind Result =
  7678. compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  7679. if (Result == ImplicitConversionSequence::Indistinguishable)
  7680. Result = CompareStandardConversionSequences(S,
  7681. Cand1.FinalConversion,
  7682. Cand2.FinalConversion);
  7683. if (Result != ImplicitConversionSequence::Indistinguishable)
  7684. return Result == ImplicitConversionSequence::Better;
  7685. // FIXME: Compare kind of reference binding if conversion functions
  7686. // convert to a reference type used in direct reference binding, per
  7687. // C++14 [over.match.best]p1 section 2 bullet 3.
  7688. }
  7689. // -- F1 is a non-template function and F2 is a function template
  7690. // specialization, or, if not that,
  7691. bool Cand1IsSpecialization = Cand1.Function &&
  7692. Cand1.Function->getPrimaryTemplate();
  7693. bool Cand2IsSpecialization = Cand2.Function &&
  7694. Cand2.Function->getPrimaryTemplate();
  7695. if (Cand1IsSpecialization != Cand2IsSpecialization)
  7696. return Cand2IsSpecialization;
  7697. // -- F1 and F2 are function template specializations, and the function
  7698. // template for F1 is more specialized than the template for F2
  7699. // according to the partial ordering rules described in 14.5.5.2, or,
  7700. // if not that,
  7701. if (Cand1IsSpecialization && Cand2IsSpecialization) {
  7702. if (FunctionTemplateDecl *BetterTemplate
  7703. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  7704. Cand2.Function->getPrimaryTemplate(),
  7705. Loc,
  7706. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  7707. : TPOC_Call,
  7708. Cand1.ExplicitCallArguments,
  7709. Cand2.ExplicitCallArguments))
  7710. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  7711. }
  7712. // Check for enable_if value-based overload resolution.
  7713. if (Cand1.Function && Cand2.Function &&
  7714. (Cand1.Function->hasAttr<EnableIfAttr>() ||
  7715. Cand2.Function->hasAttr<EnableIfAttr>())) {
  7716. // FIXME: The next several lines are just
  7717. // specific_attr_iterator<EnableIfAttr> but going in declaration order,
  7718. // instead of reverse order which is how they're stored in the AST.
  7719. AttrVec Cand1Attrs;
  7720. if (Cand1.Function->hasAttrs()) {
  7721. Cand1Attrs = Cand1.Function->getAttrs();
  7722. Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
  7723. IsNotEnableIfAttr),
  7724. Cand1Attrs.end());
  7725. std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
  7726. }
  7727. AttrVec Cand2Attrs;
  7728. if (Cand2.Function->hasAttrs()) {
  7729. Cand2Attrs = Cand2.Function->getAttrs();
  7730. Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
  7731. IsNotEnableIfAttr),
  7732. Cand2Attrs.end());
  7733. std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
  7734. }
  7735. // Candidate 1 is better if it has strictly more attributes and
  7736. // the common sequence is identical.
  7737. if (Cand1Attrs.size() <= Cand2Attrs.size())
  7738. return false;
  7739. auto Cand1I = Cand1Attrs.begin();
  7740. for (auto &Cand2A : Cand2Attrs) {
  7741. auto &Cand1A = *Cand1I++;
  7742. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  7743. cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
  7744. S.getASTContext(), true);
  7745. cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
  7746. S.getASTContext(), true);
  7747. if (Cand1ID != Cand2ID)
  7748. return false;
  7749. }
  7750. return true;
  7751. }
  7752. return false;
  7753. }
  7754. /// \brief Computes the best viable function (C++ 13.3.3)
  7755. /// within an overload candidate set.
  7756. ///
  7757. /// \param Loc The location of the function name (or operator symbol) for
  7758. /// which overload resolution occurs.
  7759. ///
  7760. /// \param Best If overload resolution was successful or found a deleted
  7761. /// function, \p Best points to the candidate function found.
  7762. ///
  7763. /// \returns The result of overload resolution.
  7764. OverloadingResult
  7765. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  7766. iterator &Best,
  7767. bool UserDefinedConversion) {
  7768. // HLSL Change Starts
  7769. // Function calls should use HLSL-style overloading. operator[] overloads
  7770. // (used for const support) aren't supported by the defined rules, so
  7771. // use C++ overload resolution for those.
  7772. if (S.getLangOpts().HLSL && !empty() && begin()->Function != nullptr &&
  7773. (begin()->Function->getDeclName() !=
  7774. S.Context.DeclarationNames.getCXXOperatorName(OO_Subscript))) {
  7775. return ::hlsl::GetBestViableFunction(S, Loc, *this, Best);
  7776. }
  7777. // HLSL Change Ends
  7778. // Find the best viable function.
  7779. Best = end();
  7780. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7781. if (Cand->Viable)
  7782. if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
  7783. UserDefinedConversion))
  7784. Best = Cand;
  7785. }
  7786. // If we didn't find any viable functions, abort.
  7787. if (Best == end())
  7788. return OR_No_Viable_Function;
  7789. // Make sure that this function is better than every other viable
  7790. // function. If not, we have an ambiguity.
  7791. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7792. if (Cand->Viable &&
  7793. Cand != Best &&
  7794. !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
  7795. UserDefinedConversion)) {
  7796. Best = end();
  7797. return OR_Ambiguous;
  7798. }
  7799. }
  7800. // Best is the best viable function.
  7801. if (Best->Function &&
  7802. (Best->Function->isDeleted() ||
  7803. S.isFunctionConsideredUnavailable(Best->Function)))
  7804. return OR_Deleted;
  7805. return OR_Success;
  7806. }
  7807. namespace {
  7808. enum OverloadCandidateKind {
  7809. oc_function,
  7810. oc_method,
  7811. oc_constructor,
  7812. oc_function_template,
  7813. oc_method_template,
  7814. oc_constructor_template,
  7815. oc_implicit_default_constructor,
  7816. oc_implicit_copy_constructor,
  7817. oc_implicit_move_constructor,
  7818. oc_implicit_copy_assignment,
  7819. oc_implicit_move_assignment,
  7820. oc_implicit_inherited_constructor
  7821. };
  7822. OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
  7823. FunctionDecl *Fn,
  7824. std::string &Description) {
  7825. bool isTemplate = false;
  7826. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  7827. isTemplate = true;
  7828. Description = S.getTemplateArgumentBindingsText(
  7829. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  7830. }
  7831. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7832. if (!Ctor->isImplicit())
  7833. return isTemplate ? oc_constructor_template : oc_constructor;
  7834. if (Ctor->getInheritedConstructor())
  7835. return oc_implicit_inherited_constructor;
  7836. if (Ctor->isDefaultConstructor())
  7837. return oc_implicit_default_constructor;
  7838. if (Ctor->isMoveConstructor())
  7839. return oc_implicit_move_constructor;
  7840. assert(Ctor->isCopyConstructor() &&
  7841. "unexpected sort of implicit constructor");
  7842. return oc_implicit_copy_constructor;
  7843. }
  7844. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  7845. if (S.getLangOpts().HLSL) return isTemplate ? oc_method_template : oc_method; // HLSL Change - all intrinsics are implicit, doesn't imply conversion
  7846. // This actually gets spelled 'candidate function' for now, but
  7847. // it doesn't hurt to split it out.
  7848. if (!Meth->isImplicit())
  7849. return isTemplate ? oc_method_template : oc_method;
  7850. if (Meth->isMoveAssignmentOperator())
  7851. return oc_implicit_move_assignment;
  7852. if (Meth->isCopyAssignmentOperator())
  7853. return oc_implicit_copy_assignment;
  7854. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  7855. return oc_method;
  7856. }
  7857. return isTemplate ? oc_function_template : oc_function;
  7858. }
  7859. void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
  7860. const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
  7861. if (!Ctor) return;
  7862. Ctor = Ctor->getInheritedConstructor();
  7863. if (!Ctor) return;
  7864. S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
  7865. }
  7866. } // end anonymous namespace
  7867. // Notes the location of an overload candidate.
  7868. void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
  7869. std::string FnDesc;
  7870. OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
  7871. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  7872. << (unsigned) K << FnDesc;
  7873. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  7874. Diag(Fn->getLocation(), PD);
  7875. MaybeEmitInheritedConstructorNote(*this, Fn);
  7876. }
  7877. // Notes the location of all overload candidates designated through
  7878. // OverloadedExpr
  7879. void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
  7880. assert(OverloadedExpr->getType() == Context.OverloadTy);
  7881. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  7882. OverloadExpr *OvlExpr = Ovl.Expression;
  7883. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  7884. IEnd = OvlExpr->decls_end();
  7885. I != IEnd; ++I) {
  7886. if (FunctionTemplateDecl *FunTmpl =
  7887. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  7888. NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
  7889. } else if (FunctionDecl *Fun
  7890. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  7891. NoteOverloadCandidate(Fun, DestType);
  7892. }
  7893. }
  7894. }
  7895. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  7896. /// "lead" diagnostic; it will be given two arguments, the source and
  7897. /// target types of the conversion.
  7898. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  7899. Sema &S,
  7900. SourceLocation CaretLoc,
  7901. const PartialDiagnostic &PDiag) const {
  7902. S.Diag(CaretLoc, PDiag)
  7903. << Ambiguous.getFromType() << Ambiguous.getToType();
  7904. // FIXME: The note limiting machinery is borrowed from
  7905. // OverloadCandidateSet::NoteCandidates; there's an opportunity for
  7906. // refactoring here.
  7907. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  7908. unsigned CandsShown = 0;
  7909. AmbiguousConversionSequence::const_iterator I, E;
  7910. for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  7911. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  7912. break;
  7913. ++CandsShown;
  7914. S.NoteOverloadCandidate(*I);
  7915. }
  7916. if (I != E)
  7917. S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
  7918. }
  7919. static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
  7920. unsigned I, const ImplicitConversionSequence &Conv, SourceLocation OpLoc) { // HLSL Change: add OpLoc and Conv
  7921. // const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  7922. assert(Conv.isBad());
  7923. assert(Cand->Function && "for now, candidate must be a function");
  7924. FunctionDecl *Fn = Cand->Function;
  7925. // There's a conversion slot for the object argument if this is a
  7926. // non-constructor method. Note that 'I' corresponds the
  7927. // conversion-slot index.
  7928. bool isObjectArgument = false;
  7929. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  7930. if (I == 0)
  7931. isObjectArgument = true;
  7932. else
  7933. I--;
  7934. }
  7935. std::string FnDesc;
  7936. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  7937. Expr *FromExpr = Conv.Bad.FromExpr;
  7938. QualType FromTy = Conv.Bad.getFromType();
  7939. QualType ToTy = Conv.Bad.getToType();
  7940. // HLSL Change: replace Fn->getLocation() in diagnostics with FnDiagLocation
  7941. // and avoid notes that try to point to built-in targets
  7942. SourceLocation FnDiagLocation = Fn->getLocation().isValid() ? Fn->getLocation() : OpLoc;
  7943. if (FromTy == S.Context.OverloadTy) {
  7944. assert(FromExpr && "overload set argument came from implicit argument?");
  7945. Expr *E = FromExpr->IgnoreParens();
  7946. if (isa<UnaryOperator>(E))
  7947. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  7948. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  7949. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_overload) // HLSL Change - FnDiagLocation
  7950. << (unsigned) FnKind << FnDesc
  7951. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7952. << ToTy << Name << I+1;
  7953. MaybeEmitInheritedConstructorNote(S, Fn);
  7954. return;
  7955. }
  7956. // Do some hand-waving analysis to see if the non-viability is due
  7957. // to a qualifier mismatch.
  7958. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  7959. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  7960. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  7961. CToTy = RT->getPointeeType();
  7962. else {
  7963. // TODO: detect and diagnose the full richness of const mismatches.
  7964. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  7965. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
  7966. CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
  7967. }
  7968. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  7969. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  7970. Qualifiers FromQs = CFromTy.getQualifiers();
  7971. Qualifiers ToQs = CToTy.getQualifiers();
  7972. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  7973. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_addrspace)
  7974. << (unsigned) FnKind << FnDesc
  7975. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7976. << FromTy
  7977. << FromQs.getAddressSpace() << ToQs.getAddressSpace()
  7978. << (unsigned) isObjectArgument << I+1;
  7979. MaybeEmitInheritedConstructorNote(S, Fn);
  7980. return;
  7981. }
  7982. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  7983. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_ownership)
  7984. << (unsigned) FnKind << FnDesc
  7985. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7986. << FromTy
  7987. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  7988. << (unsigned) isObjectArgument << I+1;
  7989. MaybeEmitInheritedConstructorNote(S, Fn);
  7990. return;
  7991. }
  7992. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  7993. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_gc)
  7994. << (unsigned) FnKind << FnDesc
  7995. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7996. << FromTy
  7997. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  7998. << (unsigned) isObjectArgument << I+1;
  7999. MaybeEmitInheritedConstructorNote(S, Fn);
  8000. return;
  8001. }
  8002. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  8003. assert(CVR && "unexpected qualifiers mismatch");
  8004. if (isObjectArgument) {
  8005. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr_this)
  8006. << (unsigned) FnKind << FnDesc
  8007. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8008. << FromTy << (CVR - 1);
  8009. } else {
  8010. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_cvr)
  8011. << (unsigned) FnKind << FnDesc
  8012. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8013. << FromTy << (CVR - 1) << I+1;
  8014. }
  8015. MaybeEmitInheritedConstructorNote(S, Fn);
  8016. return;
  8017. }
  8018. // Special diagnostic for failure to convert an initializer list, since
  8019. // telling the user that it has type void is not useful.
  8020. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  8021. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_list_argument)
  8022. << (unsigned) FnKind << FnDesc
  8023. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8024. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8025. MaybeEmitInheritedConstructorNote(S, Fn);
  8026. return;
  8027. }
  8028. // Diagnose references or pointers to incomplete types differently,
  8029. // since it's far from impossible that the incompleteness triggered
  8030. // the failure.
  8031. QualType TempFromTy = FromTy.getNonReferenceType();
  8032. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  8033. TempFromTy = PTy->getPointeeType();
  8034. if (TempFromTy->isIncompleteType()) {
  8035. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_conv_incomplete)
  8036. << (unsigned) FnKind << FnDesc
  8037. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8038. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8039. MaybeEmitInheritedConstructorNote(S, Fn);
  8040. return;
  8041. }
  8042. // Diagnose base -> derived pointer conversions.
  8043. unsigned BaseToDerivedConversion = 0;
  8044. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  8045. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  8046. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8047. FromPtrTy->getPointeeType()) &&
  8048. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  8049. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  8050. S.IsDerivedFrom(ToPtrTy->getPointeeType(),
  8051. FromPtrTy->getPointeeType()))
  8052. BaseToDerivedConversion = 1;
  8053. }
  8054. } else if (const ObjCObjectPointerType *FromPtrTy
  8055. = FromTy->getAs<ObjCObjectPointerType>()) {
  8056. if (const ObjCObjectPointerType *ToPtrTy
  8057. = ToTy->getAs<ObjCObjectPointerType>())
  8058. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  8059. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  8060. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  8061. FromPtrTy->getPointeeType()) &&
  8062. FromIface->isSuperClassOf(ToIface))
  8063. BaseToDerivedConversion = 2;
  8064. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  8065. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  8066. !FromTy->isIncompleteType() &&
  8067. !ToRefTy->getPointeeType()->isIncompleteType() &&
  8068. S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
  8069. BaseToDerivedConversion = 3;
  8070. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  8071. ToTy.getNonReferenceType().getCanonicalType() ==
  8072. FromTy.getNonReferenceType().getCanonicalType()) {
  8073. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_lvalue)
  8074. << (unsigned) FnKind << FnDesc
  8075. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8076. << (unsigned) isObjectArgument << I + 1;
  8077. MaybeEmitInheritedConstructorNote(S, Fn);
  8078. return;
  8079. }
  8080. }
  8081. if (BaseToDerivedConversion) {
  8082. S.Diag(FnDiagLocation,
  8083. diag::note_ovl_candidate_bad_base_to_derived_conv)
  8084. << (unsigned) FnKind << FnDesc
  8085. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8086. << (BaseToDerivedConversion - 1)
  8087. << FromTy << ToTy << I+1;
  8088. MaybeEmitInheritedConstructorNote(S, Fn);
  8089. return;
  8090. }
  8091. if (isa<ObjCObjectPointerType>(CFromTy) &&
  8092. isa<PointerType>(CToTy)) {
  8093. Qualifiers FromQs = CFromTy.getQualifiers();
  8094. Qualifiers ToQs = CToTy.getQualifiers();
  8095. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  8096. S.Diag(FnDiagLocation, diag::note_ovl_candidate_bad_arc_conv)
  8097. << (unsigned) FnKind << FnDesc
  8098. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8099. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  8100. MaybeEmitInheritedConstructorNote(S, Fn);
  8101. return;
  8102. }
  8103. }
  8104. // Emit the generic diagnostic and, optionally, add the hints to it.
  8105. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  8106. FDiag << (unsigned) FnKind << FnDesc
  8107. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  8108. << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
  8109. << (unsigned) (Cand->Fix.Kind);
  8110. // If we can fix the conversion, suggest the FixIts.
  8111. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  8112. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  8113. FDiag << *HI;
  8114. S.Diag(FnDiagLocation, FDiag);
  8115. MaybeEmitInheritedConstructorNote(S, Fn);
  8116. }
  8117. /// Additional arity mismatch diagnosis specific to a function overload
  8118. /// candidates. This is not covered by the more general DiagnoseArityMismatch()
  8119. /// over a candidate in any candidate set.
  8120. static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
  8121. unsigned NumArgs) {
  8122. FunctionDecl *Fn = Cand->Function;
  8123. unsigned MinParams = Fn->getMinRequiredArguments();
  8124. // With invalid overloaded operators, it's possible that we think we
  8125. // have an arity mismatch when in fact it looks like we have the
  8126. // right number of arguments, because only overloaded operators have
  8127. // the weird behavior of overloading member and non-member functions.
  8128. // Just don't report anything.
  8129. if (Fn->isInvalidDecl() &&
  8130. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  8131. return true;
  8132. if (NumArgs < MinParams) {
  8133. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  8134. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8135. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  8136. } else {
  8137. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  8138. (Cand->FailureKind == ovl_fail_bad_deduction &&
  8139. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  8140. }
  8141. return false;
  8142. }
  8143. /// General arity mismatch diagnosis over a candidate in a candidate set.
  8144. static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8145. assert(isa<FunctionDecl>(D) &&
  8146. "The templated declaration should at least be a function"
  8147. " when diagnosing bad template argument deduction due to too many"
  8148. " or too few arguments");
  8149. FunctionDecl *Fn = cast<FunctionDecl>(D);
  8150. // TODO: treat calls to a missing default constructor as a special case
  8151. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  8152. unsigned MinParams = Fn->getMinRequiredArguments();
  8153. // at least / at most / exactly
  8154. unsigned mode, modeCount;
  8155. if (NumFormalArgs < MinParams) {
  8156. if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
  8157. FnTy->isTemplateVariadic())
  8158. mode = 0; // "at least"
  8159. else
  8160. mode = 2; // "exactly"
  8161. modeCount = MinParams;
  8162. } else {
  8163. if (MinParams != FnTy->getNumParams())
  8164. mode = 1; // "at most"
  8165. else
  8166. mode = 2; // "exactly"
  8167. modeCount = FnTy->getNumParams();
  8168. }
  8169. std::string Description;
  8170. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
  8171. // HLSL Change Starts - fallback for built-ins
  8172. SourceLocation DiagLoc = Fn->getLocation();
  8173. if (DiagLoc.isInvalid()) DiagLoc = OpLoc;
  8174. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  8175. S.Diag(DiagLoc, diag::note_ovl_candidate_arity_one)
  8176. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8177. << mode << Fn->getParamDecl(0) << NumFormalArgs;
  8178. else
  8179. S.Diag(DiagLoc, diag::note_ovl_candidate_arity)
  8180. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
  8181. << mode << modeCount << NumFormalArgs;
  8182. // HLSL Change Ends
  8183. MaybeEmitInheritedConstructorNote(S, Fn);
  8184. }
  8185. /// Arity mismatch diagnosis specific to a function overload candidate.
  8186. static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  8187. unsigned NumFormalArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8188. if (!CheckArityMismatch(S, Cand, NumFormalArgs))
  8189. DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs, OpLoc);
  8190. }
  8191. static TemplateDecl *getDescribedTemplate(Decl *Templated) {
  8192. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
  8193. return FD->getDescribedFunctionTemplate();
  8194. else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
  8195. return RD->getDescribedClassTemplate();
  8196. llvm_unreachable("Unsupported: Getting the described template declaration"
  8197. " for bad deduction diagnosis");
  8198. }
  8199. /// Diagnose a failed template-argument deduction.
  8200. static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
  8201. DeductionFailureInfo &DeductionFailure,
  8202. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8203. TemplateParameter Param = DeductionFailure.getTemplateParameter();
  8204. NamedDecl *ParamD;
  8205. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  8206. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  8207. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  8208. switch (DeductionFailure.Result) {
  8209. case Sema::TDK_Success:
  8210. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8211. case Sema::TDK_Incomplete: {
  8212. assert(ParamD && "no parameter found for incomplete deduction result");
  8213. S.Diag(Templated->getLocation(),
  8214. diag::note_ovl_candidate_incomplete_deduction)
  8215. << ParamD->getDeclName();
  8216. MaybeEmitInheritedConstructorNote(S, Templated);
  8217. return;
  8218. }
  8219. case Sema::TDK_Underqualified: {
  8220. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  8221. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  8222. QualType Param = DeductionFailure.getFirstArg()->getAsType();
  8223. // Param will have been canonicalized, but it should just be a
  8224. // qualified version of ParamD, so move the qualifiers to that.
  8225. QualifierCollector Qs;
  8226. Qs.strip(Param);
  8227. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  8228. assert(S.Context.hasSameType(Param, NonCanonParam));
  8229. // Arg has also been canonicalized, but there's nothing we can do
  8230. // about that. It also doesn't matter as much, because it won't
  8231. // have any template parameters in it (because deduction isn't
  8232. // done on dependent types).
  8233. QualType Arg = DeductionFailure.getSecondArg()->getAsType();
  8234. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
  8235. << ParamD->getDeclName() << Arg << NonCanonParam;
  8236. MaybeEmitInheritedConstructorNote(S, Templated);
  8237. return;
  8238. }
  8239. case Sema::TDK_Inconsistent: {
  8240. assert(ParamD && "no parameter found for inconsistent deduction result");
  8241. int which = 0;
  8242. if (isa<TemplateTypeParmDecl>(ParamD))
  8243. which = 0;
  8244. else if (isa<NonTypeTemplateParmDecl>(ParamD))
  8245. which = 1;
  8246. else {
  8247. which = 2;
  8248. }
  8249. S.Diag(Templated->getLocation(),
  8250. diag::note_ovl_candidate_inconsistent_deduction)
  8251. << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
  8252. << *DeductionFailure.getSecondArg();
  8253. MaybeEmitInheritedConstructorNote(S, Templated);
  8254. return;
  8255. }
  8256. case Sema::TDK_InvalidExplicitArguments:
  8257. assert(ParamD && "no parameter found for invalid explicit arguments");
  8258. if (ParamD->getDeclName())
  8259. S.Diag(Templated->getLocation(),
  8260. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  8261. << ParamD->getDeclName();
  8262. else {
  8263. int index = 0;
  8264. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  8265. index = TTP->getIndex();
  8266. else if (NonTypeTemplateParmDecl *NTTP
  8267. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  8268. index = NTTP->getIndex();
  8269. else
  8270. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  8271. S.Diag(Templated->getLocation(),
  8272. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  8273. << (index + 1);
  8274. }
  8275. MaybeEmitInheritedConstructorNote(S, Templated);
  8276. return;
  8277. case Sema::TDK_TooManyArguments:
  8278. case Sema::TDK_TooFewArguments:
  8279. DiagnoseArityMismatch(S, Templated, NumArgs, OpLoc);
  8280. return;
  8281. case Sema::TDK_InstantiationDepth:
  8282. S.Diag(Templated->getLocation(),
  8283. diag::note_ovl_candidate_instantiation_depth);
  8284. MaybeEmitInheritedConstructorNote(S, Templated);
  8285. return;
  8286. case Sema::TDK_SubstitutionFailure: {
  8287. // Format the template argument list into the argument string.
  8288. SmallString<128> TemplateArgString;
  8289. if (TemplateArgumentList *Args =
  8290. DeductionFailure.getTemplateArgumentList()) {
  8291. TemplateArgString = " ";
  8292. TemplateArgString += S.getTemplateArgumentBindingsText(
  8293. getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
  8294. }
  8295. // If this candidate was disabled by enable_if, say so.
  8296. PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
  8297. if (PDiag && PDiag->second.getDiagID() ==
  8298. diag::err_typename_nested_not_found_enable_if) {
  8299. // FIXME: Use the source range of the condition, and the fully-qualified
  8300. // name of the enable_if template. These are both present in PDiag.
  8301. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  8302. << "'enable_if'" << TemplateArgString;
  8303. return;
  8304. }
  8305. // Format the SFINAE diagnostic into the argument string.
  8306. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  8307. // formatted message in another diagnostic.
  8308. SmallString<128> SFINAEArgString;
  8309. SourceRange R;
  8310. if (PDiag) {
  8311. SFINAEArgString = ": ";
  8312. R = SourceRange(PDiag->first, PDiag->first);
  8313. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  8314. }
  8315. S.Diag(Templated->getLocation(),
  8316. diag::note_ovl_candidate_substitution_failure)
  8317. << TemplateArgString << SFINAEArgString << R;
  8318. MaybeEmitInheritedConstructorNote(S, Templated);
  8319. return;
  8320. }
  8321. case Sema::TDK_FailedOverloadResolution: {
  8322. OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
  8323. S.Diag(Templated->getLocation(),
  8324. diag::note_ovl_candidate_failed_overload_resolution)
  8325. << R.Expression->getName();
  8326. return;
  8327. }
  8328. case Sema::TDK_NonDeducedMismatch: {
  8329. // FIXME: Provide a source location to indicate what we couldn't match.
  8330. TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
  8331. TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
  8332. if (FirstTA.getKind() == TemplateArgument::Template &&
  8333. SecondTA.getKind() == TemplateArgument::Template) {
  8334. TemplateName FirstTN = FirstTA.getAsTemplate();
  8335. TemplateName SecondTN = SecondTA.getAsTemplate();
  8336. if (FirstTN.getKind() == TemplateName::Template &&
  8337. SecondTN.getKind() == TemplateName::Template) {
  8338. if (FirstTN.getAsTemplateDecl()->getName() ==
  8339. SecondTN.getAsTemplateDecl()->getName()) {
  8340. // FIXME: This fixes a bad diagnostic where both templates are named
  8341. // the same. This particular case is a bit difficult since:
  8342. // 1) It is passed as a string to the diagnostic printer.
  8343. // 2) The diagnostic printer only attempts to find a better
  8344. // name for types, not decls.
  8345. // Ideally, this should folded into the diagnostic printer.
  8346. S.Diag(Templated->getLocation(),
  8347. diag::note_ovl_candidate_non_deduced_mismatch_qualified)
  8348. << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
  8349. return;
  8350. }
  8351. }
  8352. }
  8353. // HLSL Change Starts
  8354. // The implementation for template argument deducation does not yet provide
  8355. // FirstArg and SecondArg information for failure cases; ellide the note in
  8356. // this case.
  8357. if (FirstTA.isNull() || SecondTA.isNull()) return;
  8358. // HLSL Change Ends
  8359. // FIXME: For generic lambda parameters, check if the function is a lambda
  8360. // call operator, and if so, emit a prettier and more informative
  8361. // diagnostic that mentions 'auto' and lambda in addition to
  8362. // (or instead of?) the canonical template type parameters.
  8363. S.Diag(Templated->getLocation(),
  8364. diag::note_ovl_candidate_non_deduced_mismatch)
  8365. << FirstTA << SecondTA;
  8366. return;
  8367. }
  8368. // TODO: diagnose these individually, then kill off
  8369. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  8370. case Sema::TDK_MiscellaneousDeductionFailure:
  8371. S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
  8372. MaybeEmitInheritedConstructorNote(S, Templated);
  8373. return;
  8374. }
  8375. }
  8376. /// Diagnose a failed template-argument deduction, for function calls.
  8377. static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  8378. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change - add OpLoc
  8379. unsigned TDK = Cand->DeductionFailure.Result;
  8380. if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
  8381. if (CheckArityMismatch(S, Cand, NumArgs))
  8382. return;
  8383. }
  8384. DiagnoseBadDeduction(S, Cand->Function, // pattern
  8385. Cand->DeductionFailure, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8386. }
  8387. /// CUDA: diagnose an invalid call across targets.
  8388. static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  8389. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  8390. FunctionDecl *Callee = Cand->Function;
  8391. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  8392. CalleeTarget = S.IdentifyCUDATarget(Callee);
  8393. std::string FnDesc;
  8394. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
  8395. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  8396. << (unsigned)FnKind << CalleeTarget << CallerTarget;
  8397. // This could be an implicit constructor for which we could not infer the
  8398. // target due to a collsion. Diagnose that case.
  8399. CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
  8400. if (Meth != nullptr && Meth->isImplicit()) {
  8401. CXXRecordDecl *ParentClass = Meth->getParent();
  8402. Sema::CXXSpecialMember CSM;
  8403. switch (FnKind) {
  8404. default:
  8405. return;
  8406. case oc_implicit_default_constructor:
  8407. CSM = Sema::CXXDefaultConstructor;
  8408. break;
  8409. case oc_implicit_copy_constructor:
  8410. CSM = Sema::CXXCopyConstructor;
  8411. break;
  8412. case oc_implicit_move_constructor:
  8413. CSM = Sema::CXXMoveConstructor;
  8414. break;
  8415. case oc_implicit_copy_assignment:
  8416. CSM = Sema::CXXCopyAssignment;
  8417. break;
  8418. case oc_implicit_move_assignment:
  8419. CSM = Sema::CXXMoveAssignment;
  8420. break;
  8421. };
  8422. bool ConstRHS = false;
  8423. if (Meth->getNumParams()) {
  8424. if (const ReferenceType *RT =
  8425. Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
  8426. ConstRHS = RT->getPointeeType().isConstQualified();
  8427. }
  8428. }
  8429. S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
  8430. /* ConstRHS */ ConstRHS,
  8431. /* Diagnose */ true);
  8432. }
  8433. }
  8434. static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
  8435. FunctionDecl *Callee = Cand->Function;
  8436. EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
  8437. S.Diag(Callee->getLocation(),
  8438. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  8439. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  8440. }
  8441. /// Generates a 'note' diagnostic for an overload candidate. We've
  8442. /// already generated a primary error at the call site.
  8443. ///
  8444. /// It really does need to be a single diagnostic with its caret
  8445. /// pointed at the candidate declaration. Yes, this creates some
  8446. /// major challenges of technical writing. Yes, this makes pointing
  8447. /// out problems with specific arguments quite awkward. It's still
  8448. /// better than generating twenty screens of text for every failed
  8449. /// overload.
  8450. ///
  8451. /// It would be great to be able to express per-candidate problems
  8452. /// more richly for those diagnostic clients that cared, but we'd
  8453. /// still have to be just as careful with the default diagnostics.
  8454. static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  8455. unsigned NumArgs, SourceLocation OpLoc) { // HLSL Change: add OpLoc
  8456. FunctionDecl *Fn = Cand->Function;
  8457. // Note deleted candidates, but only if they're viable.
  8458. if (Cand->Viable && (Fn->isDeleted() ||
  8459. S.isFunctionConsideredUnavailable(Fn))) {
  8460. std::string FnDesc;
  8461. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  8462. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  8463. << FnKind << FnDesc
  8464. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  8465. MaybeEmitInheritedConstructorNote(S, Fn);
  8466. return;
  8467. }
  8468. // We don't really have anything else to say about viable candidates.
  8469. if (Cand->Viable) {
  8470. S.NoteOverloadCandidate(Fn);
  8471. return;
  8472. }
  8473. switch (Cand->FailureKind) {
  8474. case ovl_fail_too_many_arguments:
  8475. case ovl_fail_too_few_arguments:
  8476. return DiagnoseArityMismatch(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8477. case ovl_fail_bad_deduction:
  8478. return DiagnoseBadDeduction(S, Cand, NumArgs, OpLoc); // HLSL Change - add OpLoc
  8479. case ovl_fail_illegal_constructor: {
  8480. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
  8481. << (Fn->getPrimaryTemplate() ? 1 : 0);
  8482. MaybeEmitInheritedConstructorNote(S, Fn);
  8483. return;
  8484. }
  8485. case ovl_fail_trivial_conversion:
  8486. case ovl_fail_bad_final_conversion:
  8487. case ovl_fail_final_conversion_not_exact:
  8488. return S.NoteOverloadCandidate(Fn);
  8489. case ovl_fail_bad_conversion: {
  8490. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  8491. for (unsigned N = Cand->NumConversions; I != N; ++I)
  8492. if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8493. return DiagnoseBadConversion(S, Cand, I, Cand->Conversions[I], OpLoc); // HLSL Change: add OpLoc
  8494. if (Cand->OutConversions[I].isInitialized() && Cand->OutConversions[I].isBad()) // HLSL Change: check in and out, check out conversions
  8495. return DiagnoseBadConversion(S, Cand, I, Cand->OutConversions[I], OpLoc); // HLSL Change: add OpLoc
  8496. // FIXME: this currently happens when we're called from SemaInit
  8497. // when user-conversion overload fails. Figure out how to handle
  8498. // those conditions and diagnose them well.
  8499. return S.NoteOverloadCandidate(Fn);
  8500. }
  8501. case ovl_fail_bad_target:
  8502. return DiagnoseBadTarget(S, Cand);
  8503. case ovl_fail_enable_if:
  8504. return DiagnoseFailedEnableIfAttr(S, Cand);
  8505. }
  8506. }
  8507. static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  8508. // Desugar the type of the surrogate down to a function type,
  8509. // retaining as many typedefs as possible while still showing
  8510. // the function type (and, therefore, its parameter types).
  8511. QualType FnType = Cand->Surrogate->getConversionType();
  8512. bool isLValueReference = false;
  8513. bool isRValueReference = false;
  8514. bool isPointer = false;
  8515. if (const LValueReferenceType *FnTypeRef =
  8516. FnType->getAs<LValueReferenceType>()) {
  8517. FnType = FnTypeRef->getPointeeType();
  8518. isLValueReference = true;
  8519. } else if (const RValueReferenceType *FnTypeRef =
  8520. FnType->getAs<RValueReferenceType>()) {
  8521. FnType = FnTypeRef->getPointeeType();
  8522. isRValueReference = true;
  8523. }
  8524. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  8525. FnType = FnTypePtr->getPointeeType();
  8526. isPointer = true;
  8527. }
  8528. // Desugar down to a function type.
  8529. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  8530. // Reconstruct the pointer/reference as appropriate.
  8531. if (isPointer) FnType = S.Context.getPointerType(FnType);
  8532. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  8533. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  8534. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  8535. << FnType;
  8536. MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
  8537. }
  8538. static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
  8539. SourceLocation OpLoc,
  8540. OverloadCandidate *Cand) {
  8541. assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
  8542. std::string TypeStr("operator");
  8543. TypeStr += Opc;
  8544. TypeStr += "(";
  8545. TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
  8546. if (Cand->NumConversions == 1) {
  8547. TypeStr += ")";
  8548. S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
  8549. } else {
  8550. TypeStr += ", ";
  8551. TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
  8552. TypeStr += ")";
  8553. S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
  8554. }
  8555. }
  8556. static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  8557. OverloadCandidate *Cand) {
  8558. unsigned NoOperands = Cand->NumConversions;
  8559. for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
  8560. const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
  8561. if (ICS.isBad()) break; // all meaningless after first invalid
  8562. if (!ICS.isAmbiguous()) continue;
  8563. ICS.DiagnoseAmbiguousConversion(S, OpLoc,
  8564. S.PDiag(diag::note_ambiguous_type_conversion));
  8565. }
  8566. }
  8567. static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  8568. if (Cand->Function)
  8569. return Cand->Function->getLocation();
  8570. if (Cand->IsSurrogate)
  8571. return Cand->Surrogate->getLocation();
  8572. return SourceLocation();
  8573. }
  8574. static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
  8575. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  8576. case Sema::TDK_Success:
  8577. llvm_unreachable("TDK_success while diagnosing bad deduction");
  8578. case Sema::TDK_Invalid:
  8579. case Sema::TDK_Incomplete:
  8580. return 1;
  8581. case Sema::TDK_Underqualified:
  8582. case Sema::TDK_Inconsistent:
  8583. return 2;
  8584. case Sema::TDK_SubstitutionFailure:
  8585. case Sema::TDK_NonDeducedMismatch:
  8586. case Sema::TDK_MiscellaneousDeductionFailure:
  8587. return 3;
  8588. case Sema::TDK_InstantiationDepth:
  8589. case Sema::TDK_FailedOverloadResolution:
  8590. return 4;
  8591. case Sema::TDK_InvalidExplicitArguments:
  8592. return 5;
  8593. case Sema::TDK_TooManyArguments:
  8594. case Sema::TDK_TooFewArguments:
  8595. return 6;
  8596. }
  8597. llvm_unreachable("Unhandled deduction result");
  8598. }
  8599. namespace {
  8600. struct CompareOverloadCandidatesForDisplay {
  8601. Sema &S;
  8602. size_t NumArgs;
  8603. CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
  8604. : S(S), NumArgs(nArgs) {}
  8605. bool operator()(const OverloadCandidate *L,
  8606. const OverloadCandidate *R) {
  8607. // Fast-path this check.
  8608. if (L == R) return false;
  8609. // Order first by viability.
  8610. if (L->Viable) {
  8611. if (!R->Viable) return true;
  8612. // TODO: introduce a tri-valued comparison for overload
  8613. // candidates. Would be more worthwhile if we had a sort
  8614. // that could exploit it.
  8615. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
  8616. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
  8617. } else if (R->Viable)
  8618. return false;
  8619. assert(L->Viable == R->Viable);
  8620. // Criteria by which we can sort non-viable candidates:
  8621. if (!L->Viable) {
  8622. // 1. Arity mismatches come after other candidates.
  8623. if (L->FailureKind == ovl_fail_too_many_arguments ||
  8624. L->FailureKind == ovl_fail_too_few_arguments) {
  8625. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8626. R->FailureKind == ovl_fail_too_few_arguments) {
  8627. int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
  8628. int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
  8629. if (LDist == RDist) {
  8630. if (L->FailureKind == R->FailureKind)
  8631. // Sort non-surrogates before surrogates.
  8632. return !L->IsSurrogate && R->IsSurrogate;
  8633. // Sort candidates requiring fewer parameters than there were
  8634. // arguments given after candidates requiring more parameters
  8635. // than there were arguments given.
  8636. return L->FailureKind == ovl_fail_too_many_arguments;
  8637. }
  8638. return LDist < RDist;
  8639. }
  8640. return false;
  8641. }
  8642. if (R->FailureKind == ovl_fail_too_many_arguments ||
  8643. R->FailureKind == ovl_fail_too_few_arguments)
  8644. return true;
  8645. // 2. Bad conversions come first and are ordered by the number
  8646. // of bad conversions and quality of good conversions.
  8647. if (L->FailureKind == ovl_fail_bad_conversion) {
  8648. if (R->FailureKind != ovl_fail_bad_conversion)
  8649. return true;
  8650. // The conversion that can be fixed with a smaller number of changes,
  8651. // comes first.
  8652. unsigned numLFixes = L->Fix.NumConversionsFixed;
  8653. unsigned numRFixes = R->Fix.NumConversionsFixed;
  8654. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  8655. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  8656. if (numLFixes != numRFixes) {
  8657. return numLFixes < numRFixes;
  8658. }
  8659. // If there's any ordering between the defined conversions...
  8660. // FIXME: this might not be transitive.
  8661. assert(L->NumConversions == R->NumConversions);
  8662. int leftBetter = 0;
  8663. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  8664. for (unsigned E = L->NumConversions; I != E; ++I) {
  8665. switch (CompareImplicitConversionSequences(S,
  8666. L->Conversions[I],
  8667. R->Conversions[I])) {
  8668. case ImplicitConversionSequence::Better:
  8669. leftBetter++;
  8670. break;
  8671. case ImplicitConversionSequence::Worse:
  8672. leftBetter--;
  8673. break;
  8674. case ImplicitConversionSequence::Indistinguishable:
  8675. break;
  8676. }
  8677. }
  8678. if (leftBetter > 0) return true;
  8679. if (leftBetter < 0) return false;
  8680. } else if (R->FailureKind == ovl_fail_bad_conversion)
  8681. return false;
  8682. if (L->FailureKind == ovl_fail_bad_deduction) {
  8683. if (R->FailureKind != ovl_fail_bad_deduction)
  8684. return true;
  8685. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8686. return RankDeductionFailure(L->DeductionFailure)
  8687. < RankDeductionFailure(R->DeductionFailure);
  8688. } else if (R->FailureKind == ovl_fail_bad_deduction)
  8689. return false;
  8690. // TODO: others?
  8691. }
  8692. // Sort everything else by location.
  8693. SourceLocation LLoc = GetLocationForCandidate(L);
  8694. SourceLocation RLoc = GetLocationForCandidate(R);
  8695. // Put candidates without locations (e.g. builtins) at the end.
  8696. if (LLoc.isInvalid()) return false;
  8697. if (RLoc.isInvalid()) return true;
  8698. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8699. }
  8700. };
  8701. }
  8702. /// CompleteNonViableCandidate - Normally, overload resolution only
  8703. /// computes up to the first. Produces the FixIt set if possible.
  8704. static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  8705. ArrayRef<Expr *> Args) {
  8706. assert(!Cand->Viable);
  8707. // Don't do anything on failures other than bad conversion.
  8708. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  8709. // We only want the FixIts if all the arguments can be corrected.
  8710. bool Unfixable = false;
  8711. // Use a implicit copy initialization to check conversion fixes.
  8712. Cand->Fix.setConversionChecker(TryCopyInitialization);
  8713. // Skip forward to the first bad conversion.
  8714. unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
  8715. unsigned ConvCount = Cand->NumConversions;
  8716. while (true) {
  8717. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  8718. ConvIdx++;
  8719. if (Cand->Conversions[ConvIdx - 1].isInitialized() && Cand->Conversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8720. Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
  8721. break;
  8722. }
  8723. // HLSL Change Starts - check out conversions
  8724. if (Cand->OutConversions[ConvIdx - 1].isInitialized() && Cand->OutConversions[ConvIdx - 1].isBad()) { // HLSL Change - check defined
  8725. // Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); - consider suggesting a fix
  8726. Unfixable = true;
  8727. break;
  8728. }
  8729. // HLSL Change End
  8730. }
  8731. if (ConvIdx == ConvCount)
  8732. return;
  8733. assert(!Cand->Conversions[ConvIdx].isInitialized() &&
  8734. "remaining conversion is initialized?");
  8735. // FIXME: this should probably be preserved from the overload
  8736. // operation somehow.
  8737. bool SuppressUserConversions = false;
  8738. const FunctionProtoType* Proto;
  8739. unsigned ArgIdx = ConvIdx;
  8740. if (Cand->IsSurrogate) {
  8741. QualType ConvType
  8742. = Cand->Surrogate->getConversionType().getNonReferenceType();
  8743. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  8744. ConvType = ConvPtrType->getPointeeType();
  8745. Proto = ConvType->getAs<FunctionProtoType>();
  8746. ArgIdx--;
  8747. } else if (Cand->Function) {
  8748. Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
  8749. if (isa<CXXMethodDecl>(Cand->Function) &&
  8750. !isa<CXXConstructorDecl>(Cand->Function))
  8751. ArgIdx--;
  8752. } else {
  8753. // Builtin binary operator with a bad first conversion.
  8754. assert(ConvCount <= 3);
  8755. for (; ConvIdx != ConvCount && ConvIdx < 3; ++ConvIdx) // HLSL Change: explicit about ConvIdx < 3
  8756. Cand->Conversions[ConvIdx]
  8757. = TryCopyInitialization(S, Args[ConvIdx],
  8758. Cand->BuiltinTypes.ParamTypes[ConvIdx],
  8759. SuppressUserConversions,
  8760. /*InOverloadResolution*/ true,
  8761. /*AllowObjCWritebackConversion=*/
  8762. S.getLangOpts().ObjCAutoRefCount);
  8763. return;
  8764. }
  8765. // Fill in the rest of the conversions.
  8766. unsigned NumParams = Proto->getNumParams();
  8767. for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
  8768. if (ArgIdx < NumParams) {
  8769. Cand->Conversions[ConvIdx] = TryCopyInitialization(
  8770. S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
  8771. /*InOverloadResolution=*/true,
  8772. /*AllowObjCWritebackConversion=*/
  8773. S.getLangOpts().ObjCAutoRefCount);
  8774. // Store the FixIt in the candidate if it exists.
  8775. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  8776. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  8777. }
  8778. else
  8779. Cand->Conversions[ConvIdx].setEllipsis();
  8780. }
  8781. }
  8782. /// PrintOverloadCandidates - When overload resolution fails, prints
  8783. /// diagnostic messages containing the candidates in the candidate
  8784. /// set.
  8785. void OverloadCandidateSet::NoteCandidates(Sema &S,
  8786. OverloadCandidateDisplayKind OCD,
  8787. ArrayRef<Expr *> Args,
  8788. StringRef Opc,
  8789. SourceLocation OpLoc) {
  8790. // Sort the candidates by viability and position. Sorting directly would
  8791. // be prohibitive, so we make a set of pointers and sort those.
  8792. SmallVector<OverloadCandidate*, 32> Cands;
  8793. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  8794. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8795. if (Cand->Viable)
  8796. Cands.push_back(Cand);
  8797. else if (OCD == OCD_AllCandidates) {
  8798. CompleteNonViableCandidate(S, Cand, Args);
  8799. if (Cand->Function || Cand->IsSurrogate)
  8800. Cands.push_back(Cand);
  8801. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  8802. // want to list every possible builtin candidate.
  8803. }
  8804. }
  8805. std::sort(Cands.begin(), Cands.end(),
  8806. CompareOverloadCandidatesForDisplay(S, Args.size()));
  8807. bool ReportedAmbiguousConversions = false;
  8808. SmallVectorImpl<OverloadCandidate*>::iterator I, E;
  8809. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8810. unsigned CandsShown = 0;
  8811. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8812. OverloadCandidate *Cand = *I;
  8813. // Set an arbitrary limit on the number of candidate functions we'll spam
  8814. // the user with. FIXME: This limit should depend on details of the
  8815. // candidate list.
  8816. if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
  8817. break;
  8818. }
  8819. ++CandsShown;
  8820. if (Cand->Function)
  8821. NoteFunctionCandidate(S, Cand, Args.size(), OpLoc); // HLSL Change: add OpLoc
  8822. else if (Cand->IsSurrogate)
  8823. NoteSurrogateCandidate(S, Cand);
  8824. else {
  8825. assert(Cand->Viable &&
  8826. "Non-viable built-in candidates are not added to Cands.");
  8827. // Generally we only see ambiguities including viable builtin
  8828. // operators if overload resolution got screwed up by an
  8829. // ambiguous user-defined conversion.
  8830. //
  8831. // FIXME: It's quite possible for different conversions to see
  8832. // different ambiguities, though.
  8833. if (!ReportedAmbiguousConversions) {
  8834. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  8835. ReportedAmbiguousConversions = true;
  8836. }
  8837. // If this is a viable builtin, print it.
  8838. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  8839. }
  8840. }
  8841. if (I != E)
  8842. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  8843. }
  8844. static SourceLocation
  8845. GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
  8846. return Cand->Specialization ? Cand->Specialization->getLocation()
  8847. : SourceLocation();
  8848. }
  8849. namespace {
  8850. struct CompareTemplateSpecCandidatesForDisplay {
  8851. Sema &S;
  8852. CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
  8853. bool operator()(const TemplateSpecCandidate *L,
  8854. const TemplateSpecCandidate *R) {
  8855. // Fast-path this check.
  8856. if (L == R)
  8857. return false;
  8858. // Assuming that both candidates are not matches...
  8859. // Sort by the ranking of deduction failures.
  8860. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  8861. return RankDeductionFailure(L->DeductionFailure) <
  8862. RankDeductionFailure(R->DeductionFailure);
  8863. // Sort everything else by location.
  8864. SourceLocation LLoc = GetLocationForCandidate(L);
  8865. SourceLocation RLoc = GetLocationForCandidate(R);
  8866. // Put candidates without locations (e.g. builtins) at the end.
  8867. if (LLoc.isInvalid())
  8868. return false;
  8869. if (RLoc.isInvalid())
  8870. return true;
  8871. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  8872. }
  8873. };
  8874. }
  8875. /// Diagnose a template argument deduction failure.
  8876. /// We are treating these failures as overload failures due to bad
  8877. /// deductions.
  8878. void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
  8879. DiagnoseBadDeduction(S, Specialization, // pattern
  8880. DeductionFailure, /*NumArgs=*/0, SourceLocation()); // HLSL Change - add OpLoc
  8881. }
  8882. void TemplateSpecCandidateSet::destroyCandidates() {
  8883. for (iterator i = begin(), e = end(); i != e; ++i) {
  8884. i->DeductionFailure.Destroy();
  8885. }
  8886. }
  8887. void TemplateSpecCandidateSet::clear() {
  8888. destroyCandidates();
  8889. Candidates.clear();
  8890. }
  8891. /// NoteCandidates - When no template specialization match is found, prints
  8892. /// diagnostic messages containing the non-matching specializations that form
  8893. /// the candidate set.
  8894. /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
  8895. /// OCD == OCD_AllCandidates and Cand->Viable == false.
  8896. void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
  8897. // Sort the candidates by position (assuming no candidate is a match).
  8898. // Sorting directly would be prohibitive, so we make a set of pointers
  8899. // and sort those.
  8900. SmallVector<TemplateSpecCandidate *, 32> Cands;
  8901. Cands.reserve(size());
  8902. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  8903. if (Cand->Specialization)
  8904. Cands.push_back(Cand);
  8905. // Otherwise, this is a non-matching builtin candidate. We do not,
  8906. // in general, want to list every possible builtin candidate.
  8907. }
  8908. std::sort(Cands.begin(), Cands.end(),
  8909. CompareTemplateSpecCandidatesForDisplay(S));
  8910. // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
  8911. // for generalization purposes (?).
  8912. const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
  8913. SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
  8914. unsigned CandsShown = 0;
  8915. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  8916. TemplateSpecCandidate *Cand = *I;
  8917. // Set an arbitrary limit on the number of candidates we'll spam
  8918. // the user with. FIXME: This limit should depend on details of the
  8919. // candidate list.
  8920. if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
  8921. break;
  8922. ++CandsShown;
  8923. assert(Cand->Specialization &&
  8924. "Non-matching built-in candidates are not added to Cands.");
  8925. Cand->NoteDeductionFailure(S);
  8926. }
  8927. if (I != E)
  8928. S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
  8929. }
  8930. // [PossiblyAFunctionType] --> [Return]
  8931. // NonFunctionType --> NonFunctionType
  8932. // R (A) --> R(A)
  8933. // R (*)(A) --> R (A)
  8934. // R (&)(A) --> R (A)
  8935. // R (S::*)(A) --> R (A)
  8936. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  8937. QualType Ret = PossiblyAFunctionType;
  8938. if (const PointerType *ToTypePtr =
  8939. PossiblyAFunctionType->getAs<PointerType>())
  8940. Ret = ToTypePtr->getPointeeType();
  8941. else if (const ReferenceType *ToTypeRef =
  8942. PossiblyAFunctionType->getAs<ReferenceType>())
  8943. Ret = ToTypeRef->getPointeeType();
  8944. else if (const MemberPointerType *MemTypePtr =
  8945. PossiblyAFunctionType->getAs<MemberPointerType>())
  8946. Ret = MemTypePtr->getPointeeType();
  8947. Ret =
  8948. Context.getCanonicalType(Ret).getUnqualifiedType();
  8949. return Ret;
  8950. }
  8951. namespace {
  8952. // A helper class to help with address of function resolution
  8953. // - allows us to avoid passing around all those ugly parameters
  8954. class AddressOfFunctionResolver {
  8955. Sema& S;
  8956. Expr* SourceExpr;
  8957. const QualType& TargetType;
  8958. QualType TargetFunctionType; // Extracted function type from target type
  8959. bool Complain;
  8960. //DeclAccessPair& ResultFunctionAccessPair;
  8961. ASTContext& Context;
  8962. bool TargetTypeIsNonStaticMemberFunction;
  8963. bool FoundNonTemplateFunction;
  8964. bool StaticMemberFunctionFromBoundPointer;
  8965. OverloadExpr::FindResult OvlExprInfo;
  8966. OverloadExpr *OvlExpr;
  8967. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  8968. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  8969. TemplateSpecCandidateSet FailedCandidates;
  8970. public:
  8971. AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
  8972. const QualType &TargetType, bool Complain)
  8973. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  8974. Complain(Complain), Context(S.getASTContext()),
  8975. TargetTypeIsNonStaticMemberFunction(
  8976. !!TargetType->getAs<MemberPointerType>()),
  8977. FoundNonTemplateFunction(false),
  8978. StaticMemberFunctionFromBoundPointer(false),
  8979. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  8980. OvlExpr(OvlExprInfo.Expression),
  8981. FailedCandidates(OvlExpr->getNameLoc()) {
  8982. ExtractUnqualifiedFunctionTypeFromTargetType();
  8983. if (TargetFunctionType->isFunctionType()) {
  8984. if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
  8985. if (!UME->isImplicitAccess() &&
  8986. !S.ResolveSingleFunctionTemplateSpecialization(UME))
  8987. StaticMemberFunctionFromBoundPointer = true;
  8988. } else if (OvlExpr->hasExplicitTemplateArgs()) {
  8989. DeclAccessPair dap;
  8990. if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
  8991. OvlExpr, false, &dap)) {
  8992. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  8993. if (!Method->isStatic()) {
  8994. // If the target type is a non-function type and the function found
  8995. // is a non-static member function, pretend as if that was the
  8996. // target, it's the only possible type to end up with.
  8997. TargetTypeIsNonStaticMemberFunction = true;
  8998. // And skip adding the function if its not in the proper form.
  8999. // We'll diagnose this due to an empty set of functions.
  9000. if (!OvlExprInfo.HasFormOfMemberPointer)
  9001. return;
  9002. }
  9003. Matches.push_back(std::make_pair(dap, Fn));
  9004. }
  9005. return;
  9006. }
  9007. if (OvlExpr->hasExplicitTemplateArgs())
  9008. OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
  9009. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  9010. // C++ [over.over]p4:
  9011. // If more than one function is selected, [...]
  9012. if (Matches.size() > 1) {
  9013. if (FoundNonTemplateFunction)
  9014. EliminateAllTemplateMatches();
  9015. else
  9016. EliminateAllExceptMostSpecializedTemplate();
  9017. }
  9018. }
  9019. }
  9020. private:
  9021. bool isTargetTypeAFunction() const {
  9022. return TargetFunctionType->isFunctionType();
  9023. }
  9024. // [ToType] [Return]
  9025. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  9026. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  9027. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  9028. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  9029. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  9030. }
  9031. // return true if any matching specializations were found
  9032. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  9033. const DeclAccessPair& CurAccessFunPair) {
  9034. if (CXXMethodDecl *Method
  9035. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  9036. // Skip non-static function templates when converting to pointer, and
  9037. // static when converting to member pointer.
  9038. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9039. return false;
  9040. }
  9041. else if (TargetTypeIsNonStaticMemberFunction)
  9042. return false;
  9043. // C++ [over.over]p2:
  9044. // If the name is a function template, template argument deduction is
  9045. // done (14.8.2.2), and if the argument deduction succeeds, the
  9046. // resulting template argument list is used to generate a single
  9047. // function template specialization, which is added to the set of
  9048. // overloaded functions considered.
  9049. FunctionDecl *Specialization = nullptr;
  9050. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9051. if (Sema::TemplateDeductionResult Result
  9052. = S.DeduceTemplateArguments(FunctionTemplate,
  9053. &OvlExplicitTemplateArgs,
  9054. TargetFunctionType, Specialization,
  9055. Info, /*InOverloadResolution=*/true)) {
  9056. // Make a note of the failed deduction for diagnostics.
  9057. FailedCandidates.addCandidate()
  9058. .set(FunctionTemplate->getTemplatedDecl(),
  9059. MakeDeductionFailureInfo(Context, Result, Info));
  9060. return false;
  9061. }
  9062. // Template argument deduction ensures that we have an exact match or
  9063. // compatible pointer-to-function arguments that would be adjusted by ICS.
  9064. // This function template specicalization works.
  9065. Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
  9066. assert(S.isSameOrCompatibleFunctionType(
  9067. Context.getCanonicalType(Specialization->getType()),
  9068. Context.getCanonicalType(TargetFunctionType)));
  9069. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  9070. return true;
  9071. }
  9072. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  9073. const DeclAccessPair& CurAccessFunPair) {
  9074. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  9075. // Skip non-static functions when converting to pointer, and static
  9076. // when converting to member pointer.
  9077. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  9078. return false;
  9079. }
  9080. else if (TargetTypeIsNonStaticMemberFunction)
  9081. return false;
  9082. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  9083. if (S.getLangOpts().CUDA)
  9084. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  9085. if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
  9086. return false;
  9087. // If any candidate has a placeholder return type, trigger its deduction
  9088. // now.
  9089. if (S.getLangOpts().CPlusPlus14 &&
  9090. FunDecl->getReturnType()->isUndeducedType() &&
  9091. S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
  9092. return false;
  9093. QualType ResultTy;
  9094. if (Context.hasSameUnqualifiedType(TargetFunctionType,
  9095. FunDecl->getType()) ||
  9096. S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
  9097. ResultTy)) {
  9098. Matches.push_back(std::make_pair(CurAccessFunPair,
  9099. cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  9100. FoundNonTemplateFunction = true;
  9101. return true;
  9102. }
  9103. }
  9104. return false;
  9105. }
  9106. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  9107. bool Ret = false;
  9108. // If the overload expression doesn't have the form of a pointer to
  9109. // member, don't try to convert it to a pointer-to-member type.
  9110. if (IsInvalidFormOfPointerToMemberFunction())
  9111. return false;
  9112. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9113. E = OvlExpr->decls_end();
  9114. I != E; ++I) {
  9115. // Look through any using declarations to find the underlying function.
  9116. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  9117. // C++ [over.over]p3:
  9118. // Non-member functions and static member functions match
  9119. // targets of type "pointer-to-function" or "reference-to-function."
  9120. // Nonstatic member functions match targets of
  9121. // type "pointer-to-member-function."
  9122. // Note that according to DR 247, the containing class does not matter.
  9123. if (FunctionTemplateDecl *FunctionTemplate
  9124. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  9125. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  9126. Ret = true;
  9127. }
  9128. // If we have explicit template arguments supplied, skip non-templates.
  9129. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  9130. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  9131. Ret = true;
  9132. }
  9133. assert(Ret || Matches.empty());
  9134. return Ret;
  9135. }
  9136. void EliminateAllExceptMostSpecializedTemplate() {
  9137. // [...] and any given function template specialization F1 is
  9138. // eliminated if the set contains a second function template
  9139. // specialization whose function template is more specialized
  9140. // than the function template of F1 according to the partial
  9141. // ordering rules of 14.5.5.2.
  9142. // The algorithm specified above is quadratic. We instead use a
  9143. // two-pass algorithm (similar to the one used to identify the
  9144. // best viable function in an overload set) that identifies the
  9145. // best function template (if it exists).
  9146. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  9147. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  9148. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  9149. // TODO: It looks like FailedCandidates does not serve much purpose
  9150. // here, since the no_viable diagnostic has index 0.
  9151. UnresolvedSetIterator Result = S.getMostSpecialized(
  9152. MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
  9153. SourceExpr->getLocStart(), S.PDiag(),
  9154. S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
  9155. .second->getDeclName(),
  9156. S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
  9157. Complain, TargetFunctionType);
  9158. if (Result != MatchesCopy.end()) {
  9159. // Make it the first and only element
  9160. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  9161. Matches[0].second = cast<FunctionDecl>(*Result);
  9162. Matches.resize(1);
  9163. }
  9164. }
  9165. void EliminateAllTemplateMatches() {
  9166. // [...] any function template specializations in the set are
  9167. // eliminated if the set also contains a non-template function, [...]
  9168. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  9169. if (Matches[I].second->getPrimaryTemplate() == nullptr)
  9170. ++I;
  9171. else {
  9172. Matches[I] = Matches[--N];
  9173. Matches.set_size(N);
  9174. }
  9175. }
  9176. }
  9177. public:
  9178. void ComplainNoMatchesFound() const {
  9179. assert(Matches.empty());
  9180. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
  9181. << OvlExpr->getName() << TargetFunctionType
  9182. << OvlExpr->getSourceRange();
  9183. if (FailedCandidates.empty())
  9184. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9185. else {
  9186. // We have some deduction failure messages. Use them to diagnose
  9187. // the function templates, and diagnose the non-template candidates
  9188. // normally.
  9189. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  9190. IEnd = OvlExpr->decls_end();
  9191. I != IEnd; ++I)
  9192. if (FunctionDecl *Fun =
  9193. dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
  9194. S.NoteOverloadCandidate(Fun, TargetFunctionType);
  9195. FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
  9196. }
  9197. }
  9198. bool IsInvalidFormOfPointerToMemberFunction() const {
  9199. return TargetTypeIsNonStaticMemberFunction &&
  9200. !OvlExprInfo.HasFormOfMemberPointer;
  9201. }
  9202. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  9203. // TODO: Should we condition this on whether any functions might
  9204. // have matched, or is it more appropriate to do that in callers?
  9205. // TODO: a fixit wouldn't hurt.
  9206. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  9207. << TargetType << OvlExpr->getSourceRange();
  9208. }
  9209. bool IsStaticMemberFunctionFromBoundPointer() const {
  9210. return StaticMemberFunctionFromBoundPointer;
  9211. }
  9212. void ComplainIsStaticMemberFunctionFromBoundPointer() const {
  9213. S.Diag(OvlExpr->getLocStart(),
  9214. diag::err_invalid_form_pointer_member_function)
  9215. << OvlExpr->getSourceRange();
  9216. }
  9217. void ComplainOfInvalidConversion() const {
  9218. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
  9219. << OvlExpr->getName() << TargetType;
  9220. }
  9221. void ComplainMultipleMatchesFound() const {
  9222. assert(Matches.size() > 1);
  9223. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
  9224. << OvlExpr->getName()
  9225. << OvlExpr->getSourceRange();
  9226. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  9227. }
  9228. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  9229. int getNumMatches() const { return Matches.size(); }
  9230. FunctionDecl* getMatchingFunctionDecl() const {
  9231. if (Matches.size() != 1) return nullptr;
  9232. return Matches[0].second;
  9233. }
  9234. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  9235. if (Matches.size() != 1) return nullptr;
  9236. return &Matches[0].first;
  9237. }
  9238. };
  9239. }
  9240. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  9241. /// an overloaded function (C++ [over.over]), where @p From is an
  9242. /// expression with overloaded function type and @p ToType is the type
  9243. /// we're trying to resolve to. For example:
  9244. ///
  9245. /// @code
  9246. /// int f(double);
  9247. /// int f(int);
  9248. ///
  9249. /// int (*pfd)(double) = f; // selects f(double)
  9250. /// @endcode
  9251. ///
  9252. /// This routine returns the resulting FunctionDecl if it could be
  9253. /// resolved, and NULL otherwise. When @p Complain is true, this
  9254. /// routine will emit diagnostics if there is an error.
  9255. FunctionDecl *
  9256. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  9257. QualType TargetType,
  9258. bool Complain,
  9259. DeclAccessPair &FoundResult,
  9260. bool *pHadMultipleCandidates) {
  9261. assert(AddressOfExpr->getType() == Context.OverloadTy);
  9262. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  9263. Complain);
  9264. int NumMatches = Resolver.getNumMatches();
  9265. FunctionDecl *Fn = nullptr;
  9266. if (NumMatches == 0 && Complain) {
  9267. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  9268. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  9269. else
  9270. Resolver.ComplainNoMatchesFound();
  9271. }
  9272. else if (NumMatches > 1 && Complain)
  9273. Resolver.ComplainMultipleMatchesFound();
  9274. else if (NumMatches == 1) {
  9275. Fn = Resolver.getMatchingFunctionDecl();
  9276. assert(Fn);
  9277. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  9278. if (Complain) {
  9279. if (Resolver.IsStaticMemberFunctionFromBoundPointer())
  9280. Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
  9281. else
  9282. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  9283. }
  9284. }
  9285. if (pHadMultipleCandidates)
  9286. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  9287. return Fn;
  9288. }
  9289. /// \brief Given an expression that refers to an overloaded function, try to
  9290. /// resolve that overloaded function expression down to a single function.
  9291. ///
  9292. /// This routine can only resolve template-ids that refer to a single function
  9293. /// template, where that template-id refers to a single template whose template
  9294. /// arguments are either provided by the template-id or have defaults,
  9295. /// as described in C++0x [temp.arg.explicit]p3.
  9296. ///
  9297. /// If no template-ids are found, no diagnostics are emitted and NULL is
  9298. /// returned.
  9299. FunctionDecl *
  9300. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  9301. bool Complain,
  9302. DeclAccessPair *FoundResult) {
  9303. // C++ [over.over]p1:
  9304. // [...] [Note: any redundant set of parentheses surrounding the
  9305. // overloaded function name is ignored (5.1). ]
  9306. // C++ [over.over]p1:
  9307. // [...] The overloaded function name can be preceded by the &
  9308. // operator.
  9309. // If we didn't actually find any template-ids, we're done.
  9310. if (!ovl->hasExplicitTemplateArgs())
  9311. return nullptr;
  9312. TemplateArgumentListInfo ExplicitTemplateArgs;
  9313. ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
  9314. TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
  9315. // Look through all of the overloaded functions, searching for one
  9316. // whose type matches exactly.
  9317. FunctionDecl *Matched = nullptr;
  9318. for (UnresolvedSetIterator I = ovl->decls_begin(),
  9319. E = ovl->decls_end(); I != E; ++I) {
  9320. // C++0x [temp.arg.explicit]p3:
  9321. // [...] In contexts where deduction is done and fails, or in contexts
  9322. // where deduction is not done, if a template argument list is
  9323. // specified and it, along with any default template arguments,
  9324. // identifies a single function template specialization, then the
  9325. // template-id is an lvalue for the function template specialization.
  9326. FunctionTemplateDecl *FunctionTemplate
  9327. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  9328. // C++ [over.over]p2:
  9329. // If the name is a function template, template argument deduction is
  9330. // done (14.8.2.2), and if the argument deduction succeeds, the
  9331. // resulting template argument list is used to generate a single
  9332. // function template specialization, which is added to the set of
  9333. // overloaded functions considered.
  9334. FunctionDecl *Specialization = nullptr;
  9335. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9336. if (TemplateDeductionResult Result
  9337. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  9338. Specialization, Info,
  9339. /*InOverloadResolution=*/true)) {
  9340. // Make a note of the failed deduction for diagnostics.
  9341. // TODO: Actually use the failed-deduction info?
  9342. FailedCandidates.addCandidate()
  9343. .set(FunctionTemplate->getTemplatedDecl(),
  9344. MakeDeductionFailureInfo(Context, Result, Info));
  9345. continue;
  9346. }
  9347. assert(Specialization && "no specialization and no error?");
  9348. // Multiple matches; we can't resolve to a single declaration.
  9349. if (Matched) {
  9350. if (Complain) {
  9351. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  9352. << ovl->getName();
  9353. NoteAllOverloadCandidates(ovl);
  9354. }
  9355. return nullptr;
  9356. }
  9357. Matched = Specialization;
  9358. if (FoundResult) *FoundResult = I.getPair();
  9359. }
  9360. if (Matched && getLangOpts().CPlusPlus14 &&
  9361. Matched->getReturnType()->isUndeducedType() &&
  9362. DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
  9363. return nullptr;
  9364. return Matched;
  9365. }
  9366. // Resolve and fix an overloaded expression that can be resolved
  9367. // because it identifies a single function template specialization.
  9368. //
  9369. // Last three arguments should only be supplied if Complain = true
  9370. //
  9371. // Return true if it was logically possible to so resolve the
  9372. // expression, regardless of whether or not it succeeded. Always
  9373. // returns true if 'complain' is set.
  9374. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  9375. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  9376. bool complain, const SourceRange& OpRangeForComplaining,
  9377. QualType DestTypeForComplaining,
  9378. unsigned DiagIDForComplaining) {
  9379. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  9380. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  9381. DeclAccessPair found;
  9382. ExprResult SingleFunctionExpression;
  9383. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  9384. ovl.Expression, /*complain*/ false, &found)) {
  9385. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
  9386. SrcExpr = ExprError();
  9387. return true;
  9388. }
  9389. // It is only correct to resolve to an instance method if we're
  9390. // resolving a form that's permitted to be a pointer to member.
  9391. // Otherwise we'll end up making a bound member expression, which
  9392. // is illegal in all the contexts we resolve like this.
  9393. if (!ovl.HasFormOfMemberPointer &&
  9394. isa<CXXMethodDecl>(fn) &&
  9395. cast<CXXMethodDecl>(fn)->isInstance()) {
  9396. if (!complain) return false;
  9397. Diag(ovl.Expression->getExprLoc(),
  9398. diag::err_bound_member_function)
  9399. << 0 << ovl.Expression->getSourceRange();
  9400. // TODO: I believe we only end up here if there's a mix of
  9401. // static and non-static candidates (otherwise the expression
  9402. // would have 'bound member' type, not 'overload' type).
  9403. // Ideally we would note which candidate was chosen and why
  9404. // the static candidates were rejected.
  9405. SrcExpr = ExprError();
  9406. return true;
  9407. }
  9408. // Fix the expression to refer to 'fn'.
  9409. SingleFunctionExpression =
  9410. FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
  9411. // If desired, do function-to-pointer decay.
  9412. if (doFunctionPointerConverion) {
  9413. SingleFunctionExpression =
  9414. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
  9415. if (SingleFunctionExpression.isInvalid()) {
  9416. SrcExpr = ExprError();
  9417. return true;
  9418. }
  9419. }
  9420. }
  9421. if (!SingleFunctionExpression.isUsable()) {
  9422. if (complain) {
  9423. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  9424. << ovl.Expression->getName()
  9425. << DestTypeForComplaining
  9426. << OpRangeForComplaining
  9427. << ovl.Expression->getQualifierLoc().getSourceRange();
  9428. NoteAllOverloadCandidates(SrcExpr.get());
  9429. SrcExpr = ExprError();
  9430. return true;
  9431. }
  9432. return false;
  9433. }
  9434. SrcExpr = SingleFunctionExpression;
  9435. return true;
  9436. }
  9437. /// \brief Add a single candidate to the overload set.
  9438. static void AddOverloadedCallCandidate(Sema &S,
  9439. DeclAccessPair FoundDecl,
  9440. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9441. ArrayRef<Expr *> Args,
  9442. OverloadCandidateSet &CandidateSet,
  9443. bool PartialOverloading,
  9444. bool KnownValid) {
  9445. NamedDecl *Callee = FoundDecl.getDecl();
  9446. if (isa<UsingShadowDecl>(Callee))
  9447. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  9448. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  9449. if (ExplicitTemplateArgs) {
  9450. assert(!KnownValid && "Explicit template arguments?");
  9451. return;
  9452. }
  9453. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
  9454. /*SuppressUsedConversions=*/false,
  9455. PartialOverloading);
  9456. return;
  9457. }
  9458. if (FunctionTemplateDecl *FuncTemplate
  9459. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  9460. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  9461. ExplicitTemplateArgs, Args, CandidateSet,
  9462. /*SuppressUsedConversions=*/false,
  9463. PartialOverloading);
  9464. return;
  9465. }
  9466. assert(!KnownValid && "unhandled case in overloaded call candidate");
  9467. }
  9468. /// \brief Add the overload candidates named by callee and/or found by argument
  9469. /// dependent lookup to the given overload set.
  9470. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  9471. ArrayRef<Expr *> Args,
  9472. OverloadCandidateSet &CandidateSet,
  9473. bool PartialOverloading) {
  9474. #ifndef NDEBUG
  9475. // Verify that ArgumentDependentLookup is consistent with the rules
  9476. // in C++0x [basic.lookup.argdep]p3:
  9477. //
  9478. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9479. // and let Y be the lookup set produced by argument dependent
  9480. // lookup (defined as follows). If X contains
  9481. //
  9482. // -- a declaration of a class member, or
  9483. //
  9484. // -- a block-scope function declaration that is not a
  9485. // using-declaration, or
  9486. //
  9487. // -- a declaration that is neither a function or a function
  9488. // template
  9489. //
  9490. // then Y is empty.
  9491. if (ULE->requiresADL()) {
  9492. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9493. E = ULE->decls_end(); I != E; ++I) {
  9494. assert(!(*I)->getDeclContext()->isRecord());
  9495. assert(isa<UsingShadowDecl>(*I) ||
  9496. !(*I)->getDeclContext()->isFunctionOrMethod());
  9497. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  9498. }
  9499. }
  9500. #endif
  9501. // HLSL Change - allow ExternalSource the ability to add the overloads for a call.
  9502. if (ExternalSource &&
  9503. ExternalSource->AddOverloadedCallCandidates(ULE, Args, CandidateSet, PartialOverloading)) {
  9504. return;
  9505. }
  9506. // It would be nice to avoid this copy.
  9507. TemplateArgumentListInfo TABuffer;
  9508. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9509. if (ULE->hasExplicitTemplateArgs()) {
  9510. ULE->copyTemplateArgumentsInto(TABuffer);
  9511. ExplicitTemplateArgs = &TABuffer;
  9512. }
  9513. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  9514. E = ULE->decls_end(); I != E; ++I)
  9515. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  9516. CandidateSet, PartialOverloading,
  9517. /*KnownValid*/ true);
  9518. if (ULE->requiresADL())
  9519. AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
  9520. Args, ExplicitTemplateArgs,
  9521. CandidateSet, PartialOverloading);
  9522. }
  9523. /// Determine whether a declaration with the specified name could be moved into
  9524. /// a different namespace.
  9525. static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
  9526. switch (Name.getCXXOverloadedOperator()) {
  9527. case OO_New: case OO_Array_New:
  9528. case OO_Delete: case OO_Array_Delete:
  9529. return false;
  9530. default:
  9531. return true;
  9532. }
  9533. }
  9534. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  9535. /// template, where the non-dependent name was declared after the template
  9536. /// was defined. This is common in code written for a compilers which do not
  9537. /// correctly implement two-stage name lookup.
  9538. ///
  9539. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9540. static bool
  9541. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  9542. const CXXScopeSpec &SS, LookupResult &R,
  9543. OverloadCandidateSet::CandidateSetKind CSK,
  9544. TemplateArgumentListInfo *ExplicitTemplateArgs,
  9545. ArrayRef<Expr *> Args,
  9546. bool *DoDiagnoseEmptyLookup = nullptr) {
  9547. if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
  9548. return false;
  9549. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  9550. if (DC->isTransparentContext())
  9551. continue;
  9552. SemaRef.LookupQualifiedName(R, DC);
  9553. if (!R.empty()) {
  9554. R.suppressDiagnostics();
  9555. if (isa<CXXRecordDecl>(DC)) {
  9556. // Don't diagnose names we find in classes; we get much better
  9557. // diagnostics for these from DiagnoseEmptyLookup.
  9558. R.clear();
  9559. if (DoDiagnoseEmptyLookup)
  9560. *DoDiagnoseEmptyLookup = true;
  9561. return false;
  9562. }
  9563. OverloadCandidateSet Candidates(FnLoc, CSK);
  9564. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  9565. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  9566. ExplicitTemplateArgs, Args,
  9567. Candidates, false, /*KnownValid*/ false);
  9568. OverloadCandidateSet::iterator Best;
  9569. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  9570. // No viable functions. Don't bother the user with notes for functions
  9571. // which don't work and shouldn't be found anyway.
  9572. R.clear();
  9573. return false;
  9574. }
  9575. // Find the namespaces where ADL would have looked, and suggest
  9576. // declaring the function there instead.
  9577. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9578. Sema::AssociatedClassSet AssociatedClasses;
  9579. SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
  9580. AssociatedNamespaces,
  9581. AssociatedClasses);
  9582. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  9583. if (canBeDeclaredInNamespace(R.getLookupName())) {
  9584. DeclContext *Std = SemaRef.getStdNamespace();
  9585. for (Sema::AssociatedNamespaceSet::iterator
  9586. it = AssociatedNamespaces.begin(),
  9587. end = AssociatedNamespaces.end(); it != end; ++it) {
  9588. // Never suggest declaring a function within namespace 'std'.
  9589. if (Std && Std->Encloses(*it))
  9590. continue;
  9591. // Never suggest declaring a function within a namespace with a
  9592. // reserved name, like __gnu_cxx.
  9593. NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
  9594. if (NS &&
  9595. NS->getQualifiedNameAsString().find("__") != std::string::npos)
  9596. continue;
  9597. SuggestedNamespaces.insert(*it);
  9598. }
  9599. }
  9600. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  9601. << R.getLookupName();
  9602. if (SuggestedNamespaces.empty()) {
  9603. SemaRef.Diag(Best->Function->getLocation(),
  9604. diag::note_not_found_by_two_phase_lookup)
  9605. << R.getLookupName() << 0;
  9606. } else if (SuggestedNamespaces.size() == 1) {
  9607. SemaRef.Diag(Best->Function->getLocation(),
  9608. diag::note_not_found_by_two_phase_lookup)
  9609. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  9610. } else {
  9611. // FIXME: It would be useful to list the associated namespaces here,
  9612. // but the diagnostics infrastructure doesn't provide a way to produce
  9613. // a localized representation of a list of items.
  9614. SemaRef.Diag(Best->Function->getLocation(),
  9615. diag::note_not_found_by_two_phase_lookup)
  9616. << R.getLookupName() << 2;
  9617. }
  9618. // Try to recover by calling this function.
  9619. return true;
  9620. }
  9621. R.clear();
  9622. }
  9623. return false;
  9624. }
  9625. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  9626. /// template, where the non-dependent operator was declared after the template
  9627. /// was defined.
  9628. ///
  9629. /// Returns true if a viable candidate was found and a diagnostic was issued.
  9630. static bool
  9631. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  9632. SourceLocation OpLoc,
  9633. ArrayRef<Expr *> Args) {
  9634. DeclarationName OpName =
  9635. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  9636. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  9637. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  9638. OverloadCandidateSet::CSK_Operator,
  9639. /*ExplicitTemplateArgs=*/nullptr, Args);
  9640. }
  9641. namespace {
  9642. class BuildRecoveryCallExprRAII {
  9643. Sema &SemaRef;
  9644. public:
  9645. BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
  9646. assert(SemaRef.IsBuildingRecoveryCallExpr == false);
  9647. SemaRef.IsBuildingRecoveryCallExpr = true;
  9648. }
  9649. ~BuildRecoveryCallExprRAII() {
  9650. SemaRef.IsBuildingRecoveryCallExpr = false;
  9651. }
  9652. };
  9653. }
  9654. static std::unique_ptr<CorrectionCandidateCallback>
  9655. MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
  9656. bool HasTemplateArgs, bool AllowTypoCorrection) {
  9657. if (!AllowTypoCorrection)
  9658. return llvm::make_unique<NoTypoCorrectionCCC>();
  9659. return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
  9660. HasTemplateArgs, ME);
  9661. }
  9662. /// Attempts to recover from a call where no functions were found.
  9663. ///
  9664. /// Returns true if new candidates were found.
  9665. static ExprResult
  9666. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9667. UnresolvedLookupExpr *ULE,
  9668. SourceLocation LParenLoc,
  9669. MutableArrayRef<Expr *> Args,
  9670. SourceLocation RParenLoc,
  9671. bool EmptyLookup, bool AllowTypoCorrection) {
  9672. // Do not try to recover if it is already building a recovery call.
  9673. // This stops infinite loops for template instantiations like
  9674. //
  9675. // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
  9676. // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
  9677. //
  9678. if (SemaRef.IsBuildingRecoveryCallExpr)
  9679. return ExprError();
  9680. BuildRecoveryCallExprRAII RCE(SemaRef);
  9681. CXXScopeSpec SS;
  9682. SS.Adopt(ULE->getQualifierLoc());
  9683. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  9684. TemplateArgumentListInfo TABuffer;
  9685. TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
  9686. if (ULE->hasExplicitTemplateArgs()) {
  9687. ULE->copyTemplateArgumentsInto(TABuffer);
  9688. ExplicitTemplateArgs = &TABuffer;
  9689. }
  9690. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  9691. Sema::LookupOrdinaryName);
  9692. bool DoDiagnoseEmptyLookup = EmptyLookup;
  9693. if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
  9694. OverloadCandidateSet::CSK_Normal,
  9695. ExplicitTemplateArgs, Args,
  9696. &DoDiagnoseEmptyLookup) &&
  9697. (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
  9698. S, SS, R,
  9699. MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
  9700. ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
  9701. ExplicitTemplateArgs, Args)))
  9702. return ExprError();
  9703. assert(!R.empty() && "lookup results empty despite recovery");
  9704. // Build an implicit member call if appropriate. Just drop the
  9705. // casts and such from the call, we don't really care.
  9706. ExprResult NewFn = ExprError();
  9707. if ((*R.begin())->isCXXClassMember())
  9708. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  9709. R, ExplicitTemplateArgs);
  9710. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  9711. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  9712. ExplicitTemplateArgs);
  9713. else
  9714. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  9715. if (NewFn.isInvalid())
  9716. return ExprError();
  9717. // This shouldn't cause an infinite loop because we're giving it
  9718. // an expression with viable lookup results, which should never
  9719. // end up here.
  9720. return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
  9721. MultiExprArg(Args.data(), Args.size()),
  9722. RParenLoc);
  9723. }
  9724. /// \brief Constructs and populates an OverloadedCandidateSet from
  9725. /// the given function.
  9726. /// \returns true when an the ExprResult output parameter has been set.
  9727. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  9728. UnresolvedLookupExpr *ULE,
  9729. MultiExprArg Args,
  9730. SourceLocation RParenLoc,
  9731. OverloadCandidateSet *CandidateSet,
  9732. ExprResult *Result) {
  9733. #ifndef NDEBUG
  9734. if (ULE->requiresADL()) {
  9735. // To do ADL, we must have found an unqualified name.
  9736. // HLSL Change Begins
  9737. //
  9738. // We do want to allow argument-dependent lookup for intrinsic
  9739. // function names inside the "vk" namespace (which are by definition
  9740. // qualified names).
  9741. bool isVkNamespace =
  9742. ULE->getQualifier() &&
  9743. ULE->getQualifier()->getKind() == NestedNameSpecifier::Namespace &&
  9744. ULE->getQualifier()->getAsNamespace()->getName() == "vk";
  9745. assert((!ULE->getQualifier() || isVkNamespace) && "non-vk qualified name with ADL");
  9746. // HLSL Change Ends
  9747. // We don't perform ADL for implicit declarations of builtins.
  9748. // Verify that this was correctly set up.
  9749. FunctionDecl *F;
  9750. if (ULE->decls_begin() + 1 == ULE->decls_end() &&
  9751. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  9752. F->getBuiltinID() && F->isImplicit())
  9753. llvm_unreachable("performing ADL for builtin");
  9754. // We don't perform ADL in C.
  9755. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  9756. }
  9757. #endif
  9758. UnbridgedCastsSet UnbridgedCasts;
  9759. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
  9760. *Result = ExprError();
  9761. return true;
  9762. }
  9763. // Add the functions denoted by the callee to the set of candidate
  9764. // functions, including those from argument-dependent lookup.
  9765. AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
  9766. if (getLangOpts().MSVCCompat &&
  9767. CurContext->isDependentContext() && !isSFINAEContext() &&
  9768. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  9769. OverloadCandidateSet::iterator Best;
  9770. if (CandidateSet->empty() ||
  9771. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
  9772. OR_No_Viable_Function) {
  9773. // In Microsoft mode, if we are inside a template class member function then
  9774. // create a type dependent CallExpr. The goal is to postpone name lookup
  9775. // to instantiation time to be able to search into type dependent base
  9776. // classes.
  9777. CallExpr *CE = new (Context) CallExpr(
  9778. Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
  9779. CE->setTypeDependent(true);
  9780. *Result = CE;
  9781. return true;
  9782. }
  9783. }
  9784. if (CandidateSet->empty())
  9785. return false;
  9786. UnbridgedCasts.restore();
  9787. return false;
  9788. }
  9789. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  9790. /// the completed call expression. If overload resolution fails, emits
  9791. /// diagnostics and returns ExprError()
  9792. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  9793. UnresolvedLookupExpr *ULE,
  9794. SourceLocation LParenLoc,
  9795. MultiExprArg Args,
  9796. SourceLocation RParenLoc,
  9797. Expr *ExecConfig,
  9798. OverloadCandidateSet *CandidateSet,
  9799. OverloadCandidateSet::iterator *Best,
  9800. OverloadingResult OverloadResult,
  9801. bool AllowTypoCorrection) {
  9802. if (CandidateSet->empty())
  9803. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
  9804. RParenLoc, /*EmptyLookup=*/true,
  9805. AllowTypoCorrection);
  9806. switch (OverloadResult) {
  9807. case OR_Success: {
  9808. FunctionDecl *FDecl = (*Best)->Function;
  9809. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  9810. if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
  9811. return ExprError();
  9812. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9813. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9814. ExecConfig);
  9815. }
  9816. case OR_No_Viable_Function: {
  9817. // Try to recover by looking for viable functions which the user might
  9818. // have meant to call.
  9819. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  9820. Args, RParenLoc,
  9821. /*EmptyLookup=*/false,
  9822. AllowTypoCorrection);
  9823. if (!Recovery.isInvalid())
  9824. return Recovery;
  9825. SemaRef.Diag(Fn->getLocStart(),
  9826. diag::err_ovl_no_viable_function_in_call)
  9827. << ULE->getName() << Fn->getSourceRange();
  9828. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9829. break;
  9830. }
  9831. case OR_Ambiguous:
  9832. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
  9833. << ULE->getName() << Fn->getSourceRange();
  9834. CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
  9835. break;
  9836. case OR_Deleted: {
  9837. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
  9838. << (*Best)->Function->isDeleted()
  9839. << ULE->getName()
  9840. << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
  9841. << Fn->getSourceRange();
  9842. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
  9843. // We emitted an error for the unvailable/deleted function call but keep
  9844. // the call in the AST.
  9845. FunctionDecl *FDecl = (*Best)->Function;
  9846. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  9847. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
  9848. ExecConfig);
  9849. }
  9850. }
  9851. // Overload resolution failed.
  9852. return ExprError();
  9853. }
  9854. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  9855. /// (which eventually refers to the declaration Func) and the call
  9856. /// arguments Args/NumArgs, attempt to resolve the function call down
  9857. /// to a specific function. If overload resolution succeeds, returns
  9858. /// the call expression produced by overload resolution.
  9859. /// Otherwise, emits diagnostics and returns ExprError.
  9860. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  9861. UnresolvedLookupExpr *ULE,
  9862. SourceLocation LParenLoc,
  9863. MultiExprArg Args,
  9864. SourceLocation RParenLoc,
  9865. Expr *ExecConfig,
  9866. bool AllowTypoCorrection) {
  9867. OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
  9868. OverloadCandidateSet::CSK_Normal);
  9869. ExprResult result;
  9870. if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
  9871. &result))
  9872. return result;
  9873. OverloadCandidateSet::iterator Best;
  9874. OverloadingResult OverloadResult =
  9875. CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
  9876. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
  9877. RParenLoc, ExecConfig, &CandidateSet,
  9878. &Best, OverloadResult,
  9879. AllowTypoCorrection);
  9880. }
  9881. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  9882. return Functions.size() > 1 ||
  9883. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  9884. }
  9885. /// \brief Create a unary operation that may resolve to an overloaded
  9886. /// operator.
  9887. ///
  9888. /// \param OpLoc The location of the operator itself (e.g., '*').
  9889. ///
  9890. /// \param OpcIn The UnaryOperator::Opcode that describes this
  9891. /// operator.
  9892. ///
  9893. /// \param Fns The set of non-member functions that will be
  9894. /// considered by overload resolution. The caller needs to build this
  9895. /// set based on the context using, e.g.,
  9896. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  9897. /// set should not contain any member functions; those will be added
  9898. /// by CreateOverloadedUnaryOp().
  9899. ///
  9900. /// \param Input The input argument.
  9901. ExprResult
  9902. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
  9903. const UnresolvedSetImpl &Fns,
  9904. Expr *Input) {
  9905. UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
  9906. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  9907. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  9908. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  9909. // TODO: provide better source location info.
  9910. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  9911. if (checkPlaceholderForOverload(*this, Input))
  9912. return ExprError();
  9913. Expr *Args[2] = { Input, nullptr };
  9914. unsigned NumArgs = 1;
  9915. // For post-increment and post-decrement, add the implicit '0' as
  9916. // the second argument, so that we know this is a post-increment or
  9917. // post-decrement.
  9918. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  9919. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  9920. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  9921. SourceLocation());
  9922. NumArgs = 2;
  9923. }
  9924. ArrayRef<Expr *> ArgsArray(Args, NumArgs);
  9925. if (Input->isTypeDependent()) {
  9926. if (Fns.empty())
  9927. return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
  9928. VK_RValue, OK_Ordinary, OpLoc);
  9929. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  9930. UnresolvedLookupExpr *Fn
  9931. = UnresolvedLookupExpr::Create(Context, NamingClass,
  9932. NestedNameSpecifierLoc(), OpNameInfo,
  9933. /*ADL*/ true, IsOverloaded(Fns),
  9934. Fns.begin(), Fns.end());
  9935. return new (Context)
  9936. CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
  9937. VK_RValue, OpLoc, false);
  9938. }
  9939. // Build an empty overload set.
  9940. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  9941. // Add the candidates from the given function set.
  9942. AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
  9943. // Add operator candidates that are member functions.
  9944. AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9945. // Add candidates from ADL.
  9946. AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
  9947. /*ExplicitTemplateArgs*/nullptr,
  9948. CandidateSet);
  9949. // Add builtin operator candidates.
  9950. AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
  9951. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9952. // Perform overload resolution.
  9953. OverloadCandidateSet::iterator Best;
  9954. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  9955. case OR_Success: {
  9956. // We found a built-in operator or an overloaded operator.
  9957. FunctionDecl *FnDecl = Best->Function;
  9958. if (FnDecl) {
  9959. // We matched an overloaded operator. Build a call to that
  9960. // operator.
  9961. // Convert the arguments.
  9962. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  9963. CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
  9964. ExprResult InputRes =
  9965. PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
  9966. Best->FoundDecl, Method);
  9967. if (InputRes.isInvalid())
  9968. return ExprError();
  9969. Input = InputRes.get();
  9970. } else {
  9971. // Convert the arguments.
  9972. ExprResult InputInit
  9973. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  9974. Context,
  9975. FnDecl->getParamDecl(0)),
  9976. SourceLocation(),
  9977. Input);
  9978. if (InputInit.isInvalid())
  9979. return ExprError();
  9980. Input = InputInit.get();
  9981. }
  9982. // Build the actual expression node.
  9983. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
  9984. HadMultipleCandidates, OpLoc);
  9985. if (FnExpr.isInvalid())
  9986. return ExprError();
  9987. // Determine the result type.
  9988. QualType ResultTy = FnDecl->getReturnType();
  9989. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9990. ResultTy = ResultTy.getNonLValueExprType(Context);
  9991. Args[0] = Input;
  9992. CallExpr *TheCall =
  9993. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
  9994. ResultTy, VK, OpLoc, false);
  9995. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
  9996. return ExprError();
  9997. return MaybeBindToTemporary(TheCall);
  9998. } else {
  9999. // We matched a built-in operator. Convert the arguments, then
  10000. // break out so that we will build the appropriate built-in
  10001. // operator node.
  10002. ExprResult InputRes =
  10003. PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
  10004. Best->Conversions[0], AA_Passing);
  10005. if (InputRes.isInvalid())
  10006. return ExprError();
  10007. Input = InputRes.get();
  10008. break;
  10009. }
  10010. }
  10011. case OR_No_Viable_Function:
  10012. // This is an erroneous use of an operator which can be overloaded by
  10013. // a non-member function. Check for non-member operators which were
  10014. // defined too late to be candidates.
  10015. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
  10016. // FIXME: Recover by calling the found function.
  10017. return ExprError();
  10018. // No viable function; fall through to handling this as a
  10019. // built-in operator, which will produce an error message for us.
  10020. break;
  10021. case OR_Ambiguous:
  10022. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10023. << UnaryOperator::getOpcodeStr(Opc)
  10024. << Input->getType()
  10025. << Input->getSourceRange();
  10026. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
  10027. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10028. return ExprError();
  10029. case OR_Deleted:
  10030. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10031. << Best->Function->isDeleted()
  10032. << UnaryOperator::getOpcodeStr(Opc)
  10033. << getDeletedOrUnavailableSuffix(Best->Function)
  10034. << Input->getSourceRange();
  10035. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
  10036. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  10037. return ExprError();
  10038. }
  10039. // Either we found no viable overloaded operator or we matched a
  10040. // built-in operator. In either case, fall through to trying to
  10041. // build a built-in operation.
  10042. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10043. }
  10044. /// \brief Create a binary operation that may resolve to an overloaded
  10045. /// operator.
  10046. ///
  10047. /// \param OpLoc The location of the operator itself (e.g., '+').
  10048. ///
  10049. /// \param OpcIn The BinaryOperator::Opcode that describes this
  10050. /// operator.
  10051. ///
  10052. /// \param Fns The set of non-member functions that will be
  10053. /// considered by overload resolution. The caller needs to build this
  10054. /// set based on the context using, e.g.,
  10055. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  10056. /// set should not contain any member functions; those will be added
  10057. /// by CreateOverloadedBinOp().
  10058. ///
  10059. /// \param LHS Left-hand argument.
  10060. /// \param RHS Right-hand argument.
  10061. ExprResult
  10062. Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  10063. unsigned OpcIn,
  10064. const UnresolvedSetImpl &Fns,
  10065. Expr *LHS, Expr *RHS) {
  10066. Expr *Args[2] = { LHS, RHS };
  10067. LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
  10068. BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
  10069. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  10070. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  10071. // If either side is type-dependent, create an appropriate dependent
  10072. // expression.
  10073. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10074. if (Fns.empty()) {
  10075. // If there are no functions to store, just build a dependent
  10076. // BinaryOperator or CompoundAssignment.
  10077. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  10078. return new (Context) BinaryOperator(
  10079. Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
  10080. OpLoc, FPFeatures.fp_contract);
  10081. return new (Context) CompoundAssignOperator(
  10082. Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
  10083. Context.DependentTy, Context.DependentTy, OpLoc,
  10084. FPFeatures.fp_contract);
  10085. }
  10086. // FIXME: save results of ADL from here?
  10087. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10088. // TODO: provide better source location info in DNLoc component.
  10089. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  10090. UnresolvedLookupExpr *Fn
  10091. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10092. NestedNameSpecifierLoc(), OpNameInfo,
  10093. /*ADL*/ true, IsOverloaded(Fns),
  10094. Fns.begin(), Fns.end());
  10095. return new (Context)
  10096. CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
  10097. VK_RValue, OpLoc, FPFeatures.fp_contract);
  10098. }
  10099. // Always do placeholder-like conversions on the RHS.
  10100. if (checkPlaceholderForOverload(*this, Args[1]))
  10101. return ExprError();
  10102. // Do placeholder-like conversion on the LHS; note that we should
  10103. // not get here with a PseudoObject LHS.
  10104. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  10105. if (checkPlaceholderForOverload(*this, Args[0]))
  10106. return ExprError();
  10107. // If this is the assignment operator, we only perform overload resolution
  10108. // if the left-hand side is a class or enumeration type. This is actually
  10109. // a hack. The standard requires that we do overload resolution between the
  10110. // various built-in candidates, but as DR507 points out, this can lead to
  10111. // problems. So we do it this way, which pretty much follows what GCC does.
  10112. // Note that we go the traditional code path for compound assignment forms.
  10113. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  10114. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10115. // If this is the .* operator, which is not overloadable, just
  10116. // create a built-in binary operator.
  10117. if (Opc == BO_PtrMemD)
  10118. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10119. // Build an empty overload set.
  10120. OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
  10121. // Add the candidates from the given function set.
  10122. AddFunctionCandidates(Fns, Args, CandidateSet);
  10123. // Add operator candidates that are member functions.
  10124. AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10125. // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
  10126. // performed for an assignment operator (nor for operator[] nor operator->,
  10127. // which don't get here).
  10128. if (Opc != BO_Assign)
  10129. AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
  10130. /*ExplicitTemplateArgs*/ nullptr,
  10131. CandidateSet);
  10132. // Add builtin operator candidates.
  10133. AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
  10134. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10135. // Perform overload resolution.
  10136. OverloadCandidateSet::iterator Best;
  10137. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10138. case OR_Success: {
  10139. // We found a built-in operator or an overloaded operator.
  10140. FunctionDecl *FnDecl = Best->Function;
  10141. if (FnDecl) {
  10142. // We matched an overloaded operator. Build a call to that
  10143. // operator.
  10144. // Convert the arguments.
  10145. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  10146. // Best->Access is only meaningful for class members.
  10147. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  10148. ExprResult Arg1 =
  10149. PerformCopyInitialization(
  10150. InitializedEntity::InitializeParameter(Context,
  10151. FnDecl->getParamDecl(0)),
  10152. SourceLocation(), Args[1]);
  10153. if (Arg1.isInvalid())
  10154. return ExprError();
  10155. ExprResult Arg0 =
  10156. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10157. Best->FoundDecl, Method);
  10158. if (Arg0.isInvalid())
  10159. return ExprError();
  10160. Args[0] = Arg0.getAs<Expr>();
  10161. Args[1] = RHS = Arg1.getAs<Expr>();
  10162. } else {
  10163. // Convert the arguments.
  10164. ExprResult Arg0 = PerformCopyInitialization(
  10165. InitializedEntity::InitializeParameter(Context,
  10166. FnDecl->getParamDecl(0)),
  10167. SourceLocation(), Args[0]);
  10168. if (Arg0.isInvalid())
  10169. return ExprError();
  10170. ExprResult Arg1 =
  10171. PerformCopyInitialization(
  10172. InitializedEntity::InitializeParameter(Context,
  10173. FnDecl->getParamDecl(1)),
  10174. SourceLocation(), Args[1]);
  10175. if (Arg1.isInvalid())
  10176. return ExprError();
  10177. Args[0] = LHS = Arg0.getAs<Expr>();
  10178. Args[1] = RHS = Arg1.getAs<Expr>();
  10179. }
  10180. // Build the actual expression node.
  10181. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10182. Best->FoundDecl,
  10183. HadMultipleCandidates, OpLoc);
  10184. if (FnExpr.isInvalid())
  10185. return ExprError();
  10186. // Determine the result type.
  10187. QualType ResultTy = FnDecl->getReturnType();
  10188. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10189. ResultTy = ResultTy.getNonLValueExprType(Context);
  10190. CXXOperatorCallExpr *TheCall =
  10191. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
  10192. Args, ResultTy, VK, OpLoc,
  10193. FPFeatures.fp_contract);
  10194. if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
  10195. FnDecl))
  10196. return ExprError();
  10197. ArrayRef<const Expr *> ArgsArray(Args, 2);
  10198. // Cut off the implicit 'this'.
  10199. if (isa<CXXMethodDecl>(FnDecl))
  10200. ArgsArray = ArgsArray.slice(1);
  10201. // Check for a self move.
  10202. if (Op == OO_Equal)
  10203. DiagnoseSelfMove(Args[0], Args[1], OpLoc);
  10204. checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
  10205. TheCall->getSourceRange(), VariadicDoesNotApply);
  10206. return MaybeBindToTemporary(TheCall);
  10207. } else {
  10208. // We matched a built-in operator. Convert the arguments, then
  10209. // break out so that we will build the appropriate built-in
  10210. // operator node.
  10211. ExprResult ArgsRes0 =
  10212. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10213. Best->Conversions[0], AA_Passing);
  10214. if (ArgsRes0.isInvalid())
  10215. return ExprError();
  10216. Args[0] = ArgsRes0.get();
  10217. ExprResult ArgsRes1 =
  10218. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10219. Best->Conversions[1], AA_Passing);
  10220. if (ArgsRes1.isInvalid())
  10221. return ExprError();
  10222. Args[1] = ArgsRes1.get();
  10223. break;
  10224. }
  10225. }
  10226. case OR_No_Viable_Function: {
  10227. // C++ [over.match.oper]p9:
  10228. // If the operator is the operator , [...] and there are no
  10229. // viable functions, then the operator is assumed to be the
  10230. // built-in operator and interpreted according to clause 5.
  10231. if (Opc == BO_Comma)
  10232. break;
  10233. // HLSL Change Starts
  10234. if (getLangOpts().HLSL)
  10235. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10236. // HLSL Change Ends
  10237. // For class as left operand for assignment or compound assigment
  10238. // operator do not fall through to handling in built-in, but report that
  10239. // no overloaded assignment operator found
  10240. ExprResult Result = ExprError();
  10241. if (Args[0]->getType()->isRecordType() &&
  10242. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  10243. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10244. << BinaryOperator::getOpcodeStr(Opc)
  10245. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10246. if (Args[0]->getType()->isIncompleteType()) {
  10247. Diag(OpLoc, diag::note_assign_lhs_incomplete)
  10248. << Args[0]->getType()
  10249. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10250. }
  10251. } else {
  10252. // This is an erroneous use of an operator which can be overloaded by
  10253. // a non-member function. Check for non-member operators which were
  10254. // defined too late to be candidates.
  10255. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  10256. // FIXME: Recover by calling the found function.
  10257. return ExprError();
  10258. // No viable function; try to create a built-in operation, which will
  10259. // produce an error. Then, show the non-viable candidates.
  10260. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10261. }
  10262. assert(Result.isInvalid() &&
  10263. "C++ binary operator overloading is missing candidates!");
  10264. if (Result.isInvalid())
  10265. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10266. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10267. return Result;
  10268. }
  10269. case OR_Ambiguous:
  10270. // HLSL Change Starts
  10271. if (getLangOpts().HLSL)
  10272. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10273. // HLSL Change Ends
  10274. Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
  10275. << BinaryOperator::getOpcodeStr(Opc)
  10276. << Args[0]->getType() << Args[1]->getType()
  10277. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10278. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10279. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10280. return ExprError();
  10281. case OR_Deleted:
  10282. if (isImplicitlyDeleted(Best->Function)) {
  10283. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10284. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  10285. << Context.getRecordType(Method->getParent())
  10286. << getSpecialMember(Method);
  10287. // The user probably meant to call this special member. Just
  10288. // explain why it's deleted.
  10289. NoteDeletedFunction(Method);
  10290. return ExprError();
  10291. } else {
  10292. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10293. << Best->Function->isDeleted()
  10294. << BinaryOperator::getOpcodeStr(Opc)
  10295. << getDeletedOrUnavailableSuffix(Best->Function)
  10296. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10297. }
  10298. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10299. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  10300. return ExprError();
  10301. }
  10302. // We matched a built-in operator; build it.
  10303. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  10304. }
  10305. ExprResult
  10306. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  10307. SourceLocation RLoc,
  10308. Expr *Base, Expr *Idx) {
  10309. Expr *Args[2] = { Base, Idx };
  10310. DeclarationName OpName =
  10311. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  10312. // If either side is type-dependent, create an appropriate dependent
  10313. // expression.
  10314. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  10315. CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
  10316. // CHECKME: no 'operator' keyword?
  10317. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  10318. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10319. UnresolvedLookupExpr *Fn
  10320. = UnresolvedLookupExpr::Create(Context, NamingClass,
  10321. NestedNameSpecifierLoc(), OpNameInfo,
  10322. /*ADL*/ true, /*Overloaded*/ false,
  10323. UnresolvedSetIterator(),
  10324. UnresolvedSetIterator());
  10325. // Can't add any actual overloads yet
  10326. return new (Context)
  10327. CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
  10328. Context.DependentTy, VK_RValue, RLoc, false);
  10329. }
  10330. // Handle placeholders on both operands.
  10331. if (checkPlaceholderForOverload(*this, Args[0]))
  10332. return ExprError();
  10333. if (checkPlaceholderForOverload(*this, Args[1]))
  10334. return ExprError();
  10335. // Build an empty overload set.
  10336. OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
  10337. // Subscript can only be overloaded as a member function.
  10338. // Add operator candidates that are member functions.
  10339. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10340. // Add builtin operator candidates.
  10341. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
  10342. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10343. // Perform overload resolution.
  10344. OverloadCandidateSet::iterator Best;
  10345. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  10346. case OR_Success: {
  10347. // We found a built-in operator or an overloaded operator.
  10348. FunctionDecl *FnDecl = Best->Function;
  10349. if (FnDecl) {
  10350. // We matched an overloaded operator. Build a call to that
  10351. // operator.
  10352. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  10353. // Convert the arguments.
  10354. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  10355. ExprResult Arg0 =
  10356. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
  10357. Best->FoundDecl, Method);
  10358. if (Arg0.isInvalid())
  10359. return ExprError();
  10360. Args[0] = Arg0.get();
  10361. // Convert the arguments.
  10362. ExprResult InputInit
  10363. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10364. Context,
  10365. FnDecl->getParamDecl(0)),
  10366. SourceLocation(),
  10367. Args[1]);
  10368. if (InputInit.isInvalid())
  10369. return ExprError();
  10370. Args[1] = InputInit.getAs<Expr>();
  10371. // Build the actual expression node.
  10372. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  10373. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  10374. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  10375. Best->FoundDecl,
  10376. HadMultipleCandidates,
  10377. OpLocInfo.getLoc(),
  10378. OpLocInfo.getInfo());
  10379. if (FnExpr.isInvalid())
  10380. return ExprError();
  10381. // Determine the result type
  10382. QualType ResultTy = FnDecl->getReturnType();
  10383. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10384. ResultTy = ResultTy.getNonLValueExprType(Context);
  10385. CXXOperatorCallExpr *TheCall =
  10386. new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
  10387. FnExpr.get(), Args,
  10388. ResultTy, VK, RLoc,
  10389. false);
  10390. if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
  10391. return ExprError();
  10392. return MaybeBindToTemporary(TheCall);
  10393. } else {
  10394. // We matched a built-in operator. Convert the arguments, then
  10395. // break out so that we will build the appropriate built-in
  10396. // operator node.
  10397. ExprResult ArgsRes0 =
  10398. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  10399. Best->Conversions[0], AA_Passing);
  10400. if (ArgsRes0.isInvalid())
  10401. return ExprError();
  10402. Args[0] = ArgsRes0.get();
  10403. ExprResult ArgsRes1 =
  10404. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  10405. Best->Conversions[1], AA_Passing);
  10406. if (ArgsRes1.isInvalid())
  10407. return ExprError();
  10408. Args[1] = ArgsRes1.get();
  10409. break;
  10410. }
  10411. }
  10412. case OR_No_Viable_Function: {
  10413. if (CandidateSet.empty())
  10414. Diag(LLoc, diag::err_ovl_no_oper)
  10415. << Args[0]->getType() << /*subscript*/ 0
  10416. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10417. else
  10418. Diag(LLoc, diag::err_ovl_no_viable_subscript)
  10419. << Args[0]->getType()
  10420. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10421. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10422. "[]", LLoc);
  10423. return ExprError();
  10424. }
  10425. case OR_Ambiguous:
  10426. Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
  10427. << "[]"
  10428. << Args[0]->getType() << Args[1]->getType()
  10429. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10430. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  10431. "[]", LLoc);
  10432. return ExprError();
  10433. case OR_Deleted:
  10434. Diag(LLoc, diag::err_ovl_deleted_oper)
  10435. << Best->Function->isDeleted() << "[]"
  10436. << getDeletedOrUnavailableSuffix(Best->Function)
  10437. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  10438. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  10439. "[]", LLoc);
  10440. return ExprError();
  10441. }
  10442. // We matched a built-in operator; build it.
  10443. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  10444. }
  10445. /// BuildCallToMemberFunction - Build a call to a member
  10446. /// function. MemExpr is the expression that refers to the member
  10447. /// function (and includes the object parameter), Args/NumArgs are the
  10448. /// arguments to the function call (not including the object
  10449. /// parameter). The caller needs to validate that the member
  10450. /// expression refers to a non-static member function or an overloaded
  10451. /// member function.
  10452. ExprResult
  10453. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  10454. SourceLocation LParenLoc,
  10455. MultiExprArg Args,
  10456. SourceLocation RParenLoc) {
  10457. assert(MemExprE->getType() == Context.BoundMemberTy ||
  10458. MemExprE->getType() == Context.OverloadTy);
  10459. // Dig out the member expression. This holds both the object
  10460. // argument and the member function we're referring to.
  10461. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  10462. // Determine whether this is a call to a pointer-to-member function.
  10463. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  10464. assert(op->getType() == Context.BoundMemberTy);
  10465. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  10466. QualType fnType =
  10467. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  10468. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  10469. QualType resultType = proto->getCallResultType(Context);
  10470. ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
  10471. // Check that the object type isn't more qualified than the
  10472. // member function we're calling.
  10473. Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
  10474. QualType objectType = op->getLHS()->getType();
  10475. if (op->getOpcode() == BO_PtrMemI)
  10476. objectType = objectType->castAs<PointerType>()->getPointeeType();
  10477. Qualifiers objectQuals = objectType.getQualifiers();
  10478. Qualifiers difference = objectQuals - funcQuals;
  10479. difference.removeObjCGCAttr();
  10480. difference.removeAddressSpace();
  10481. if (difference) {
  10482. std::string qualsString = difference.getAsString();
  10483. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  10484. << fnType.getUnqualifiedType()
  10485. << qualsString
  10486. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  10487. }
  10488. if (resultType->isMemberPointerType())
  10489. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10490. RequireCompleteType(LParenLoc, resultType, 0);
  10491. CXXMemberCallExpr *call
  10492. = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10493. resultType, valueKind, RParenLoc);
  10494. if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
  10495. call, nullptr))
  10496. return ExprError();
  10497. if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
  10498. return ExprError();
  10499. if (CheckOtherCall(call, proto))
  10500. return ExprError();
  10501. return MaybeBindToTemporary(call);
  10502. }
  10503. if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
  10504. return new (Context)
  10505. CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
  10506. UnbridgedCastsSet UnbridgedCasts;
  10507. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10508. return ExprError();
  10509. MemberExpr *MemExpr;
  10510. CXXMethodDecl *Method = nullptr;
  10511. DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
  10512. NestedNameSpecifier *Qualifier = nullptr;
  10513. if (isa<MemberExpr>(NakedMemExpr)) {
  10514. MemExpr = cast<MemberExpr>(NakedMemExpr);
  10515. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  10516. FoundDecl = MemExpr->getFoundDecl();
  10517. Qualifier = MemExpr->getQualifier();
  10518. UnbridgedCasts.restore();
  10519. } else {
  10520. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  10521. Qualifier = UnresExpr->getQualifier();
  10522. QualType ObjectType = UnresExpr->getBaseType();
  10523. Expr::Classification ObjectClassification
  10524. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  10525. : UnresExpr->getBase()->Classify(Context);
  10526. // Add overload candidates
  10527. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
  10528. OverloadCandidateSet::CSK_Normal);
  10529. // FIXME: avoid copy.
  10530. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  10531. if (UnresExpr->hasExplicitTemplateArgs()) {
  10532. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  10533. TemplateArgs = &TemplateArgsBuffer;
  10534. }
  10535. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  10536. E = UnresExpr->decls_end(); I != E; ++I) {
  10537. NamedDecl *Func = *I;
  10538. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  10539. if (isa<UsingShadowDecl>(Func))
  10540. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  10541. // Microsoft supports direct constructor calls.
  10542. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  10543. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
  10544. Args, CandidateSet);
  10545. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  10546. // If explicit template arguments were provided, we can't call a
  10547. // non-template member function.
  10548. if (TemplateArgs)
  10549. continue;
  10550. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  10551. ObjectClassification, Args, CandidateSet,
  10552. /*SuppressUserConversions=*/false);
  10553. } else {
  10554. AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
  10555. I.getPair(), ActingDC, TemplateArgs,
  10556. ObjectType, ObjectClassification,
  10557. Args, CandidateSet,
  10558. /*SuppressUsedConversions=*/false);
  10559. }
  10560. }
  10561. DeclarationName DeclName = UnresExpr->getMemberName();
  10562. UnbridgedCasts.restore();
  10563. OverloadCandidateSet::iterator Best;
  10564. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
  10565. Best)) {
  10566. case OR_Success:
  10567. Method = cast<CXXMethodDecl>(Best->Function);
  10568. FoundDecl = Best->FoundDecl;
  10569. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  10570. if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
  10571. return ExprError();
  10572. // If FoundDecl is different from Method (such as if one is a template
  10573. // and the other a specialization), make sure DiagnoseUseOfDecl is
  10574. // called on both.
  10575. // FIXME: This would be more comprehensively addressed by modifying
  10576. // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
  10577. // being used.
  10578. if (Method != FoundDecl.getDecl() &&
  10579. DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
  10580. return ExprError();
  10581. break;
  10582. case OR_No_Viable_Function:
  10583. Diag(UnresExpr->getMemberLoc(),
  10584. diag::err_ovl_no_viable_member_function_in_call)
  10585. << DeclName << MemExprE->getSourceRange();
  10586. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, StringRef(), UnresExpr->getMemberLoc()); // HLSL Change - add member loc
  10587. // FIXME: Leaking incoming expressions!
  10588. return ExprError();
  10589. case OR_Ambiguous:
  10590. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
  10591. << DeclName << MemExprE->getSourceRange();
  10592. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10593. // FIXME: Leaking incoming expressions!
  10594. return ExprError();
  10595. case OR_Deleted:
  10596. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
  10597. << Best->Function->isDeleted()
  10598. << DeclName
  10599. << getDeletedOrUnavailableSuffix(Best->Function)
  10600. << MemExprE->getSourceRange();
  10601. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10602. // FIXME: Leaking incoming expressions!
  10603. return ExprError();
  10604. }
  10605. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  10606. // If overload resolution picked a static member, build a
  10607. // non-member call based on that function.
  10608. if (Method->isStatic()) {
  10609. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
  10610. RParenLoc);
  10611. }
  10612. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  10613. }
  10614. QualType ResultType = Method->getReturnType();
  10615. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  10616. ResultType = ResultType.getNonLValueExprType(Context);
  10617. assert(Method && "Member call to something that isn't a method?");
  10618. CXXMemberCallExpr *TheCall =
  10619. new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
  10620. ResultType, VK, RParenLoc);
  10621. // (CUDA B.1): Check for invalid calls between targets.
  10622. if (getLangOpts().CUDA) {
  10623. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
  10624. if (CheckCUDATarget(Caller, Method)) {
  10625. Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
  10626. << IdentifyCUDATarget(Method) << Method->getIdentifier()
  10627. << IdentifyCUDATarget(Caller);
  10628. return ExprError();
  10629. }
  10630. }
  10631. }
  10632. // Check for a valid return type.
  10633. if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
  10634. TheCall, Method))
  10635. return ExprError();
  10636. // Convert the object argument (for a non-static member function call).
  10637. // We only need to do this if there was actually an overload; otherwise
  10638. // it was done at lookup.
  10639. if (!Method->isStatic()) {
  10640. ExprResult ObjectArg =
  10641. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  10642. FoundDecl, Method);
  10643. if (ObjectArg.isInvalid())
  10644. return ExprError();
  10645. MemExpr->setBase(ObjectArg.get());
  10646. }
  10647. // Convert the rest of the arguments
  10648. const FunctionProtoType *Proto =
  10649. Method->getType()->getAs<FunctionProtoType>();
  10650. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
  10651. RParenLoc))
  10652. return ExprError();
  10653. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10654. if (CheckFunctionCall(Method, TheCall, Proto))
  10655. return ExprError();
  10656. if ((isa<CXXConstructorDecl>(CurContext) ||
  10657. isa<CXXDestructorDecl>(CurContext)) &&
  10658. TheCall->getMethodDecl()->isPure()) {
  10659. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  10660. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
  10661. Diag(MemExpr->getLocStart(),
  10662. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  10663. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  10664. << MD->getParent()->getDeclName();
  10665. Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
  10666. }
  10667. }
  10668. return MaybeBindToTemporary(TheCall);
  10669. }
  10670. /// BuildCallToObjectOfClassType - Build a call to an object of class
  10671. /// type (C++ [over.call.object]), which can end up invoking an
  10672. /// overloaded function call operator (@c operator()) or performing a
  10673. /// user-defined conversion on the object argument.
  10674. ExprResult
  10675. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  10676. SourceLocation LParenLoc,
  10677. MultiExprArg Args,
  10678. SourceLocation RParenLoc) {
  10679. if (checkPlaceholderForOverload(*this, Obj))
  10680. return ExprError();
  10681. ExprResult Object = Obj;
  10682. UnbridgedCastsSet UnbridgedCasts;
  10683. if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
  10684. return ExprError();
  10685. assert(Object.get()->getType()->isRecordType() &&
  10686. "Requires object type argument");
  10687. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  10688. // C++ [over.call.object]p1:
  10689. // If the primary-expression E in the function call syntax
  10690. // evaluates to a class object of type "cv T", then the set of
  10691. // candidate functions includes at least the function call
  10692. // operators of T. The function call operators of T are obtained by
  10693. // ordinary lookup of the name operator() in the context of
  10694. // (E).operator().
  10695. OverloadCandidateSet CandidateSet(LParenLoc,
  10696. OverloadCandidateSet::CSK_Operator);
  10697. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  10698. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  10699. diag::err_incomplete_object_call, Object.get()))
  10700. return true;
  10701. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  10702. LookupQualifiedName(R, Record->getDecl());
  10703. R.suppressDiagnostics();
  10704. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10705. Oper != OperEnd; ++Oper) {
  10706. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  10707. Object.get()->Classify(Context),
  10708. Args, CandidateSet,
  10709. /*SuppressUserConversions=*/ false);
  10710. }
  10711. // C++ [over.call.object]p2:
  10712. // In addition, for each (non-explicit in C++0x) conversion function
  10713. // declared in T of the form
  10714. //
  10715. // operator conversion-type-id () cv-qualifier;
  10716. //
  10717. // where cv-qualifier is the same cv-qualification as, or a
  10718. // greater cv-qualification than, cv, and where conversion-type-id
  10719. // denotes the type "pointer to function of (P1,...,Pn) returning
  10720. // R", or the type "reference to pointer to function of
  10721. // (P1,...,Pn) returning R", or the type "reference to function
  10722. // of (P1,...,Pn) returning R", a surrogate call function [...]
  10723. // is also considered as a candidate function. Similarly,
  10724. // surrogate call functions are added to the set of candidate
  10725. // functions for each conversion function declared in an
  10726. // accessible base class provided the function is not hidden
  10727. // within T by another intervening declaration.
  10728. const auto &Conversions =
  10729. cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  10730. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  10731. NamedDecl *D = *I;
  10732. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  10733. if (isa<UsingShadowDecl>(D))
  10734. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  10735. // Skip over templated conversion functions; they aren't
  10736. // surrogates.
  10737. if (isa<FunctionTemplateDecl>(D))
  10738. continue;
  10739. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  10740. if (!Conv->isExplicit()) {
  10741. // Strip the reference type (if any) and then the pointer type (if
  10742. // any) to get down to what might be a function type.
  10743. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  10744. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  10745. ConvType = ConvPtrType->getPointeeType();
  10746. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  10747. {
  10748. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  10749. Object.get(), Args, CandidateSet);
  10750. }
  10751. }
  10752. }
  10753. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10754. // Perform overload resolution.
  10755. OverloadCandidateSet::iterator Best;
  10756. switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
  10757. Best)) {
  10758. case OR_Success:
  10759. // Overload resolution succeeded; we'll build the appropriate call
  10760. // below.
  10761. break;
  10762. case OR_No_Viable_Function:
  10763. if (CandidateSet.empty())
  10764. Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
  10765. << Object.get()->getType() << /*call*/ 1
  10766. << Object.get()->getSourceRange();
  10767. else
  10768. Diag(Object.get()->getLocStart(),
  10769. diag::err_ovl_no_viable_object_call)
  10770. << Object.get()->getType() << Object.get()->getSourceRange();
  10771. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10772. break;
  10773. case OR_Ambiguous:
  10774. Diag(Object.get()->getLocStart(),
  10775. diag::err_ovl_ambiguous_object_call)
  10776. << Object.get()->getType() << Object.get()->getSourceRange();
  10777. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  10778. break;
  10779. case OR_Deleted:
  10780. Diag(Object.get()->getLocStart(),
  10781. diag::err_ovl_deleted_object_call)
  10782. << Best->Function->isDeleted()
  10783. << Object.get()->getType()
  10784. << getDeletedOrUnavailableSuffix(Best->Function)
  10785. << Object.get()->getSourceRange();
  10786. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  10787. break;
  10788. }
  10789. if (Best == CandidateSet.end())
  10790. return true;
  10791. UnbridgedCasts.restore();
  10792. if (Best->Function == nullptr) {
  10793. // Since there is no function declaration, this is one of the
  10794. // surrogate candidates. Dig out the conversion function.
  10795. CXXConversionDecl *Conv
  10796. = cast<CXXConversionDecl>(
  10797. Best->Conversions[0].UserDefined.ConversionFunction);
  10798. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
  10799. Best->FoundDecl);
  10800. if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
  10801. return ExprError();
  10802. assert(Conv == Best->FoundDecl.getDecl() &&
  10803. "Found Decl & conversion-to-functionptr should be same, right?!");
  10804. // We selected one of the surrogate functions that converts the
  10805. // object parameter to a function pointer. Perform the conversion
  10806. // on the object argument, then let ActOnCallExpr finish the job.
  10807. // Create an implicit member expr to refer to the conversion operator.
  10808. // and then call it.
  10809. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  10810. Conv, HadMultipleCandidates);
  10811. if (Call.isInvalid())
  10812. return ExprError();
  10813. // Record usage of conversion in an implicit cast.
  10814. Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
  10815. CK_UserDefinedConversion, Call.get(),
  10816. nullptr, VK_RValue);
  10817. return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
  10818. }
  10819. CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
  10820. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  10821. // that calls this method, using Object for the implicit object
  10822. // parameter and passing along the remaining arguments.
  10823. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10824. // An error diagnostic has already been printed when parsing the declaration.
  10825. if (Method->isInvalidDecl())
  10826. return ExprError();
  10827. const FunctionProtoType *Proto =
  10828. Method->getType()->getAs<FunctionProtoType>();
  10829. unsigned NumParams = Proto->getNumParams();
  10830. DeclarationNameInfo OpLocInfo(
  10831. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  10832. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  10833. ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10834. HadMultipleCandidates,
  10835. OpLocInfo.getLoc(),
  10836. OpLocInfo.getInfo());
  10837. if (NewFn.isInvalid())
  10838. return true;
  10839. // Build the full argument list for the method call (the implicit object
  10840. // parameter is placed at the beginning of the list).
  10841. std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
  10842. MethodArgs[0] = Object.get();
  10843. std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
  10844. // Once we've built TheCall, all of the expressions are properly
  10845. // owned.
  10846. QualType ResultTy = Method->getReturnType();
  10847. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10848. ResultTy = ResultTy.getNonLValueExprType(Context);
  10849. CXXOperatorCallExpr *TheCall = new (Context)
  10850. CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
  10851. llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
  10852. ResultTy, VK, RParenLoc, false);
  10853. MethodArgs.reset();
  10854. if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
  10855. return true;
  10856. // We may have default arguments. If so, we need to allocate more
  10857. // slots in the call for them.
  10858. if (Args.size() < NumParams)
  10859. TheCall->setNumArgs(Context, NumParams + 1);
  10860. bool IsError = false;
  10861. // Initialize the implicit object parameter.
  10862. ExprResult ObjRes =
  10863. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
  10864. Best->FoundDecl, Method);
  10865. if (ObjRes.isInvalid())
  10866. IsError = true;
  10867. else
  10868. Object = ObjRes;
  10869. TheCall->setArg(0, Object.get());
  10870. // Check the argument types.
  10871. for (unsigned i = 0; i != NumParams; i++) {
  10872. Expr *Arg;
  10873. if (i < Args.size()) {
  10874. Arg = Args[i];
  10875. // Pass the argument.
  10876. ExprResult InputInit
  10877. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  10878. Context,
  10879. Method->getParamDecl(i)),
  10880. SourceLocation(), Arg);
  10881. IsError |= InputInit.isInvalid();
  10882. Arg = InputInit.getAs<Expr>();
  10883. } else {
  10884. ExprResult DefArg
  10885. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  10886. if (DefArg.isInvalid()) {
  10887. IsError = true;
  10888. break;
  10889. }
  10890. Arg = DefArg.getAs<Expr>();
  10891. }
  10892. TheCall->setArg(i + 1, Arg);
  10893. }
  10894. // If this is a variadic call, handle args passed through "...".
  10895. if (Proto->isVariadic()) {
  10896. // Promote the arguments (C99 6.5.2.2p7).
  10897. for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
  10898. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  10899. nullptr);
  10900. IsError |= Arg.isInvalid();
  10901. TheCall->setArg(i + 1, Arg.get());
  10902. }
  10903. }
  10904. if (IsError) return true;
  10905. DiagnoseSentinelCalls(Method, LParenLoc, Args);
  10906. if (CheckFunctionCall(Method, TheCall, Proto))
  10907. return true;
  10908. return MaybeBindToTemporary(TheCall);
  10909. }
  10910. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  10911. /// (if one exists), where @c Base is an expression of class type and
  10912. /// @c Member is the name of the member we're trying to find.
  10913. ExprResult
  10914. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
  10915. bool *NoArrowOperatorFound) {
  10916. assert(Base->getType()->isRecordType() &&
  10917. "left-hand side must have class type");
  10918. if (checkPlaceholderForOverload(*this, Base))
  10919. return ExprError();
  10920. SourceLocation Loc = Base->getExprLoc();
  10921. // C++ [over.ref]p1:
  10922. //
  10923. // [...] An expression x->m is interpreted as (x.operator->())->m
  10924. // for a class object x of type T if T::operator->() exists and if
  10925. // the operator is selected as the best match function by the
  10926. // overload resolution mechanism (13.3).
  10927. DeclarationName OpName =
  10928. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  10929. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
  10930. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  10931. if (RequireCompleteType(Loc, Base->getType(),
  10932. diag::err_typecheck_incomplete_tag, Base))
  10933. return ExprError();
  10934. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  10935. LookupQualifiedName(R, BaseRecord->getDecl());
  10936. R.suppressDiagnostics();
  10937. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  10938. Oper != OperEnd; ++Oper) {
  10939. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  10940. None, CandidateSet, /*SuppressUserConversions=*/false);
  10941. }
  10942. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  10943. // Perform overload resolution.
  10944. OverloadCandidateSet::iterator Best;
  10945. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  10946. case OR_Success:
  10947. // Overload resolution succeeded; we'll build the call below.
  10948. break;
  10949. case OR_No_Viable_Function:
  10950. if (CandidateSet.empty()) {
  10951. QualType BaseType = Base->getType();
  10952. if (NoArrowOperatorFound) {
  10953. // Report this specific error to the caller instead of emitting a
  10954. // diagnostic, as requested.
  10955. *NoArrowOperatorFound = true;
  10956. return ExprError();
  10957. }
  10958. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  10959. << BaseType << Base->getSourceRange();
  10960. if (BaseType->isRecordType() && !BaseType->isPointerType()) {
  10961. Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
  10962. << FixItHint::CreateReplacement(OpLoc, ".");
  10963. }
  10964. } else
  10965. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  10966. << "operator->" << Base->getSourceRange();
  10967. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10968. return ExprError();
  10969. case OR_Ambiguous:
  10970. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  10971. << "->" << Base->getType() << Base->getSourceRange();
  10972. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
  10973. return ExprError();
  10974. case OR_Deleted:
  10975. Diag(OpLoc, diag::err_ovl_deleted_oper)
  10976. << Best->Function->isDeleted()
  10977. << "->"
  10978. << getDeletedOrUnavailableSuffix(Best->Function)
  10979. << Base->getSourceRange();
  10980. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  10981. return ExprError();
  10982. }
  10983. CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
  10984. // Convert the object parameter.
  10985. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  10986. ExprResult BaseResult =
  10987. PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
  10988. Best->FoundDecl, Method);
  10989. if (BaseResult.isInvalid())
  10990. return ExprError();
  10991. Base = BaseResult.get();
  10992. // Build the operator call.
  10993. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
  10994. HadMultipleCandidates, OpLoc);
  10995. if (FnExpr.isInvalid())
  10996. return ExprError();
  10997. QualType ResultTy = Method->getReturnType();
  10998. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  10999. ResultTy = ResultTy.getNonLValueExprType(Context);
  11000. CXXOperatorCallExpr *TheCall =
  11001. new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
  11002. Base, ResultTy, VK, OpLoc, false);
  11003. if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
  11004. return ExprError();
  11005. return MaybeBindToTemporary(TheCall);
  11006. }
  11007. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  11008. /// a literal operator described by the provided lookup results.
  11009. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  11010. DeclarationNameInfo &SuffixInfo,
  11011. ArrayRef<Expr*> Args,
  11012. SourceLocation LitEndLoc,
  11013. TemplateArgumentListInfo *TemplateArgs) {
  11014. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  11015. OverloadCandidateSet CandidateSet(UDSuffixLoc,
  11016. OverloadCandidateSet::CSK_Normal);
  11017. AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
  11018. /*SuppressUserConversions=*/true);
  11019. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  11020. // Perform overload resolution. This will usually be trivial, but might need
  11021. // to perform substitutions for a literal operator template.
  11022. OverloadCandidateSet::iterator Best;
  11023. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  11024. case OR_Success:
  11025. case OR_Deleted:
  11026. break;
  11027. case OR_No_Viable_Function:
  11028. Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
  11029. << R.getLookupName();
  11030. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  11031. return ExprError();
  11032. case OR_Ambiguous:
  11033. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  11034. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  11035. return ExprError();
  11036. }
  11037. FunctionDecl *FD = Best->Function;
  11038. ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
  11039. HadMultipleCandidates,
  11040. SuffixInfo.getLoc(),
  11041. SuffixInfo.getInfo());
  11042. if (Fn.isInvalid())
  11043. return true;
  11044. // Check the argument types. This should almost always be a no-op, except
  11045. // that array-to-pointer decay is applied to string literals.
  11046. Expr *ConvArgs[2];
  11047. for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
  11048. ExprResult InputInit = PerformCopyInitialization(
  11049. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  11050. SourceLocation(), Args[ArgIdx]);
  11051. if (InputInit.isInvalid())
  11052. return true;
  11053. ConvArgs[ArgIdx] = InputInit.get();
  11054. }
  11055. QualType ResultTy = FD->getReturnType();
  11056. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  11057. ResultTy = ResultTy.getNonLValueExprType(Context);
  11058. UserDefinedLiteral *UDL =
  11059. new (Context) UserDefinedLiteral(Context, Fn.get(),
  11060. llvm::makeArrayRef(ConvArgs, Args.size()),
  11061. ResultTy, VK, LitEndLoc, UDSuffixLoc);
  11062. if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
  11063. return ExprError();
  11064. if (CheckFunctionCall(FD, UDL, nullptr))
  11065. return ExprError();
  11066. return MaybeBindToTemporary(UDL);
  11067. }
  11068. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  11069. /// given LookupResult is non-empty, it is assumed to describe a member which
  11070. /// will be invoked. Otherwise, the function will be found via argument
  11071. /// dependent lookup.
  11072. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  11073. /// otherwise CallExpr is set to ExprError() and some non-success value
  11074. /// is returned.
  11075. Sema::ForRangeStatus
  11076. Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
  11077. SourceLocation RangeLoc, VarDecl *Decl,
  11078. BeginEndFunction BEF,
  11079. const DeclarationNameInfo &NameInfo,
  11080. LookupResult &MemberLookup,
  11081. OverloadCandidateSet *CandidateSet,
  11082. Expr *Range, ExprResult *CallExpr) {
  11083. CandidateSet->clear();
  11084. if (!MemberLookup.empty()) {
  11085. ExprResult MemberRef =
  11086. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  11087. /*IsPtr=*/false, CXXScopeSpec(),
  11088. /*TemplateKWLoc=*/SourceLocation(),
  11089. /*FirstQualifierInScope=*/nullptr,
  11090. MemberLookup,
  11091. /*TemplateArgs=*/nullptr);
  11092. if (MemberRef.isInvalid()) {
  11093. *CallExpr = ExprError();
  11094. Diag(Range->getLocStart(), diag::note_in_for_range)
  11095. << RangeLoc << BEF << Range->getType();
  11096. return FRS_DiagnosticIssued;
  11097. }
  11098. *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
  11099. if (CallExpr->isInvalid()) {
  11100. *CallExpr = ExprError();
  11101. Diag(Range->getLocStart(), diag::note_in_for_range)
  11102. << RangeLoc << BEF << Range->getType();
  11103. return FRS_DiagnosticIssued;
  11104. }
  11105. } else {
  11106. UnresolvedSet<0> FoundNames;
  11107. UnresolvedLookupExpr *Fn =
  11108. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
  11109. NestedNameSpecifierLoc(), NameInfo,
  11110. /*NeedsADL=*/true, /*Overloaded=*/false,
  11111. FoundNames.begin(), FoundNames.end());
  11112. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
  11113. CandidateSet, CallExpr);
  11114. if (CandidateSet->empty() || CandidateSetError) {
  11115. *CallExpr = ExprError();
  11116. return FRS_NoViableFunction;
  11117. }
  11118. OverloadCandidateSet::iterator Best;
  11119. OverloadingResult OverloadResult =
  11120. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
  11121. if (OverloadResult == OR_No_Viable_Function) {
  11122. *CallExpr = ExprError();
  11123. return FRS_NoViableFunction;
  11124. }
  11125. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
  11126. Loc, nullptr, CandidateSet, &Best,
  11127. OverloadResult,
  11128. /*AllowTypoCorrection=*/false);
  11129. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  11130. *CallExpr = ExprError();
  11131. Diag(Range->getLocStart(), diag::note_in_for_range)
  11132. << RangeLoc << BEF << Range->getType();
  11133. return FRS_DiagnosticIssued;
  11134. }
  11135. }
  11136. return FRS_Success;
  11137. }
  11138. /// FixOverloadedFunctionReference - E is an expression that refers to
  11139. /// a C++ overloaded function (possibly with some parentheses and
  11140. /// perhaps a '&' around it). We have resolved the overloaded function
  11141. /// to the function declaration Fn, so patch up the expression E to
  11142. /// refer (possibly indirectly) to Fn. Returns the new expr.
  11143. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  11144. FunctionDecl *Fn) {
  11145. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  11146. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  11147. Found, Fn);
  11148. if (SubExpr == PE->getSubExpr())
  11149. return PE;
  11150. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  11151. }
  11152. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  11153. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  11154. Found, Fn);
  11155. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  11156. SubExpr->getType()) &&
  11157. "Implicit cast type cannot be determined from overload");
  11158. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  11159. if (SubExpr == ICE->getSubExpr())
  11160. return ICE;
  11161. return ImplicitCastExpr::Create(Context, ICE->getType(),
  11162. ICE->getCastKind(),
  11163. SubExpr, nullptr,
  11164. ICE->getValueKind());
  11165. }
  11166. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  11167. assert(UnOp->getOpcode() == UO_AddrOf &&
  11168. "Can only take the address of an overloaded function");
  11169. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  11170. if (Method->isStatic()) {
  11171. // Do nothing: static member functions aren't any different
  11172. // from non-member functions.
  11173. } else {
  11174. // Fix the subexpression, which really has to be an
  11175. // UnresolvedLookupExpr holding an overloaded member function
  11176. // or template.
  11177. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11178. Found, Fn);
  11179. if (SubExpr == UnOp->getSubExpr())
  11180. return UnOp;
  11181. assert(isa<DeclRefExpr>(SubExpr)
  11182. && "fixed to something other than a decl ref");
  11183. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  11184. && "fixed to a member ref with no nested name qualifier");
  11185. // We have taken the address of a pointer to member
  11186. // function. Perform the computation here so that we get the
  11187. // appropriate pointer to member type.
  11188. QualType ClassType
  11189. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  11190. QualType MemPtrType
  11191. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  11192. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  11193. VK_RValue, OK_Ordinary,
  11194. UnOp->getOperatorLoc());
  11195. }
  11196. }
  11197. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  11198. Found, Fn);
  11199. if (SubExpr == UnOp->getSubExpr())
  11200. return UnOp;
  11201. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  11202. Context.getPointerType(SubExpr->getType()),
  11203. VK_RValue, OK_Ordinary,
  11204. UnOp->getOperatorLoc());
  11205. }
  11206. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11207. // FIXME: avoid copy.
  11208. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11209. if (ULE->hasExplicitTemplateArgs()) {
  11210. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11211. TemplateArgs = &TemplateArgsBuffer;
  11212. }
  11213. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11214. ULE->getQualifierLoc(),
  11215. ULE->getTemplateKeywordLoc(),
  11216. Fn,
  11217. /*enclosing*/ false, // FIXME?
  11218. ULE->getNameLoc(),
  11219. Fn->getType(),
  11220. VK_LValue,
  11221. Found.getDecl(),
  11222. TemplateArgs);
  11223. MarkDeclRefReferenced(DRE);
  11224. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  11225. return DRE;
  11226. }
  11227. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  11228. // FIXME: avoid copy.
  11229. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  11230. if (MemExpr->hasExplicitTemplateArgs()) {
  11231. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  11232. TemplateArgs = &TemplateArgsBuffer;
  11233. }
  11234. Expr *Base;
  11235. // If we're filling in a static method where we used to have an
  11236. // implicit member access, rewrite to a simple decl ref.
  11237. if (MemExpr->isImplicitAccess()) {
  11238. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11239. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  11240. MemExpr->getQualifierLoc(),
  11241. MemExpr->getTemplateKeywordLoc(),
  11242. Fn,
  11243. /*enclosing*/ false,
  11244. MemExpr->getMemberLoc(),
  11245. Fn->getType(),
  11246. VK_LValue,
  11247. Found.getDecl(),
  11248. TemplateArgs);
  11249. MarkDeclRefReferenced(DRE);
  11250. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  11251. return DRE;
  11252. } else {
  11253. SourceLocation Loc = MemExpr->getMemberLoc();
  11254. if (MemExpr->getQualifier())
  11255. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  11256. CheckCXXThisCapture(Loc);
  11257. Base = new (Context) CXXThisExpr(Loc,
  11258. MemExpr->getBaseType(),
  11259. /*isImplicit=*/true);
  11260. }
  11261. } else
  11262. Base = MemExpr->getBase();
  11263. ExprValueKind valueKind;
  11264. QualType type;
  11265. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  11266. valueKind = VK_LValue;
  11267. type = Fn->getType();
  11268. } else {
  11269. valueKind = VK_RValue;
  11270. type = Context.BoundMemberTy;
  11271. }
  11272. MemberExpr *ME = MemberExpr::Create(
  11273. Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
  11274. MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
  11275. MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
  11276. OK_Ordinary);
  11277. ME->setHadMultipleCandidates(true);
  11278. MarkMemberReferenced(ME);
  11279. return ME;
  11280. }
  11281. llvm_unreachable("Invalid reference to overloaded function");
  11282. }
  11283. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  11284. DeclAccessPair Found,
  11285. FunctionDecl *Fn) {
  11286. return FixOverloadedFunctionReference(E.get(), Found, Fn);
  11287. }